diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/constant/TableConstant.java b/src/main/java/com/chaozhanggui/system/cashierservice/constant/TableConstant.java index 34717e0..43677ff 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/constant/TableConstant.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/constant/TableConstant.java @@ -21,6 +21,39 @@ public interface TableConstant { } } + class CashierCart { + public static final String ID = "-999"; + + @Getter + public enum Status { + REFUNDING("refunding"), REFUND("refund"), CLOSED("closed"), CREATE("create"), + UNPAID("unpaid"), PAYING("paying"), RETURN("return"), CANCEL("cancel"); + private final String value; + Status(String value) { + this.value = value; + } + public boolean equalsVals(String value) { + return this.value.equals(value); + } + } + + @Getter + public enum UseType { + TAKEOUT("takeout"), + DINE_IN_AFTER("dine-in-after"), + DINE_IN_BEFORE("dine-in-before"); + private final String value; + + UseType(String value) { + this.value = value; + } + + public boolean equalsVals(String value) { + return this.value.equals(value); + } + } + } + class OrderInfo { @Getter public enum Status { @@ -31,6 +64,9 @@ public interface TableConstant { Status(String value) { this.value = value; } + public boolean equalsVals(String value) { + return this.value.equals(value); + } } @Getter diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/controller/OrderController.java b/src/main/java/com/chaozhanggui/system/cashierservice/controller/OrderController.java index be25987..98abe4d 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/controller/OrderController.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/controller/OrderController.java @@ -2,6 +2,7 @@ package com.chaozhanggui.system.cashierservice.controller; import cn.hutool.core.util.ObjectUtil; import com.alibaba.fastjson.JSONObject; +import com.chaozhanggui.system.cashierservice.entity.dto.CreateOrderDTO; import com.chaozhanggui.system.cashierservice.redis.RedisCst; import com.chaozhanggui.system.cashierservice.service.CartService; import com.chaozhanggui.system.cashierservice.service.OrderService; @@ -34,9 +35,9 @@ public class OrderController { * @return */ @PostMapping("/creatOrder") - public Result createOrder(@RequestHeader String environment, @RequestBody JSONObject jsonObject){ - jsonObject.put("environment",environment); - return Utils.runFunAndCheckKey(() -> cartService.createOrder(jsonObject), stringRedisTemplate, RedisCst.getLockKey("CREATE_ORDER_KEY")); + public Result createOrder(@RequestHeader String environment, @RequestBody CreateOrderDTO createOrderDTO){ + createOrderDTO.setEnvironment(environment); + return Utils.runFunAndCheckKey(() -> cartService.createOrder(createOrderDTO), stringRedisTemplate, RedisCst.getLockKey("CREATE_ORDER_KEY")); // return orderService.createOrder(shopTable.getTableId(),shopTable.getShopId(),shopTable.getUserId()); } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbProductMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbProductMapper.java index 9e33d9a..367c462 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbProductMapper.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbProductMapper.java @@ -48,4 +48,7 @@ public interface TbProductMapper { @Update("update tb_product set stock_number=stock_number-#{num} WHERE id=#{id}") int decrStockUnCheck(@Param("id") String id, @Param("num") Integer num); + + @Update("update tb_product set stock_number=stock_number+#{addNum} WHERE id=#{id}") + int incrStock(@Param("id") Integer id, @Param("addNum") Integer addNum); } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbCashierCart.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbCashierCart.java index d978055..2c3d94b 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbCashierCart.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbCashierCart.java @@ -71,6 +71,9 @@ public class TbCashierCart implements Serializable { private String useType; private Integer placeNum; + // 使用的优惠券id + private Integer userCouponId; + private static final long serialVersionUID = 1L; public String getSkuName() { diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbOrderInfo.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbOrderInfo.java index f87e7f4..8bb9fb8 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbOrderInfo.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbOrderInfo.java @@ -126,14 +126,14 @@ public class TbOrderInfo implements Serializable { private BigDecimal seatAmount; private BigDecimal pointsDiscountAmount; private Integer pointsNum; - // 用户优惠券id - private String activateInInfoList; - private BigDecimal activateInDiscountAmount; //根据状态返回 需付款 已付款 未付款 已退 @TableField(exist = false) private String description; + private BigDecimal fullCouponDiscountAmount; + private BigDecimal productCouponDiscountAmount; + private String couponInfoList; public void setDescription(String shopName) { this.shopName = shopName; @@ -220,4 +220,6 @@ public class TbOrderInfo implements Serializable { public String getEatModel() { return TableConstant.OrderInfo.UseType.TAKEOUT.equalsVals(this.getUseType()) ? TableConstant.ShopInfo.EatModel.TAKEOUT.getValue() : TableConstant.ShopInfo.EatModel.DINE_IN.getValue(); } + + } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbShopUser.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbShopUser.java index e4d6a24..44762d1 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbShopUser.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbShopUser.java @@ -1,11 +1,14 @@ package com.chaozhanggui.system.cashierservice.entity; +import com.baomidou.mybatisplus.annotation.TableField; +import lombok.Data; import org.springframework.data.annotation.Transient; import java.io.Serializable; import java.math.BigDecimal; import java.sql.Timestamp; +@Data public class TbShopUser implements Serializable { private String id; @@ -66,299 +69,22 @@ public class TbShopUser implements Serializable { private Long updatedAt; private String miniOpenId; + @TableField(exist = false) private String shopName=""; + @TableField(exist = false) private String lat=""; + @TableField(exist = false) private String lng=""; + @TableField(exist = false) private String address=""; @Transient + @TableField(exist = false) private String isUser; private Timestamp joinTime; - - - private static final long serialVersionUID = 1L; - public String getId() { - return id; - } - public void setId(String id) { - this.id = id == null ? null : id.trim(); - } - - public BigDecimal getAmount() { - return amount; - } - - public void setAmount(BigDecimal amount) { - this.amount = amount; - } - - public BigDecimal getCreditAmount() { - return creditAmount; - } - - public void setCreditAmount(BigDecimal creditAmount) { - this.creditAmount = creditAmount; - } - - public BigDecimal getConsumeAmount() { - return consumeAmount; - } - - public void setConsumeAmount(BigDecimal consumeAmount) { - this.consumeAmount = consumeAmount; - } - - public Integer getConsumeNumber() { - return consumeNumber; - } - - public void setConsumeNumber(Integer consumeNumber) { - this.consumeNumber = consumeNumber; - } - - public BigDecimal getLevelConsume() { - return levelConsume; - } - - public void setLevelConsume(BigDecimal levelConsume) { - this.levelConsume = levelConsume; - } - - public Byte getStatus() { - return status; - } - - public void setStatus(Byte status) { - this.status = status; - } - - public String getMerchantId() { - return merchantId; - } - - public void setMerchantId(String merchantId) { - this.merchantId = merchantId == null ? null : merchantId.trim(); - } - - public String getShopId() { - return shopId; - } - - public void setShopId(String shopId) { - this.shopId = shopId == null ? null : shopId.trim(); - } - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId == null ? null : userId.trim(); - } - - public String getParentId() { - return parentId; - } - - public void setParentId(String parentId) { - this.parentId = parentId == null ? null : parentId.trim(); - } - - public String getParentLevel() { - return parentLevel; - } - - public void setParentLevel(String parentLevel) { - this.parentLevel = parentLevel == null ? null : parentLevel.trim(); - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name == null ? null : name.trim(); - } - - public String getHeadImg() { - return headImg; - } - - public void setHeadImg(String headImg) { - this.headImg = headImg == null ? null : headImg.trim(); - } - - public Byte getSex() { - return sex; - } - - public void setSex(Byte sex) { - this.sex = sex; - } - - public String getBirthDay() { - return birthDay; - } - - public void setBirthDay(String birthDay) { - this.birthDay = birthDay == null ? null : birthDay.trim(); - } - - public String getTelephone() { - return telephone; - } - - public void setTelephone(String telephone) { - this.telephone = telephone == null ? null : telephone.trim(); - } - - public Byte getIsVip() { - return isVip; - } - - public void setIsVip(Byte isVip) { - this.isVip = isVip; - } - - public String getCode() { - return code; - } - - public void setCode(String code) { - this.code = code == null ? null : code.trim(); - } - - public String getDynamicCode() { - return dynamicCode; - } - - public void setDynamicCode(String dynamicCode) { - this.dynamicCode = dynamicCode; - } - - - public Byte getIsAttention() { - return isAttention; - } - - public void setIsAttention(Byte isAttention) { - this.isAttention = isAttention; - } - - public Integer getAttentionAt() { - return attentionAt; - } - - public void setAttentionAt(Integer attentionAt) { - this.attentionAt = attentionAt; - } - - public Byte getIsShareholder() { - return isShareholder; - } - - public void setIsShareholder(Byte isShareholder) { - this.isShareholder = isShareholder; - } - - public Byte getLevel() { - return level; - } - - public void setLevel(Byte level) { - this.level = level; - } - - public String getDistributeType() { - return distributeType; - } - - public void setDistributeType(String distributeType) { - this.distributeType = distributeType == null ? null : distributeType.trim(); - } - - public Integer getSort() { - return sort; - } - - public void setSort(Integer sort) { - this.sort = sort; - } - - public Long getCreatedAt() { - return createdAt; - } - - public void setCreatedAt(Long createdAt) { - this.createdAt = createdAt; - } - - public Long getUpdatedAt() { - return updatedAt; - } - - public void setUpdatedAt(Long updatedAt) { - this.updatedAt = updatedAt; - } - - public String getMiniOpenId() { - return miniOpenId; - } - - public String getShopName() { - return shopName; - } - - public void setShopName(String shopName) { - this.shopName = shopName; - } - - public void setMiniOpenId(String miniOpenId) { - this.miniOpenId = miniOpenId == null ? null : miniOpenId.trim(); - } - - public String getIsUser() { - return isUser; - } - - public void setIsUser(String isUser) { - this.isUser = isUser; - } - - public String getLat() { - return lat; - } - - public void setLat(String lat) { - this.lat = lat; - } - - public String getLng() { - return lng; - } - - public void setLng(String lng) { - this.lng = lng; - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - - public Timestamp getJoinTime() { - return joinTime; - } - - public void setJoinTime(Timestamp joinTime) { - this.joinTime = joinTime; - } -} \ No newline at end of file +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/CreateOrderDTO.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/CreateOrderDTO.java new file mode 100644 index 0000000..bbca79b --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/CreateOrderDTO.java @@ -0,0 +1,27 @@ +package com.chaozhanggui.system.cashierservice.entity.dto; + +import lombok.Data; + +import javax.validation.Valid; +import javax.validation.constraints.NotEmpty; +import java.util.ArrayList; +import java.util.List; + +@Data +public class CreateOrderDTO { + @NotEmpty + private Integer shopId; + private String tableId; + private Integer userId; + @NotEmpty(message = "用餐类型不为空") + private String sendType; + private String remark = ""; + private String environment; + private String type; + + // 使用的优惠券 + @Valid + private List userCouponInfos = new ArrayList<>(); + // 使用的积分抵扣数量 + private Integer pointsNum; +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/MemberInDTO.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/MemberInDTO.java index c1a03ca..740de97 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/MemberInDTO.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/MemberInDTO.java @@ -22,5 +22,5 @@ public class MemberInDTO { // 使用的优惠券 private List userCouponIds = new ArrayList<>(); // 是否使用积分抵扣 - private boolean usePoints ; + private Integer pointsNum ; } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/OrderCartInfoDTO.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/OrderCartInfoDTO.java new file mode 100644 index 0000000..8e7f304 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/OrderCartInfoDTO.java @@ -0,0 +1,19 @@ +package com.chaozhanggui.system.cashierservice.entity.dto; + +import com.chaozhanggui.system.cashierservice.entity.TbCashierCart; +import lombok.Data; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +@Data +public class OrderCartInfoDTO { + private BigDecimal totalAmount = BigDecimal.ZERO; + private BigDecimal newAddTotalAmount = BigDecimal.ZERO; + private List newCashierCarts = new ArrayList<>(); + private List cashierCarts = new ArrayList<>(); + private List cashierCartIds = new ArrayList<>(); + private Integer orderId; + private TbCashierCart seatCart; +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/OrderCouponInfoDTO.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/OrderCouponInfoDTO.java new file mode 100644 index 0000000..21458fa --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/OrderCouponInfoDTO.java @@ -0,0 +1,20 @@ +package com.chaozhanggui.system.cashierservice.entity.dto; + +import com.chaozhanggui.system.cashierservice.entity.TbActivateOutRecord; +import com.chaozhanggui.system.cashierservice.entity.TbShopUser; +import com.chaozhanggui.system.cashierservice.entity.vo.TbUserCouponVo; +import lombok.Data; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +@Data +public class OrderCouponInfoDTO { + private TbShopUser shopUser; + private List outRecordList = new ArrayList<>(); + // 满减优惠券 + private HashMap fullReductionCouponMap = new HashMap<>(); + // 商品优惠券 + private HashMap productCouponMap = new HashMap<>(); +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/OrderPriceDTO.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/OrderPriceDTO.java new file mode 100644 index 0000000..684c55f --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/OrderPriceDTO.java @@ -0,0 +1,21 @@ +package com.chaozhanggui.system.cashierservice.entity.dto; + +import com.chaozhanggui.system.cashierservice.entity.TbOrderDetail; +import lombok.Data; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +@Data +public class OrderPriceDTO { + private BigDecimal productDiscountAmount = BigDecimal.ZERO; + private BigDecimal originAmount = BigDecimal.ZERO; + private BigDecimal totalAmount = BigDecimal.ZERO; + private BigDecimal packAmount = BigDecimal.ZERO; + private boolean hasNewInfo = false; + private List newOrderDetailList = new ArrayList<>(); + private List removeOrderDetailList = new ArrayList<>(); + private List removeOrderDetailIds = new ArrayList<>(); + private List orderDetailList = new ArrayList<>(); +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/ShopEatTypeInfoDTO.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/ShopEatTypeInfoDTO.java index b1117c9..3cb85b8 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/ShopEatTypeInfoDTO.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/ShopEatTypeInfoDTO.java @@ -11,8 +11,15 @@ public class ShopEatTypeInfoDTO { private boolean isMunchies; private boolean isDineInAfter; private boolean isDineInBefore; + // 是否需要餐位费 + private boolean needSeatFee; + // 是否无桌台下单 + private boolean isNoneTable; + // 是否增加masterId + private boolean isIncrMaterId; private TbShopInfo shopInfo; private String useType; private boolean isOpenTakeout; private boolean isOpenDineIn; + private String tableId; } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/UserCouponInfoDTO.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/UserCouponInfoDTO.java new file mode 100644 index 0000000..13ee9c7 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/UserCouponInfoDTO.java @@ -0,0 +1,12 @@ +package com.chaozhanggui.system.cashierservice.entity.dto; + +import lombok.Data; + +import javax.validation.constraints.Min; + +@Data +public class UserCouponInfoDTO { + private Integer userCouponId; + @Min(1) + private Integer num; +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/TbUserCouponVo.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/TbUserCouponVo.java index 6e0f865..ee2c289 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/TbUserCouponVo.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/TbUserCouponVo.java @@ -24,6 +24,8 @@ public class TbUserCouponVo { private String useRestrictions; private boolean isUse = false; + private Integer currentUseNum = 0; + public void setEndTime(Date endTime) { this.endTime = endTime; diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/exception/MsgException.java b/src/main/java/com/chaozhanggui/system/cashierservice/exception/MsgException.java index b2c23a2..0018131 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/exception/MsgException.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/exception/MsgException.java @@ -1,5 +1,6 @@ package com.chaozhanggui.system.cashierservice.exception; +import cn.hutool.core.util.StrUtil; import com.chaozhanggui.system.cashierservice.annotation.ResultCode; import lombok.Data; import lombok.EqualsAndHashCode; @@ -31,6 +32,10 @@ public class MsgException extends RuntimeException { this(ResultCode.FAIL, msg, obj); } + public MsgException(String template, Object... args) { + this(ResultCode.FAIL, StrUtil.format(template, args), null); + } + public MsgException(ResultCode code, String msg, Serializable obj) { super(msg); this.code = code; diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/mapper/MpShopUserMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/mapper/MpShopUserMapper.java new file mode 100644 index 0000000..6a596a0 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/mapper/MpShopUserMapper.java @@ -0,0 +1,19 @@ +package com.chaozhanggui.system.cashierservice.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.chaozhanggui.system.cashierservice.entity.TbShopInfo; +import com.chaozhanggui.system.cashierservice.entity.TbShopUser; + +/** +* @author Administrator +* @description 针对表【tb_call_queue】的数据库操作Mapper +* @createDate 2024-09-13 13:44:26 +* @Entity com.chaozhanggui.system.cashierservice.entity.TbCallQueue +*/ +public interface MpShopUserMapper extends BaseMapper { + +} + + + + diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/CartConsumer.java b/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/CartConsumer.java index 2ad7144..00a2569 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/CartConsumer.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/CartConsumer.java @@ -3,6 +3,7 @@ package com.chaozhanggui.system.cashierservice.rabbit; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; +import com.chaozhanggui.system.cashierservice.entity.dto.CreateOrderDTO; import com.chaozhanggui.system.cashierservice.entity.dto.ShopEatTypeInfoDTO; import com.chaozhanggui.system.cashierservice.exception.MsgException; import com.chaozhanggui.system.cashierservice.redis.RedisCst; @@ -52,7 +53,7 @@ public class CartConsumer { else if (jsonObject.getString("type").equals("queryCart") ) { cartService.queryCart(jsonObject); } else if(jsonObject.getString("type").equals("createOrder")){ - cartService.createOrder(jsonObject); + cartService.createOrder(JSONObject.parseObject(message, CreateOrderDTO.class)); } // else if(jsonObject.getString("type").equals("clearCart")){ // cartService.clearCart(jsonObject); diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/redis/RedisCst.java b/src/main/java/com/chaozhanggui/system/cashierservice/redis/RedisCst.java index c5e3907..0a87ea8 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/redis/RedisCst.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/redis/RedisCst.java @@ -34,6 +34,7 @@ public class RedisCst { public static final String ORDER_PRINT = "ORDER_PRINT:"; // 选择人数锁 public static final String CHOSE_TABLE_COUNT = "CHOSE_TABLE_COUNT"; + public static final String ORDER_PRODUCT_NUM = "ORDER_NUM:"; static final String CURRENT_TABLE_ORDER = "CURRENT_TABLE_ORDER:"; diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/CartService.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/CartService.java index 950c1d8..d97bfbe 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/service/CartService.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/CartService.java @@ -12,15 +12,13 @@ import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.chaozhanggui.system.cashierservice.constant.TableConstant; import com.chaozhanggui.system.cashierservice.dao.*; -import com.chaozhanggui.system.cashierservice.entity.Enum.OrderUseTypeEnum; import com.chaozhanggui.system.cashierservice.entity.Enum.PlatformTypeEnum; import com.chaozhanggui.system.cashierservice.entity.Enum.ShopWxMsgTypeEnum; import com.chaozhanggui.system.cashierservice.entity.*; -import com.chaozhanggui.system.cashierservice.entity.dto.ChoseEatModelDTO; -import com.chaozhanggui.system.cashierservice.entity.dto.ShopEatTypeInfoDTO; +import com.chaozhanggui.system.cashierservice.entity.dto.*; +import com.chaozhanggui.system.cashierservice.entity.vo.TbUserCouponVo; import com.chaozhanggui.system.cashierservice.exception.MsgException; import com.chaozhanggui.system.cashierservice.mapper.*; -import com.chaozhanggui.system.cashierservice.mpservice.MpShopTableService; import com.chaozhanggui.system.cashierservice.netty.PushToAppChannelHandlerAdapter; import com.chaozhanggui.system.cashierservice.rabbit.RabbitProducer; import com.chaozhanggui.system.cashierservice.redis.RedisCst; @@ -28,21 +26,18 @@ import com.chaozhanggui.system.cashierservice.redis.RedisUtil; import com.chaozhanggui.system.cashierservice.sign.CodeEnum; import com.chaozhanggui.system.cashierservice.sign.Result; import com.chaozhanggui.system.cashierservice.util.*; -import com.chaozhanggui.system.cashierservice.wxUtil.WechatUtil; import com.chaozhanggui.system.cashierservice.wxUtil.WxAccountUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; -import javax.annotation.Resource; -import java.io.IOException; import java.math.BigDecimal; +import java.math.RoundingMode; import java.time.Instant; import java.util.*; import java.util.concurrent.CompletableFuture; @@ -58,8 +53,7 @@ public class CartService { @Autowired private RedisUtil redisUtil; - @Autowired - private TbOrderInfoMapper orderInfoMapper; + @Autowired private TbCashierCartMapper cashierCartMapper; @Autowired @@ -73,20 +67,11 @@ public class CartService { @Autowired private TbShopUserMapper shopUserMapper; - @Autowired - private TbOrderDetailMapper orderDetailMapper; @Autowired private TbShopTableMapper shopTableMapper; - private final TbUserShopMsgMapper tbUserShopMsgMapper; - private final WechatUtil wechatUtil; - private final WxAccountUtil wxAccountUtil; private final TbShopOpenIdMapper shopOpenIdMapper; - @Resource - private TbActivateInRecordService activateInRecordService; - @Autowired - private TbActivateOutRecordMapper outRecordMapper; @Autowired private RabbitProducer producer; @@ -94,13 +79,6 @@ public class CartService { @Autowired private TbShopInfoMapper tbShopInfoMapper; - - private final ProductService productService; - - private final TbProductMapper tbProductMapper; - - private final RedisTemplate redisTemplate; - private final StringRedisTemplate stringRedisTemplate; private final ShopUtils shopUtils; @@ -112,31 +90,33 @@ public class CartService { @Autowired TbConsInfoMapper tbConsInfoMapper; @Autowired - private MpShopInfoMapper mpShopInfoMapper; - @Autowired private MpOrderInfoMapper mpOrderInfoMapper; @Autowired private MpCashierCartMapper mpCashierCartMapper; @Autowired - private MpOrderDetailMapper mpOrderDetailMapper; - @Autowired private MpShopTableMapper mpShopTableMapper; - private final MpShopTableService mpShopTableService; + private final TbCashierCartService cashierCartService; + private final TbShopCouponService shopCouponService; + private final TbOrderDetailService orderDetailService; + private final TbMemberPointsService memberPointsService; @Autowired private MQUtils mQUtils; + @Autowired + private MpShopUserMapper mpShopUserMapper; - public CartService(TbUserShopMsgMapper tbUserShopMsgMapper, WechatUtil wechatUtil, WxAccountUtil wxAccountUtil, TbShopOpenIdMapper shopOpenIdMapper, ProductService productService, TbProductMapper tbProductMapper, RedisTemplate redisTemplate, StringRedisTemplate stringRedisTemplate, ShopUtils shopUtils, MpShopTableService mpShopTableService) { - this.tbUserShopMsgMapper = tbUserShopMsgMapper; - this.wechatUtil = wechatUtil; + public CartService(WxAccountUtil wxAccountUtil, TbShopOpenIdMapper shopOpenIdMapper, + StringRedisTemplate stringRedisTemplate, ShopUtils shopUtils, + TbCashierCartService cashierCartService, TbShopCouponService shopCouponService, + TbOrderDetailService orderDetailService, TbMemberPointsService memberPointsService) { this.wxAccountUtil = wxAccountUtil; this.shopOpenIdMapper = shopOpenIdMapper; - this.productService = productService; - this.tbProductMapper = tbProductMapper; - this.redisTemplate = redisTemplate; this.stringRedisTemplate = stringRedisTemplate; this.shopUtils = shopUtils; - this.mpShopTableService = mpShopTableService; + this.cashierCartService = cashierCartService; + this.shopCouponService = shopCouponService; + this.orderDetailService = orderDetailService; + this.memberPointsService = memberPointsService; } @@ -205,40 +185,40 @@ public class CartService { // } // } else { - // 查询购物车所有信息 - LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper() - .eq(TbCashierCart::getShopId, shopId) - .gt(TbCashierCart::getCreatedAt, DateUtil.offsetDay(DateUtil.date(), -1).getTime()) - .isNull(TbCashierCart::getOrderId) - .and(q -> q.isNull(TbCashierCart::getUseType).or().eq(TbCashierCart::getUseType, shopEatTypeInfoDTO.getUseType())) - .eq(TbCashierCart::getStatus, "create"); + // 查询购物车所有信息 + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper() + .eq(TbCashierCart::getShopId, shopId) + .gt(TbCashierCart::getCreatedAt, DateUtil.offsetDay(DateUtil.date(), -1).getTime()) + .isNull(TbCashierCart::getOrderId) + .and(q -> q.isNull(TbCashierCart::getUseType).or().eq(TbCashierCart::getUseType, shopEatTypeInfoDTO.getUseType())) + .eq(TbCashierCart::getStatus, "create"); - if (StrUtil.isNotBlank(tableId)) { - queryWrapper.eq(TbCashierCart::getTableId, tableId); - } else { - queryWrapper.eq(TbCashierCart::getUserId, userId); - } + if (StrUtil.isNotBlank(tableId)) { + queryWrapper.eq(TbCashierCart::getTableId, tableId); + } else { + queryWrapper.eq(TbCashierCart::getUserId, userId); + } - List tbCashierCarts = mpCashierCartMapper.selectList(queryWrapper); - if (!CollectionUtils.isEmpty(tbCashierCarts)) { - for (TbCashierCart cashierCart : tbCashierCarts) { - if (TableConstant.CART_SEAT_ID.equals(cashierCart.getProductId())) { - seatCartInfo = cashierCart; - }else { - array.add(cashierCart); - } - if (cashierCart.getIsVip().equals((byte) 1)) continue; - if ((!TableConstant.CART_SEAT_ID.equals(cashierCart.getProductId()) || !ignoreTableFee) && cashierCart.getNumber() > 0) { - amount = amount.add(new BigDecimal(cashierCart.getTotalNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee()))); - } + List tbCashierCarts = mpCashierCartMapper.selectList(queryWrapper); + if (!CollectionUtils.isEmpty(tbCashierCarts)) { + for (TbCashierCart cashierCart : tbCashierCarts) { + if (TableConstant.CART_SEAT_ID.equals(cashierCart.getProductId())) { + seatCartInfo = cashierCart; + } else { + array.add(cashierCart); + } + if (cashierCart.getIsVip().equals((byte) 1)) continue; + if ((!TableConstant.CART_SEAT_ID.equals(cashierCart.getProductId()) || !ignoreTableFee) && cashierCart.getNumber() > 0) { + amount = amount.add(new BigDecimal(cashierCart.getTotalNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee()))); } - redisUtil.saveMessage(tableCartKey, array.toString(), 60 * 60 * 12L); } + redisUtil.saveMessage(tableCartKey, array.toString(), 60 * 60 * 12L); + } // } if (ignoreTableFee && seatCartInfo != null) { mpCashierCartMapper.deleteById(seatCartInfo.getId()); - }else { + } else { redisUtil.saveMessage(RedisCst.getCurrentTableSeatCount(shopEatTypeInfoDTO.getShopInfo().getId(), tableId), JSONObject.toJSONString(seatCartInfo), 60 * 60 * 12L); } @@ -497,22 +477,6 @@ public class CartService { return Result.success(CodeEnum.SUCCESS); } - private List> formatCartStruct(List cashierCartList) { - // 根据placeNum进行分组 - Map> groupedByPlaceNum = cashierCartList.stream() - .collect(Collectors.groupingBy(TbCashierCart::getPlaceNum)); - - ArrayList> list = new ArrayList<>(); - groupedByPlaceNum.forEach((k, v) -> { - HashMap item = new HashMap<>(); - item.put("placeNum", k); - item.put("placeTime", !v.isEmpty() ? v.get(0).getUpdatedAt() : null); - item.put("info", v); - list.add(item); - }); - return list; - } - private void rmCart(JSONObject jsonObject, String skuId, String redisKey) { JSONArray jsonArray = new JSONArray(); BigDecimal amount = BigDecimal.ZERO; @@ -687,25 +651,618 @@ public class CartService { } } + /** + * 获取优惠券信息 + * + * @param shopId 店铺id + * @param userCouponInfoDTOList 用户使用的优惠券信息 + * @param orderAmount 订单金额 + * @param productIds 商品id + * @return + */ + private OrderCouponInfoDTO getCouponInfo(TbShopUser shopUser, Integer shopId, List userCouponInfoDTOList, BigDecimal orderAmount, Set productIds) { + OrderCouponInfoDTO infoDTO = new OrderCouponInfoDTO(); + // 查询优惠券信息 + if (shopUser == null) { + throw new MsgException("用户不存在"); + } + // 获取当前用户可用的优惠券 + List activateCouponList = shopCouponService.getActivateCoupon(shopUser, orderAmount, shopId, productIds); + // 将优惠券分类为满减和商品 + HashMap fullReductionCoupon = new HashMap<>(); + HashMap productCoupon = new HashMap<>(); + if (activateCouponList.isEmpty()) { + throw new MsgException("未查询到相关优惠券"); + } + activateCouponList.forEach(item -> { + if (TableConstant.ActivateOutRecord.Type.FULL_REDUCTION.equalsVals(item.getType())) { + fullReductionCoupon.put(item.getId(), item); + } else { + productCoupon.put(item.getId(), item); + } + }); + + userCouponInfoDTOList.forEach(item -> { + TbUserCouponVo couponVo = fullReductionCoupon.get(item.getUserCouponId()); + if (couponVo != null) { + if (couponVo.getNum() < item.getNum()) { + throw new MsgException(couponVo.getName() + "数量不足: " + couponVo.getNum()); + } + couponVo.setCurrentUseNum(item.getNum()); + infoDTO.getFullReductionCouponMap().put(couponVo.getId(), couponVo); + return; + } + couponVo = productCoupon.get(item.getUserCouponId()); + if (couponVo == null) { + throw new MsgException("存在不可用优惠券"); + } + couponVo.setCurrentUseNum(item.getNum()); + infoDTO.getProductCouponMap().put(item.getUserCouponId(), couponVo); + }); + + infoDTO.setShopUser(shopUser); + + return infoDTO; + } + + + private Integer getOutNumber(String shopId) { + JSONObject object = new JSONObject(); + String outNumber = redisUtil.getMessage(RedisCst.OUT_NUMBER.concat(shopId)); + Integer number = 1; + if (Objects.isNull(outNumber)) { + object.put("outNumber", number); + object.put("times", DateUtils.getDay()); + } else { + object = JSONObject.parseObject(outNumber); + if (object.getString("times").equals(DateUtils.getDay())) { + number = object.getInteger("outNumber") + 1; + object.put("outNumber", number); + } else { + object.put("outNumber", number); + object.put("times", DateUtils.getDay()); + } + } + redisUtil.saveMessage(RedisCst.OUT_NUMBER.concat(shopId), object.toString()); + return number; + } + + + /** + * 增加库存 + * + * @param productId 商品id + * @param skuId sku + * @param addNum 增加的库存数量 + */ + public void incrStock(Integer productId, Integer skuId, Integer addNum) { + productMapper.incrStock(productId, addNum); + } + + /** + * 减少库存 + * + * @param productId 商品数据 + * @param skuId sku + * @param decrNum 减少的数量 + */ + public void decrStock(Integer productId, String skuId, int decrNum) { + TbProduct product = productMapper.selectById(productId); + if (product.getIsStock() == 1) { + if (productMapper.decrStock(String.valueOf(productId), decrNum) < 1) { + throw new MsgException(product.getName() + "库存不足,下单失败"); + } + } else { + productMapper.decrStockUnCheck(String.valueOf(productId), decrNum); + } + } + + + /** + * 更新库存 + * + * @param cashierCart 购物车 + * @return 是否是第一次添加的商品 + */ + private boolean updateStock(TbCashierCart cashierCart) { + if (cashierCart.getOrderId() != null) { + String message = stringRedisTemplate.opsForValue().get(RedisCst.ORDER_PRODUCT_NUM + cashierCart.getId()); + if (message != null) { + int lastNum = Integer.parseInt(message); + // 数量减少, 返还库存 + if (lastNum > cashierCart.getNumber()) { + incrStock(Integer.parseInt(cashierCart.getProductId()), Integer.parseInt(cashierCart.getSkuId()), lastNum - cashierCart.getNumber()); + } else { + decrStock(Integer.parseInt(cashierCart.getProductId()), cashierCart.getSkuId(), cashierCart.getNumber() - lastNum); + } + stringRedisTemplate.opsForValue().set(RedisCst.ORDER_PRODUCT_NUM + cashierCart.getId(), cashierCart.getNumber().toString(), 24 * 60 * 60, TimeUnit.SECONDS); + } + return false; + + // 首次添加的商品 + } else { + stringRedisTemplate.opsForValue().set(RedisCst.ORDER_PRODUCT_NUM + cashierCart.getId(), cashierCart.getNumber().toString(), 24 * 60 * 60, TimeUnit.SECONDS); + // 修改库存 + decrStock(Integer.parseInt(cashierCart.getProductId()), cashierCart.getSkuId(), cashierCart.getNumber()); + return true; + } + } + + private void updateTableState(ShopEatTypeInfoDTO shopEatTypeInfoDTO, TbOrderInfo orderInfo, List fullCashierCarts, TbCashierCart seatCart) { + if (!shopEatTypeInfoDTO.isTakeout() && StrUtil.isNotBlank(shopEatTypeInfoDTO.getTableId())) { + // 清空台桌信息 + if (shopEatTypeInfoDTO.isDineInBefore()) { + mpShopTableMapper.update(null, new LambdaUpdateWrapper() + .eq(TbShopTable::getShopId, shopEatTypeInfoDTO.getShopInfo().getId()) + .eq(TbShopTable::getQrcode, shopEatTypeInfoDTO.getTableId()) + .set(TbShopTable::getProductNum, 0) + .set(TbShopTable::getTotalAmount, 0) + .set(TbShopTable::getRealAmount, 0) + .set(TbShopTable::getUseNum, 0) + .set(TbShopTable::getStatus, TableConstant.ShopTable.State.IDLE.getValue())); + // 设置台桌信息 + } else { + LambdaUpdateWrapper wrapper = new LambdaUpdateWrapper() + .eq(TbShopTable::getShopId, shopEatTypeInfoDTO.getShopInfo().getId()) + .eq(TbShopTable::getQrcode, shopEatTypeInfoDTO.getTableId()) + .set(TbShopTable::getProductNum, fullCashierCarts.size()) + .set(TbShopTable::getTotalAmount, orderInfo.getOrderAmount()) + .set(TbShopTable::getRealAmount, orderInfo.getOrderAmount()) + .set(TbShopTable::getUseNum, seatCart != null ? seatCart.getNumber() : null) + .set(TbShopTable::getStatus, TableConstant.ShopTable.State.USING.getValue()); + if (orderInfo.getPlaceNum() == 1) { + wrapper.set(TbShopTable::getUseTime, DateUtil.date()); + } + mpShopTableMapper.update(null, wrapper); + + } + } + } + + /** + * 推送耗材消耗信息 + */ + private void pushConsMsg(TbOrderInfo orderInfo, List cashierCarts) { + log.info("创建订单,发送更新耗材消息,订单id:{}", orderInfo.getId()); + //修改耗材数据 + // 发送mq消息 + JSONObject jsonObject2 = new JSONObject(); + jsonObject2.put("orderId", orderInfo.getId()); + jsonObject2.put("type", "create"); + log.info("开始发送mq消息,消耗耗材,消息内容:{}", jsonObject2); + producer.cons(jsonObject2.toString()); + + ThreadUtil.execAsync(() -> { + ThreadUtil.sleep(5, TimeUnit.SECONDS); + for (TbCashierCart cashierCart : cashierCarts) { + JSONObject objectMsg = new JSONObject(); + objectMsg.put("skuId", Integer.valueOf(cashierCart.getSkuId())); + objectMsg.put("shopId", Integer.valueOf(cashierCart.getShopId())); + producer.con_msg(objectMsg.toString()); + } + }); + } + + + private void updateCartAndStock(List newAddCashierCarts, TbOrderInfo orderInfo, ShopEatTypeInfoDTO shopEatTypeInfoDTO) { + // 更新购物车记录的orderId + for (TbCashierCart cashierCart : newAddCashierCarts) { + if (!"-999".equals(cashierCart.getProductId())) { + TbProduct product = productMapper.selectById(Integer.valueOf(cashierCart.getProductId())); + TbProductSku productSku = productSkuMapper.selectByPrimaryKey(Integer.valueOf(cashierCart.getSkuId())); + + log.info("下单,开始校验库存预警,购物车id:{}", cashierCart.getId()); + CompletableFuture.runAsync(() -> checkWarnLineAndSendMsg(productSku, product, cashierCart.getNumber())); + // 已经添加的商品,修改数量 + updateStock(cashierCart); + } + + cashierCart.setOrderId(String.valueOf(orderInfo.getId())); + cashierCart.setUpdatedAt(System.currentTimeMillis()); + cashierCart.setStatus("pending".equals(orderInfo.getStatus()) ? "refund" : cashierCart.getStatus()); + if (cashierCart.getPlaceNum() == null) { + cashierCart.setPlaceNum(orderInfo.getPlaceNum()); + } + + // 先付费模式,结束购物车状态 + if (!shopEatTypeInfoDTO.isDineInAfter() || StrUtil.isBlank(shopEatTypeInfoDTO.getTableId())) { + cashierCart.setStatus("final"); + } + mpCashierCartMapper.updateById(cashierCart); + } + } + + private void updateDetailAndPrint(TbOrderInfo orderInfo, OrderPriceDTO priceDTO, ShopEatTypeInfoDTO shopEatTypeInfoDTO) { + // 添加订单详细数据 + Integer orderId = orderInfo.getId(); + for (TbOrderDetail orderDetail : priceDTO.getOrderDetailList()) { + orderDetail.setOrderId(orderId); + if (orderDetail.getPlaceNum() == null) { + orderDetail.setPlaceNum(orderInfo.getPlaceNum()); + } + } + // 删除已经移除购物车的订单 修改并保存数据 + if (!priceDTO.getOrderDetailList().isEmpty()) { + orderDetailService.saveOrUpdateBatch(priceDTO.getOrderDetailList()); + } + + // 菜品票 + if (!priceDTO.getNewOrderDetailList().isEmpty() && shopEatTypeInfoDTO.isDineInAfter()) { + mQUtils.printDishesTicket(orderInfo.getId(), false, priceDTO.getNewOrderDetailList().toArray(new TbOrderDetail[0])); + } + + if (!priceDTO.getRemoveOrderDetailIds().isEmpty()) { + // 退单票 + orderDetailService.removeByIds(priceDTO.getRemoveOrderDetailIds()); + if (shopEatTypeInfoDTO.isDineInAfter()) { + mQUtils.printDishesTicket(orderInfo.getId(), true, priceDTO.getRemoveOrderDetailList().toArray(new TbOrderDetail[0])); + } + } + } + + private BigDecimal calcPointsDiscountAndReturn(TbOrderInfo orderInfo, int pointsNum) { + Long memberId = Long.valueOf(orderInfo.getMemberId()); + + if (orderInfo.getPointsNum() != null && orderInfo.getPointsNum() != 0) { + memberPointsService.addPoints(memberId, orderInfo.getPointsNum(), "用户未支付订单积分返还: " + orderInfo.getPointsNum() + "积分", Long.valueOf(orderInfo.getId())); + } + + OrderDeductionPointsDTO memberUsablePoints = memberPointsService.getMemberUsablePoints(memberId, orderInfo.getOrderAmount()); + if (!memberUsablePoints.getUsable()) { + throw new MsgException(memberUsablePoints.getUnusableReason()); + } + if (pointsNum < memberUsablePoints.getMinDeductionPoints() || pointsNum > memberUsablePoints.getMaxUsablePoints()) { + throw new MsgException("可抵扣积分区间为: [" + memberUsablePoints.getMinDeductionPoints() + "-" + memberUsablePoints.getMaxUsablePoints() + "]"); + } + + BigDecimal discountAmount = memberPointsService.calcDeductionAmount(memberId, orderInfo.getOrderAmount(), pointsNum); + orderInfo.setPointsNum(pointsNum); + orderInfo.setPointsDiscountAmount(discountAmount); + memberPointsService.deductPoints(memberId, pointsNum, "订单积分抵扣" + discountAmount + "元", Long.valueOf(orderInfo.getId())); + return discountAmount; + } + + private TbActivateOutRecord calcOrderInfoDiscount(CreateOrderDTO orderDTO, TbOrderInfo orderInfo, OrderCouponInfoDTO couponInfo, Integer memberId) { + BigDecimal finalAmount = orderInfo.getOrderAmount(); + TbActivateOutRecord tbActivateOutRecord = null; + if (couponInfo != null && !couponInfo.getFullReductionCouponMap().isEmpty()) { + TbUserCouponVo couponVo = couponInfo.getFullReductionCouponMap().values().stream().findFirst().orElse(null); + finalAmount = finalAmount.subtract(couponVo.getDiscountAmount()); + orderInfo.setFullCouponDiscountAmount(couponVo.getDiscountAmount()); + + tbActivateOutRecord = new TbActivateOutRecord(); + tbActivateOutRecord.setShopId(Integer.valueOf(orderInfo.getShopId())); + tbActivateOutRecord.setGiveId(couponVo.getId()); + tbActivateOutRecord.setVipUserId(memberId); + tbActivateOutRecord.setType(TableConstant.ActivateOutRecord.Type.FULL_REDUCTION.getValue()); + tbActivateOutRecord.setUseNum(couponVo.getCurrentUseNum()); + tbActivateOutRecord.setStatus(TableConstant.ActivateOutRecord.Status.CLOSED.getValue()); + tbActivateOutRecord.setCreateTime(DateUtil.date()); + tbActivateOutRecord.setRefNum(0); + + } + + // 计算积分优惠 + if (orderDTO.getPointsNum() != null && orderDTO.getPointsNum() != 0) { + BigDecimal discountPointsAmount = calcPointsDiscountAndReturn(orderInfo, orderDTO.getPointsNum()); + finalAmount = finalAmount.subtract(discountPointsAmount); + orderInfo.setPointsDiscountAmount(discountPointsAmount); + } + + if (finalAmount.compareTo(BigDecimal.ZERO) < 0) { + finalAmount = BigDecimal.ZERO; + orderInfo.setFullCouponDiscountAmount(orderInfo.getOrderAmount()); + } + + orderInfo.setSettlementAmount(finalAmount); + orderInfo.setOrderAmount(finalAmount); + orderInfo.setAmount(finalAmount); + + return tbActivateOutRecord; + + } + + private TbOrderInfo createOrderInfoWithCoupon(CreateOrderDTO createOrderDTO, OrderPriceDTO priceDTO, ShopEatTypeInfoDTO eatTypeInfoDTO, + TbOrderInfo orderInfo, TbCashierCart seatCart, TbShopUser shopUser, TbShopTable shopTable, OrderCouponInfoDTO couponInfoDTO) { + Integer placeNum = getCurrentPlaceNum(eatTypeInfoDTO.getTableId(), eatTypeInfoDTO.getShopInfo().getId(), eatTypeInfoDTO); + boolean isFirst = false; + // 修改订单信息 + if (orderInfo == null) { + isFirst = true; + String orderNo = generateOrderNumber(null); + orderInfo = new TbOrderInfo(); + orderInfo.setOrderNo(orderNo); + orderInfo.setCreatedAt(DateUtil.current()); + orderInfo.setTradeDay(DateUtil.today()); + orderInfo.setRefundAble((byte) 1); + orderInfo.setOrderType("cash"); + orderInfo.setShopId(createOrderDTO.getShopId().toString()); + orderInfo.setTableId(createOrderDTO.getTableId()); + orderInfo.setTableName(shopTable != null ? shopTable.getName() : null); + TbMerchantAccount merchantAccount = merchantAccountMapper.selectByShopId(String.valueOf(createOrderDTO.getShopId())); + if (merchantAccount == null) { + throw new MsgException("商户信息不存在"); + } + orderInfo.setMerchantId(merchantAccount.getId().toString()); + } + // 更新取餐号 + orderInfo.setOutNumber(getOutNumber(createOrderDTO.getShopId().toString()).toString()); + orderInfo.setUpdatedAt(System.currentTimeMillis()); + orderInfo.setSettlementAmount(priceDTO.getTotalAmount()); + orderInfo.setAmount(priceDTO.getTotalAmount()); + orderInfo.setOriginAmount(priceDTO.getOriginAmount()); + orderInfo.setOrderAmount(priceDTO.getTotalAmount()); + orderInfo.setRemark(createOrderDTO.getRemark()); + orderInfo.setFreightAmount(BigDecimal.ZERO); + orderInfo.setProductAmount(BigDecimal.ZERO); + orderInfo.setTradeDay(DateUtils.getDay()); + orderInfo.setUseType(eatTypeInfoDTO.getUseType()); + orderInfo.setCreatedAt(DateUtil.current()); + orderInfo.setProductCouponDiscountAmount(priceDTO.getProductDiscountAmount()); + + if (seatCart != null) { + orderInfo.setSeatAmount(seatCart.getTotalAmount()); + orderInfo.setSeatCount(seatCart.getNumber()); + } + orderInfo.setMemberId(String.valueOf(shopUser.getId())); + orderInfo.setUserId(shopUser.getUserId()); + orderInfo.setSendType(createOrderDTO.getSendType()); + // 存在新添加的商品,增加下单次数 + if (priceDTO.isHasNewInfo()) { + orderInfo.setPlaceNum(placeNum); + } + + return orderInfo; + } + + private OrderPriceDTO createOrderDetailWithCoupon(List fullCashierCarts, Integer orderId, + Integer shopId, ShopEatTypeInfoDTO shopEatTypeInfoDTO) { + OrderPriceDTO priceDTO = new OrderPriceDTO(); + + List cartIds = fullCashierCarts.stream().map(TbCashierCart::getId).collect(Collectors.toList()); + // 查询历史orderDetail + List oldOrderDetailList = orderDetailService + .selectByCartIdOrOrderId(shopId, cartIds, orderId); + HashMap oldOrderDetailMap = new HashMap<>(); + oldOrderDetailList.forEach(item -> { + if (cartIds.contains(item.getCartId())) { + oldOrderDetailMap.put(item.getOrderId().toString() + item.getCartId(), item); + } else { + priceDTO.getRemoveOrderDetailIds().add(item.getId()); + priceDTO.getRemoveOrderDetailList().add(item); + } + }); + + for (TbCashierCart cashierCart : fullCashierCarts) { + // 设置打包费 + if (shopEatTypeInfoDTO.isTakeout() && !TableConstant.CashierCart.ID.equals(cashierCart.getProductId())) { + cashierCart.setTableId(""); + // 打包费 + TbProduct product = productMapper.selectById(Integer.valueOf(cashierCart.getProductId())); + cashierCart.setPackFee(product.getPackFee() != null ? + product.getPackFee().multiply(BigDecimal.valueOf(cashierCart.getNumber())) : BigDecimal.ZERO); + cashierCart.setIsPack("true"); + } else { + cashierCart.setTableId(shopEatTypeInfoDTO.getTableId()); + cashierCart.setPackFee(BigDecimal.ZERO); + } + + cashierCart.setStatus(shopEatTypeInfoDTO.isDineInAfter() ? "create" : "final"); + + // 已经退款和使用优惠券的商品不进行统计金额 + if (!"return".equals(cashierCart.getStatus()) && cashierCart.getUserCouponId() == null) { + priceDTO.setTotalAmount(priceDTO.getTotalAmount().add(cashierCart.getTotalAmount())); + priceDTO.setPackAmount(priceDTO.getPackAmount().add(cashierCart.getPackFee())); + } + + priceDTO.setOriginAmount(priceDTO.getOriginAmount().add(cashierCart.getTotalAmount())); + + TbProductSku productSku = productSkuMapper.selectByPrimaryKey(Integer.valueOf(cashierCart.getSkuId())); + TbOrderDetail orderDetail = null; + if (cashierCart.getOrderId() != null) { + orderDetail = oldOrderDetailMap.get(cashierCart.getOrderId() + cashierCart.getId()); + } + + if (orderDetail == null) { + orderDetail = new TbOrderDetail(); + priceDTO.setHasNewInfo(true); + priceDTO.getNewOrderDetailList().add(orderDetail); + } + + if (Objects.nonNull(productSku)) { + orderDetail.setProductSkuName(productSku.getSpecSnap()); + } + + orderDetail.setNote(cashierCart.getNote()); + orderDetail.setCreateTime(DateUtil.date().toTimestamp()); + orderDetail.setNum(cashierCart.getNumber()); + orderDetail.setPrice(cashierCart.getSalePrice()); + orderDetail.setPriceAmount(cashierCart.getTotalAmount()); + orderDetail.setProductId(Integer.valueOf(cashierCart.getProductId())); + orderDetail.setProductSkuId(Integer.valueOf(cashierCart.getSkuId())); + orderDetail.setProductName(cashierCart.getName()); + orderDetail.setShopId(Integer.valueOf(cashierCart.getShopId())); + orderDetail.setPackAmount(cashierCart.getPackFee()); + orderDetail.setStatus(TableConstant.CashierCart.Status.RETURN.equalsVals(cashierCart.getStatus()) ? cashierCart.getStatus() : "unpaid"); + orderDetail.setUseType(cashierCart.getUseType()); + orderDetail.setProductImg(cashierCart.getCoverImg()); + orderDetail.setCartId(cashierCart.getId()); + if (cashierCart.getOrderId() != null) { + orderId = Integer.valueOf(cashierCart.getOrderId()); + } + orderDetail.setOrderId(orderId); + priceDTO.getOrderDetailList().add(orderDetail); + } + return priceDTO; + } + + /** + * 根据商品优惠券计算购物车优惠金额 + * + * @param couponInfoDTO 优惠券信息 + * @param memberId 店铺会员id + * @return 折扣金额 + */ + private BigDecimal calcCartPriceWithCoupon(OrderCartInfoDTO cartInfoDTO, OrderCouponInfoDTO couponInfoDTO, Integer memberId) { + ArrayList balanceCartList = new ArrayList<>(); + BigDecimal discountAmount = BigDecimal.ZERO; + HashMap couponMap = new HashMap<>(); + couponInfoDTO.getProductCouponMap().values().forEach(item -> { + couponMap.put(item.getProId().toString(), item); + }); + HashMap usedCouponMap = new HashMap<>(); + ArrayList outRecords = new ArrayList<>(); + for (TbCashierCart cashierCart : cartInfoDTO.getNewCashierCarts()) { + TbUserCouponVo couponVo = couponMap.get(cashierCart.getProductId()); + boolean useCoupon; + if (couponVo != null && couponVo.getCurrentUseNum() > 0) { + BigDecimal currentUseNum = BigDecimal.ZERO; + if (cashierCart.getNumber() < couponVo.getCurrentUseNum()) { + currentUseNum = BigDecimal.valueOf(couponVo.getCurrentUseNum()); + BigDecimal cartNum = BigDecimal.valueOf(cashierCart.getNumber()); + BigDecimal singlePackFee = cashierCart.getPackFee().divide(cartNum, RoundingMode.HALF_UP); + cashierCart.setPackFee(singlePackFee.multiply(currentUseNum)); + cashierCart.setTotalAmount(cashierCart.getSalePrice().multiply(currentUseNum).add(singlePackFee.multiply(currentUseNum))); + cashierCart.setNumber(couponVo.getCurrentUseNum()); + cashierCart.setTotalNumber(couponVo.getCurrentUseNum()); + cashierCart.setUserCouponId(couponVo.getId()); + discountAmount = discountAmount.add(cashierCart.getTotalAmount()); + couponVo.setCurrentUseNum(couponVo.getCurrentUseNum() - cashierCart.getNumber()); + } + usedCouponMap.put(Integer.valueOf(cashierCart.getProductId()), couponVo); + // 优惠券数量小于购物车数量,分割购物车数据 + if (cashierCart.getNumber() > couponVo.getCurrentUseNum()) { + currentUseNum = BigDecimal.valueOf(couponVo.getCurrentUseNum()); + BigDecimal cartNum = BigDecimal.valueOf(cashierCart.getNumber()); + int balanceNum = cashierCart.getTotalNumber() - couponVo.getCurrentUseNum(); + BigDecimal singlePackFee = cashierCart.getPackFee().divide(cartNum, RoundingMode.HALF_UP); + cashierCart.setPackFee(singlePackFee.multiply(currentUseNum)); + cashierCart.setTotalAmount(cashierCart.getSalePrice().multiply(currentUseNum).add(singlePackFee.multiply(currentUseNum))); + cashierCart.setNumber(couponVo.getCurrentUseNum()); + cashierCart.setTotalNumber(couponVo.getCurrentUseNum()); + cashierCart.setUserCouponId(couponVo.getId()); + discountAmount = discountAmount.add(cashierCart.getTotalAmount()); + couponVo.setCurrentUseNum(couponVo.getCurrentUseNum() - cashierCart.getNumber()); + + + // 创建结余购物车 + TbCashierCart balanceCart = BeanUtil.copyProperties(cashierCart, TbCashierCart.class); + BigDecimal num = BigDecimal.valueOf(balanceNum); + balanceCart.setUserCouponId(null); + balanceCart.setId(null); + balanceCart.setNumber(balanceNum); + balanceCart.setTotalNumber(balanceNum); + balanceCart.setPackFee(singlePackFee.multiply(num)); + balanceCart.setTotalAmount(cashierCart.getSalePrice().multiply(num).add(balanceCart.getPackFee())); + balanceCartList.add(balanceCart); + } else { + currentUseNum = BigDecimal.valueOf(cashierCart.getNumber()); + discountAmount = discountAmount.add(cashierCart.getTotalAmount()); + cashierCart.setUserCouponId(couponVo.getId()); + couponVo.setCurrentUseNum(couponVo.getCurrentUseNum() - cashierCart.getNumber()); + } + // 消耗并返还商品优惠券 + Integer shopId = Integer.valueOf(cashierCart.getShopId()); + TbActivateOutRecord tbActivateOutRecord = new TbActivateOutRecord(); + tbActivateOutRecord.setShopId(shopId); + tbActivateOutRecord.setGiveId(couponVo.getId()); + tbActivateOutRecord.setVipUserId(memberId); + tbActivateOutRecord.setType(TableConstant.ActivateOutRecord.Type.FULL_REDUCTION.getValue()); + tbActivateOutRecord.setUseNum(currentUseNum.toBigInteger().intValue()); + tbActivateOutRecord.setStatus(TableConstant.ActivateOutRecord.Status.CLOSED.getValue()); + tbActivateOutRecord.setCreateTime(DateUtil.date()); + tbActivateOutRecord.setRefNum(0); + outRecords.add(tbActivateOutRecord); + } + } + + if (!balanceCartList.isEmpty()) { + cartInfoDTO.getCashierCarts().addAll(balanceCartList); + cartInfoDTO.getNewCashierCarts().addAll(balanceCartList); + cashierCartService.saveBatch(balanceCartList); + } + // 更新购物车信息 + cashierCartService.updateBatchById(cartInfoDTO.getNewCashierCarts()); + + couponInfoDTO.setOutRecordList(outRecords); + couponInfoDTO.setProductCouponMap(usedCouponMap); + + return discountAmount; + } + + + private OrderCartInfoDTO getCartInfoForOrder(ShopEatTypeInfoDTO shopEatTypeInfoDTO, List allCartList, TbShopTable shopTable) { + OrderCartInfoDTO infoDTO = new OrderCartInfoDTO(); + // 就餐人数 + ArrayList cashierIds = new ArrayList<>(); + TbCashierCart seatInfo = null; + Integer orderId = null; + for (TbCashierCart tbCashierCart : allCartList) { + cashierIds.add(tbCashierCart.getId()); + if (TableConstant.CashierCart.ID.equals(tbCashierCart.getProductId())) { + seatInfo = tbCashierCart; + } + + if (TableConstant.OrderInfo.Status.CREATE.equalsVals(tbCashierCart.getStatus())) { + infoDTO.getNewCashierCarts().add(tbCashierCart); + infoDTO.setNewAddTotalAmount(infoDTO.getNewAddTotalAmount().add(tbCashierCart.getTotalAmount())); + + } + infoDTO.getCashierCarts().add(tbCashierCart); + + if (StringUtils.isNotEmpty(tbCashierCart.getOrderId())) { + orderId = Integer.valueOf(tbCashierCart.getOrderId()); + + } + infoDTO.setTotalAmount(infoDTO.getTotalAmount().add(tbCashierCart.getTotalAmount())); + + } + infoDTO.setSeatCart(seatInfo); + infoDTO.setOrderId(orderId); + + // 校验是否选择人数 + if (shopEatTypeInfoDTO.isNeedSeatFee() && seatInfo == null) { + throw new MsgException("请选择就餐人数"); + } + if (allCartList.isEmpty() || (shopEatTypeInfoDTO.isNeedSeatFee() && allCartList.size() < 2)) { +// log.info("消息推送"); +// JSONObject responseData = new JSONObject(); +// responseData.put("msg", "购物车为空"); +// if (shopTable.getMaxCapacity() < seatNum) { +// responseData.put("msg", "当前台桌最大人数为: " + shopTable.getMaxCapacity()); +// } +// responseData.put("status", "fail"); +// responseData.put("type", orderDTO.getType()); +// responseData.put("data", ""); +// PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(responseData.toString(), tableCartKey, userId, true); + throw new MsgException("当前台桌最大人数为: " + shopTable.getMaxCapacity()); + } + + infoDTO.setCashierCartIds(cashierIds); + return infoDTO; + } + + private TbShopTable getTableInfoByEatType(ShopEatTypeInfoDTO shopEatTypeInfoDTO) { + if (!shopEatTypeInfoDTO.isTakeout()) { + TbShopTable shopTable = mpShopTableMapper.selectOne(new LambdaQueryWrapper() + .eq(TbShopTable::getQrcode, shopEatTypeInfoDTO.getTableId())); + if (shopTable == null) { + throw new MsgException("台桌不存在"); + } + return shopTable; + } + + return null; + } + @Transactional(rollbackFor = Exception.class) - public Result createOrder(JSONObject jsonObject) { + public Result createOrder(CreateOrderDTO orderDTO) { try { - JSONObject responseData = new JSONObject(); + String shopId = orderDTO.getShopId().toString(); + String tableId = orderDTO.getTableId(); + String userId = orderDTO.getUserId().toString(); + String sendType = orderDTO.getSendType(); - String shopId = jsonObject.getString("shopId"); - String tableId = jsonObject.getString("tableId"); - String userId = jsonObject.getString("userId"); - String sendType = jsonObject.getString("sendType"); - String remark = StringUtils.isBlank(jsonObject.getString("remark")) ? "" : jsonObject.getString("remark"); - - BigDecimal totalAmount = BigDecimal.ZERO; - BigDecimal packAMount = BigDecimal.ZERO; - BigDecimal originAmount = BigDecimal.ZERO; - BigDecimal saleAmount = BigDecimal.ZERO; - String couponId = ""; - BigDecimal couponAmount = BigDecimal.ZERO; - List orderDetails = new ArrayList<>(); - Integer orderId = 0; TbMerchantAccount tbMerchantAccount = merchantAccountMapper.selectByShopId(shopId); if (tbMerchantAccount == null) { MsgException.throwException("生成订单错误"); @@ -715,432 +1272,123 @@ public class CartService { if (tbUserInfo == null) { MsgException.throwException("生成订单失败"); } - - if (StrUtil.isBlank(sendType)) { - MsgException.throwException("用餐类型不为空"); - } + TbShopUser tbShopUser = shopUserMapper.selectByUserIdAndShopId(userId, shopId); // 获取当前下单次数和用餐类型 if ("takeself".equals(sendType)) { tableId = null; } + ShopEatTypeInfoDTO shopEatTypeInfoDTO = shopUtils.checkEatModel(tableId, shopId); - Integer currentPlaceNum = getCurrentPlaceNum(tableId, shopId, shopEatTypeInfoDTO); - String tableCartKey = RedisCst.getTableCartKey(shopId, shopEatTypeInfoDTO.isOpenDineIn() ? tableId : null, Integer.valueOf(userId)); - JSONArray array = JSON.parseArray(redisUtil.getMessage(tableCartKey)); - // 查询购物车所有信息 - LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper() - .eq(TbCashierCart::getShopId, shopId) - .gt(TbCashierCart::getCreatedAt, DateUtil.offsetDay(DateUtil.date(), -1).getTime()) - .eq(TbCashierCart::getStatus, "create"); - - TbShopTable shopTable = null; - // 外带模式 - if (shopEatTypeInfoDTO.isTakeout()) { - queryWrapper.eq(TbCashierCart::getUserId, userId); - // 台桌点单 - } else { - String finalTableId = tableId; - queryWrapper.and(q -> { - q.eq(TbCashierCart::getTableId, finalTableId).or().eq(TbCashierCart::getUserId, userId); - }).and(q -> q.eq(TbCashierCart::getUseType, shopEatTypeInfoDTO.getUseType()).or().isNull(TbCashierCart::getUseType)); - - shopTable = mpShopTableMapper.selectOne(new LambdaQueryWrapper() - .eq(TbShopTable::getQrcode, tableId)); - if (shopTable == null) { - throw new MsgException("台桌不存在"); - } - } - - // 所有订单信息 - List cashierCartList = mpCashierCartMapper.selectList(queryWrapper); + // 查询购物车数据并获取台桌信息 + List cashierCartList = cashierCartService.selectByShopEatTypeInfo(shopEatTypeInfoDTO, orderDTO.getUserId()); if (cashierCartList.isEmpty()) { - responseData.put("status", "fail"); - responseData.put("msg", "购物车为空"); - responseData.put("data", new ArrayList<>()); - PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(responseData.toString(), tableCartKey, jsonObject.getString("userId"), true); return Result.fail("购物车为空"); } - // 就餐人数 - ArrayList cashierIds = new ArrayList<>(); + // 获取台桌信息 + TbShopTable shopTable = getTableInfoByEatType(shopEatTypeInfoDTO); - Integer seatNum = 0; - BigDecimal seatCost = BigDecimal.ZERO; - for (TbCashierCart tbCashierCart : cashierCartList) { - cashierIds.add(tbCashierCart.getId()); - if ("-999".equals(tbCashierCart.getProductId())) { - seatNum = tbCashierCart.getNumber(); - seatCost = tbCashierCart.getTotalAmount(); - } + // 获取详细的购物车信息 + OrderCartInfoDTO cartInfoDTO = getCartInfoForOrder(shopEatTypeInfoDTO, cashierCartList, shopTable); - if (StringUtils.isNotEmpty(tbCashierCart.getOrderId())) { - orderId = Integer.valueOf(tbCashierCart.getOrderId()); - } - } - - // 校验是否选择人数 - // 设置餐位费 - TbShopInfo shopInfo = mpShopInfoMapper.selectById(shopId); - if (!shopEatTypeInfoDTO.isTakeout() && shopInfo.getIsTableFee() != null && shopInfo.getIsTableFee() == 0 - && (seatNum < 1 || cashierCartList.size() < 2)) { - log.info("消息推送"); - responseData.put("msg", "购物车为空"); - if (shopTable.getMaxCapacity() < seatNum) { - responseData.put("msg", "当前台桌最大人数为: " + shopTable.getMaxCapacity()); - } - responseData.put("status", "fail"); - responseData.put("type", jsonObject.getString("type")); - responseData.put("data", ""); - PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(responseData.toString(), tableCartKey, jsonObject.getString("userId"), true); - return Result.fail(responseData.getString("msg")); - } - - - TbShopUser tbShopUser = shopUserMapper.selectByUserIdAndShopId(userId, shopId); - boolean isVip = tbShopUser != null && tbShopUser.getIsVip().equals((byte) 1); - - // 查询历史orderDetail - Integer finalOrderId = orderId; - List oldOrderDetailList = mpOrderDetailMapper.selectList(new LambdaQueryWrapper() - .eq(TbOrderDetail::getStatus, "unpaid") - .and(q -> q.in(TbOrderDetail::getCartId, cashierIds).or().eq(TbOrderDetail::getOrderId, finalOrderId)) - .eq(TbOrderDetail::getShopId, shopId)); - HashMap oldOrderDetailMap = new HashMap<>(); - ArrayList removeOrderDetailList = new ArrayList<>(); - ArrayList addOrderDetail = new ArrayList<>(); - - oldOrderDetailList.forEach(item -> { - oldOrderDetailMap.put(item.getOrderId().toString() + item.getCartId(), item); - if (cashierIds.contains(item.getCartId())) { - oldOrderDetailMap.put(item.getOrderId().toString() + item.getCartId(), item); - } else { - removeOrderDetailList.add(item); - } - }); - boolean hasNewInfo = false; - - // 外带模式去除餐位费 - TbCashierCart seatCartInfo = null; - //校验 库存 耗材 - for (TbCashierCart cart : cashierCartList) { - if (shopEatTypeInfoDTO.isTakeout() && "-999".equals(cart.getProductId())) { - seatCartInfo = cart; - continue; - } - - // 设置打包费 - if (shopEatTypeInfoDTO.isTakeout()) { - cart.setTableId(""); - // 打包费 - TbProduct product = productMapper.selectById(Integer.valueOf(cart.getProductId())); - cart.setPackFee(product.getPackFee() != null ? - product.getPackFee().multiply(BigDecimal.valueOf(cart.getNumber())) : BigDecimal.ZERO); - cart.setIsPack("true"); - } else { - cart.setTableId(tableId); - cart.setPackFee(BigDecimal.ZERO); - } - - TbProductSkuWithBLOBs tbProduct; - if (!"-999".equals(cart.getProductId())) { - tbProduct = productSkuMapper.selectByPrimaryKey(Integer.valueOf(cart.getSkuId())); - TbProduct tbProduct1 = tbProductMapper.selectById(Integer.valueOf(tbProduct.getProductId())); - // 判断商品是否已下架 - if (tbProduct.getIsGrounding().equals(0)) { - JSONObject jsonObject1 = new JSONObject(); - jsonObject1.put("status", "fail"); - jsonObject1.put("msg", "商品已下架:" + tbProduct1.getName()); - jsonObject1.put("data", new ArrayList<>()); - PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), tableCartKey, jsonObject.getString("userId"), true); - continue; - } - - log.info("下单,开始校验库存预警,购物车id:{}", cart.getId()); - CompletableFuture.runAsync(() -> checkWarnLineAndSendMsg(tbProduct, tbProduct1, cart.getNumber())); - - log.info("开始修改库存,商品id:{},商品名:{}", tbProduct1.getId(), tbProduct1.getName()); - // 修改库存 - try { - // 首次下单扣除库存 - if (StrUtil.isBlank(cart.getOrderId())) { - if (tbProduct1.getIsStock() == 1) { - productService.updateStock(tbProduct.getProductId(), tbProduct.getId(), cart.getNumber()); - } else { - productService.updateStockAndNoCheck(tbProduct.getProductId(), tbProduct.getId(), cart.getNumber()); - } - } - - } catch (Exception e) { - JSONObject jsonObject1 = new JSONObject(); - jsonObject1.put("status", "fail"); - jsonObject1.put("msg", tbProduct1.getName() + "库存不足"); - jsonObject1.put("data", new ArrayList<>()); - PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), tableCartKey, jsonObject.getString("userId"), true); - throw new MsgException((String) jsonObject1.get("msg")); - } - saleAmount = saleAmount.add(tbProduct.getSalePrice()); - } else { - tbProduct = null; - saleAmount = saleAmount.add(shopEatTypeInfoDTO.getShopInfo().getTableFee()); - } - - totalAmount = totalAmount.add(cart.getTotalAmount()); - packAMount = packAMount.add(cart.getPackFee()); - originAmount = originAmount.add(cart.getTotalAmount()); - - TbOrderDetail orderDetail = oldOrderDetailMap.get(cart.getOrderId() + cart.getId()); - if (orderDetail == null) { - orderDetail = new TbOrderDetail(); - hasNewInfo = true; - addOrderDetail.add(orderDetail); - } - orderDetail.setCreateTime(new Date()); - orderDetail.setNum(cart.getNumber()); - orderDetail.setPrice(cart.getSalePrice()); - if (cart.getIsPack().equals("true")) { - orderDetail.setPriceAmount(cart.getTotalAmount().add(cart.getPackFee())); - } else { - orderDetail.setPriceAmount(cart.getTotalAmount()); - } - orderDetail.setProductId(Integer.valueOf(cart.getProductId())); - orderDetail.setProductSkuId(Integer.valueOf(cart.getSkuId())); - orderDetail.setProductSkuName(tbProduct == null ? null : tbProduct.getSpecSnap()); - orderDetail.setProductName(cart.getName()); - orderDetail.setShopId(jsonObject.getInteger("shopId")); - orderDetail.setPackAmount(cart.getPackFee()); - orderDetail.setProductImg(cart.getCoverImg()); - orderDetail.setStatus("unpaid"); - orderDetail.setIsVip(cart.getIsVip()); - orderDetail.setCartId(cart.getId()); - if (StringUtils.isNotEmpty(cart.getOrderId())) { - orderId = Integer.valueOf(cart.getOrderId()); - } - orderDetail.setUseType(shopEatTypeInfoDTO.getUseType()); - if (orderDetail.getPlaceNum() == null) { - orderDetail.setPlaceNum(currentPlaceNum); - } - - // 设置下单次数 - if (cart.getPlaceNum() == null) { - cart.setPlaceNum(currentPlaceNum); - } - - orderDetails.add(orderDetail); - cart.setStatus(shopEatTypeInfoDTO.isDineInAfter() ? "create" : "final"); - cart.setUpdatedAt(DateUtil.current()); - - if (!TableConstant.CART_SEAT_ID.equals(cart.getProductId()) || !shopEatTypeInfoDTO.getUseType().equals(OrderUseTypeEnum.TAKEOUT.getValue())) { - cart.setUseType(shopEatTypeInfoDTO.getUseType()); - } - - if (cart.getId() != null) { - mpCashierCartMapper.updateById(cart); - } else { - mpCashierCartMapper.insert(cart); - } - } - - //生成订单 - TbOrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId); - - if (orderInfo != null) { - log.info("订单状态:" + orderInfo.getStatus()); + // 获取订单信息 + TbOrderInfo orderInfo = null; + if (cartInfoDTO.getOrderId() != null) { + orderInfo = mpOrderInfoMapper.selectById(cartInfoDTO.getOrderId()); if (!"unpaid".equals(orderInfo.getStatus())) { - log.info("开始处理订单"); - responseData.put("status", "fail"); - responseData.put("msg", "订单正在支付中,请稍后再试"); - responseData.put("type", jsonObject.getString("type")); - responseData.put("data", ""); - PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(responseData.toString(), tableCartKey, jsonObject.getString("userId"), true); - log.info("消息推送"); return Result.fail("订单正在支付中,请稍后再试"); } - orderInfo.setUpdatedAt(System.currentTimeMillis()); - orderInfo.setSettlementAmount(totalAmount); - orderInfo.setUserCouponId(couponId); - orderInfo.setUserCouponAmount(couponAmount); - orderInfo.setAmount(totalAmount); - orderInfo.setOriginAmount(originAmount); - orderInfo.setOrderAmount(totalAmount.add(packAMount)); - orderInfo.setFreightAmount(BigDecimal.ZERO); - orderInfo.setProductAmount(saleAmount); - orderInfo.setRemark(remark); - if (StrUtil.isNotBlank(remark)) { - orderInfo.setRemark(remark); - } - orderInfo.setUserId(userId); - if (hasNewInfo) { - orderInfo.setPlaceNum(currentPlaceNum); - } - orderInfo.setUseType(shopEatTypeInfoDTO.getUseType()); - orderInfo.setSeatCount(seatNum); - orderInfo.setSeatAmount(seatCost); - orderInfo.setSendType(sendType); - mpOrderInfoMapper.updateById(orderInfo); - } else { - orderInfo = getOrder(totalAmount, packAMount, shopTable, tbMerchantAccount.getId().toString(), jsonObject, originAmount); - orderInfo.setMerchantId(String.valueOf(tbMerchantAccount.getId())); - orderInfo.setUserCouponId(couponId); - orderInfo.setOriginAmount(originAmount); - orderInfo.setUserCouponAmount(couponAmount); - if (StrUtil.isNotBlank(remark)) { - orderInfo.setRemark(remark); - } - orderInfo.setUserId(userId); - orderInfo.setPlaceNum(currentPlaceNum); - orderInfo.setUseType(shopEatTypeInfoDTO.getUseType()); - orderInfo.setSeatCount(seatNum); - orderInfo.setSeatAmount(seatCost); + // 返还上次使用的券 + returnCoupon(orderInfo); + } - JSONObject object = new JSONObject(); - String outNumber = redisUtil.getMessage(RedisCst.OUT_NUMBER.concat(jsonObject.getString("shopId"))); - Integer number = 1; - if (Objects.isNull(outNumber)) { - object.put("outNumber", number); - object.put("times", DateUtils.getDay()); - } else { - object = JSONObject.parseObject(outNumber); - if (object.getString("times").equals(DateUtils.getDay())) { - number = object.getInteger("outNumber") + 1; - object.put("outNumber", number); - } else { - object.put("outNumber", number); - object.put("times", DateUtils.getDay()); - } - } - orderInfo.setOutNumber(number + ""); - orderInfo.setSendType(sendType); - redisUtil.saveMessage(RedisCst.OUT_NUMBER.concat(jsonObject.getString("shopId")), object.toString()); + // 获取优惠券信息 + OrderCouponInfoDTO couponInfo = null; + BigDecimal discountAmount = BigDecimal.ZERO; + if (!orderDTO.getUserCouponInfos().isEmpty()) { + // 获取优惠券信息 + couponInfo = getCouponInfo(tbShopUser, orderDTO.getShopId(), orderDTO.getUserCouponInfos(), + cartInfoDTO.getNewAddTotalAmount(), cartInfoDTO.getNewCashierCarts().stream().map(TbCashierCart::getProductId).collect(Collectors.toSet())); + + // 根据优惠券信息重新计算购物车相关价格 + discountAmount = calcCartPriceWithCoupon(cartInfoDTO, couponInfo, Integer.valueOf(couponInfo.getShopUser().getId())); + } + + // 创建订单详情数据 + OrderPriceDTO detailPriceDTO = createOrderDetailWithCoupon(cartInfoDTO.getCashierCarts(), cartInfoDTO.getOrderId(), orderDTO.getShopId(), shopEatTypeInfoDTO); + detailPriceDTO.setProductDiscountAmount(discountAmount); + + // 是否是第一次创建订单 + orderInfo = createOrderInfoWithCoupon(orderDTO, detailPriceDTO, shopEatTypeInfoDTO, + orderInfo, cartInfoDTO.getSeatCart(), tbShopUser, shopTable, couponInfo); + + if (orderInfo.getId() == null) { mpOrderInfoMapper.insert(orderInfo); - orderId = orderInfo.getId(); } - for (TbOrderDetail orderDetail : orderDetails) { - orderDetail.setOrderId(orderInfo.getId()); - if (orderDetail.getId() != null) { - mpOrderDetailMapper.updateById(orderDetail); - } else { - mpOrderDetailMapper.insert(orderDetail); + // 计算订单满减优惠 + TbActivateOutRecord outRecord = calcOrderInfoDiscount(orderDTO, orderInfo, couponInfo, Integer.valueOf(tbShopUser.getId())); + if (couponInfo != null) { + if (outRecord != null) { + couponInfo.getOutRecordList().add(outRecord); } + orderInfo.setCouponInfoList(JSONObject.toJSONString(couponInfo)); } - // 去除餐位费信息 - for (TbCashierCart cashierCart : cashierCartList) { - cashierCart.setUpdatedAt(System.currentTimeMillis()); - cashierCart.setOrderId(orderId + ""); - if ((!TableConstant.CART_SEAT_ID.equals(cashierCart.getProductId()) && !shopEatTypeInfoDTO.isDineInAfter()) - || shopEatTypeInfoDTO.isDineInBefore()) { - cashierCart.setStatus("closed"); - } - cashierCart.setPlaceNum(cashierCart.getPlaceNum() == null ? currentPlaceNum : cashierCart.getPlaceNum()); - mpCashierCartMapper.updateById(cashierCart); + + + // 修改订单详情并打票 + updateDetailAndPrint(orderInfo, detailPriceDTO, shopEatTypeInfoDTO); + + // 修改购物车状态和库存 + updateCartAndStock(cartInfoDTO.getNewCashierCarts(), orderInfo, shopEatTypeInfoDTO); + + // 推送耗材信息 + pushConsMsg(orderInfo, cartInfoDTO.getNewCashierCarts()); + + updateTableState(shopEatTypeInfoDTO, orderInfo, cartInfoDTO.getCashierCarts(), cartInfoDTO.getSeatCart()); + + // 消耗优惠券 + if (!orderDTO.getUserCouponInfos().isEmpty() && couponInfo != null) { + consumeCoupon(couponInfo.getOutRecordList(), Integer.valueOf(tbShopUser.getId()), orderInfo); } - cashierCartList = cashierCartList.stream().filter(item -> !"-999".equals(item.getProductId())).collect(Collectors.toList()); + mpOrderInfoMapper.updateById(orderInfo); - - // 删除旧的餐位费信息 -// if (shopEatTypeInfoDTO.isTakeout() && seatCartInfo != null) { -// cashierCartMapper.deleteByPrimaryKey(seatCartInfo.getId()); -// } - - // 打印票据 - if (!addOrderDetail.isEmpty() && shopEatTypeInfoDTO.isDineInAfter()) { - log.info("待打印菜品信息: {}", addOrderDetail); - mQUtils.printDishesTicket(orderInfo.getId(), false, addOrderDetail.toArray(new TbOrderDetail[0])); - } - - if (!removeOrderDetailList.isEmpty()) { - log.info("待打印退菜菜品信息: {}", removeOrderDetailList); - // 退单票 - mpOrderDetailMapper.deleteBatchIds(removeOrderDetailList.stream().map(TbOrderDetail::getId).collect(Collectors.toList())); - if (shopEatTypeInfoDTO.isDineInAfter()) { - mQUtils.printDishesTicket(orderInfo.getId(), true, removeOrderDetailList.toArray(new TbOrderDetail[0])); - } - } - - // 修改台桌状态 - if (!shopEatTypeInfoDTO.isTakeout() && StrUtil.isNotBlank(tableId)) { - mpShopTableService.updateStateByQrcode(tableId, TableConstant.ShopTable.State.USING); - } - - // 发送mq消息 - JSONObject jsonObject2 = new JSONObject(); - jsonObject2.put("orderId", orderInfo.getId()); - jsonObject2.put("type", "create"); - log.info("开始发送mq消息,消耗耗材,消息内容:{}", jsonObject2); - producer.cons(jsonObject2.toString()); - - redisUtil.saveMessage(tableCartKey, new JSONArray().toJSONString()); - orderInfo.setDetailList(orderDetails); - responseData.put("status", "success"); - responseData.put("msg", "成功"); - responseData.put("type", jsonObject.getString("type")); - responseData.put("data", orderInfo); + String tableCartKey = RedisCst.getTableCartKey(shopId, shopEatTypeInfoDTO.isOpenDineIn() ? tableId : null, Integer.valueOf(userId)); redisUtil.deleteByKey(tableCartKey); - PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(responseData.toString(), tableCartKey, jsonObject.getString("userId"), true); - - responseData.put("status", "success"); - responseData.put("msg", "成功"); - responseData.put("type", "order"); - responseData.put("amount", BigDecimal.ZERO); - responseData.put("data", new JSONArray()); -// PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject12.toString(), jsonObject.getString("tableId").concat("-").concat(shopId), "", false); - PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(responseData.toString(), tableCartKey, jsonObject.getString("userId")); - - redisUtil.saveMessage(RedisCst.ORDER_EXPIRED.concat(orderId.toString()), orderId.toString(), 60 * 16L); - List finalCashierCartList = cashierCartList; - ThreadUtil.execAsync(() -> { - ThreadUtil.sleep(5, TimeUnit.SECONDS); - for (TbCashierCart cashierCart : finalCashierCartList) { - // 发送判断耗材是否耗尽消息 - JSONObject objectMsg = new JSONObject(); - objectMsg.put("skuId", Integer.valueOf(cashierCart.getSkuId())); - objectMsg.put("shopId", Integer.valueOf(cashierCart.getShopId())); - producer.con_msg(objectMsg.toString()); - } - }); - return Result.successWithData(orderInfo); } catch (Exception e) { log.info("长链接错误 createOrder{}", e.getMessage()); e.printStackTrace(); + throw e; } - - return Result.fail("失败"); } - private TbOrderInfo getOrder(BigDecimal totalAmount, BigDecimal packAMount, - TbShopTable shopTable, String merchantId, JSONObject jsonObject, BigDecimal originAmount) { - TbOrderInfo orderInfo = new TbOrderInfo(); - String orderNo = generateOrderNumber(jsonObject.getString("environment")); - orderInfo.setOrderNo(orderNo); - orderInfo.setSettlementAmount(totalAmount); - orderInfo.setPackFee(packAMount); - orderInfo.setOriginAmount(originAmount); - orderInfo.setProductAmount(originAmount); - orderInfo.setAmount(totalAmount); - orderInfo.setOrderAmount(totalAmount.add(packAMount)); - orderInfo.setPayAmount(BigDecimal.ZERO); - orderInfo.setRefundAmount(new BigDecimal("0.00")); - orderInfo.setTableId(jsonObject.getString("tableId")); - orderInfo.setSendType("table"); - orderInfo.setOrderType("miniapp"); - orderInfo.setTradeDay(DateUtils.getDay()); - orderInfo.setStatus("unpaid"); - orderInfo.setShopId(jsonObject.getString("shopId")); - orderInfo.setUserId(jsonObject.getString("userId")); - orderInfo.setCreatedAt(Instant.now().toEpochMilli()); - orderInfo.setSystemTime(Instant.now().toEpochMilli()); - orderInfo.setUpdatedAt(Instant.now().toEpochMilli()); - orderInfo.setIsAccepted((byte) 1); - if (Objects.nonNull(shopTable)) { - orderInfo.setTableName(shopTable.getName()); + private void returnCoupon(TbOrderInfo orderInfo) { + // 返还优惠券 + if (StrUtil.isNotBlank(orderInfo.getCouponInfoList())) { + OrderCouponInfoDTO couponInfoDTO = JSONObject.parseObject(orderInfo.getCouponInfoList(), OrderCouponInfoDTO.class); + // 券返还 + if (!couponInfoDTO.getOutRecordList().isEmpty()) { + couponInfoDTO.getOutRecordList().forEach(item -> { + item.setRefNum(item.getUseNum()); + }); + shopCouponService.refund(couponInfoDTO.getOutRecordList()); + couponInfoDTO.setOutRecordList(new ArrayList<>()); + orderInfo.setCouponInfoList(JSONObject.toJSONString(couponInfoDTO)); + } + } + + } + + private void consumeCoupon(List outRecordList, Integer memberId, TbOrderInfo orderInfo) { + boolean use = shopCouponService.use(Integer.valueOf(orderInfo.getShopId()), orderInfo.getId(), memberId, outRecordList); + if (!use) { + throw new MsgException("消耗券失败"); } - orderInfo.setMerchantId(merchantId); - return orderInfo; } public String generateOrderNumber(String environment) { @@ -1170,12 +1418,6 @@ public class CartService { .set(TbCashierCart::getStatus, "closed")); } String tableCartKey = RedisCst.getTableCartKey(shopId, tableId, userId); -// String message = redisUtil.getMessage(tableCartKey); -// if (StrUtil.isNotBlank(message)) { -// JSONArray jsonArray = JSONObject.parseArray(message); -// List collect = jsonArray.stream().filter(info -> "-999".equals(((JSONObject) info).getString("productId"))).collect(Collectors.toList()); -// redisUtil.saveMessage(tableCartKey, new JSONArray().toJSONString()); -// } redisUtil.saveMessage(tableCartKey, new JSONArray().toJSONString()); JSONObject jsonObject1 = new JSONObject(); jsonObject1.put("status", "success"); @@ -1190,166 +1432,6 @@ public class CartService { } } - @Transactional(rollbackFor = Exception.class) - public void pendingOrder(JSONObject jsonObject) throws IOException { - try { - String shopId = jsonObject.getString("shopId"); - String tableId = jsonObject.getString("tableId"); - String userId = jsonObject.getString("userId"); - String tableCartKey = RedisCst.getTableCartKey(shopId, tableId, Integer.valueOf(userId)); - JSONArray array = JSON.parseArray(redisUtil.getMessage(tableCartKey)); - List ids = new ArrayList<>(); - BigDecimal totalAmount = BigDecimal.ZERO; - BigDecimal packAMount = BigDecimal.ZERO; - BigDecimal originAmount = BigDecimal.ZERO; - BigDecimal saleAmount = BigDecimal.ZERO; - String couponId = ""; - BigDecimal couponAmount = BigDecimal.ZERO; - Map skuMap = new HashMap<>(); - List orderDetails = new ArrayList<>(); - Integer orderId = 0; - TbMerchantAccount tbMerchantAccount = merchantAccountMapper.selectByShopId(jsonObject.getString("shopId")); - if (tbMerchantAccount == null) { - throw new MsgException("生成订单错误"); - } - - TbUserInfo tbUserInfo = userInfoMapper.selectByPrimaryKey(Integer.valueOf(userId)); - if (tbUserInfo == null) { - throw new MsgException("生成订单失败"); - } - for (int i = 0; i < array.size(); i++) { - JSONObject object = array.getJSONObject(i); - TbCashierCart cashierCart = JSONUtil.parseJSONStr2T(object.toJSONString(), TbCashierCart.class); - TbProductSkuWithBLOBs tbProduct = productSkuMapper.selectByPrimaryKey(Integer.valueOf(cashierCart.getSkuId())); - totalAmount = totalAmount.add(cashierCart.getTotalAmount()); - packAMount = packAMount.add(cashierCart.getPackFee()); - originAmount = originAmount.add(cashierCart.getTotalAmount()); - if (Objects.nonNull(tbProduct)) { - saleAmount = saleAmount.add(tbProduct.getSalePrice()); - } - skuMap.put(tbProduct.getId(), tbProduct); - TbOrderDetail orderDetail = new TbOrderDetail(); - orderDetail.setCreateTime(new Date()); - orderDetail.setNum(cashierCart.getNumber()); - orderDetail.setPrice(cashierCart.getSalePrice()); - if (cashierCart.getIsPack().equals("true")) { - orderDetail.setPriceAmount(cashierCart.getTotalAmount().add(cashierCart.getPackFee())); - } else { - orderDetail.setPriceAmount(cashierCart.getTotalAmount()); - } - orderDetail.setProductId(Integer.valueOf(cashierCart.getProductId())); - orderDetail.setProductSkuId(Integer.valueOf(cashierCart.getSkuId())); - orderDetail.setProductSkuName(tbProduct.getSpecSnap()); - orderDetail.setProductName(cashierCart.getName()); - orderDetail.setShopId(jsonObject.getInteger("shopId")); - orderDetail.setPackAmount(cashierCart.getPackFee()); - orderDetail.setProductImg(cashierCart.getCoverImg()); - orderDetail.setStatus("unpaid"); - if (StringUtils.isNotEmpty(cashierCart.getOrderId())) { - orderId = Integer.valueOf(cashierCart.getOrderId()); - - } - orderDetails.add(orderDetail); - if (StringUtils.isNotEmpty(cashierCart.getOrderId())) { - orderId = Integer.valueOf(cashierCart.getOrderId()); - } - } - //总金额 - TbShopTable shopTable = shopTableMapper.selectQRcode(jsonObject.getString("tableId")); - //生成订单 - TbOrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId); - if (Objects.nonNull(orderInfo)) { - log.info("订单状态:" + orderInfo.getStatus()); - if (!"unpaid".equals(orderInfo.getStatus())) { - log.info("开始处理订单"); - JSONObject jsonObject1 = new JSONObject(); - jsonObject1.put("status", "fail"); - jsonObject1.put("msg", "订单正在支付中,请稍后再试"); - jsonObject1.put("type", jsonObject.getString("type")); - jsonObject1.put("data", ""); - PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), tableCartKey, jsonObject.getString("userId"), true); - log.info("消息推送"); - return; - } - - orderDetailMapper.deleteByOUrderId(orderId); - orderInfo.setUpdatedAt(System.currentTimeMillis()); - orderInfo.setSettlementAmount(totalAmount); - orderInfo.setUserCouponId(couponId); - orderInfo.setUserCouponAmount(couponAmount); - orderInfo.setAmount(totalAmount); - orderInfo.setOriginAmount(originAmount); - orderInfo.setOrderAmount(totalAmount.add(packAMount)); - orderInfo.setFreightAmount(BigDecimal.ZERO); - orderInfo.setProductAmount(saleAmount); - orderInfoMapper.updateByPrimaryKeySelective(orderInfo); - } else { - orderInfo = getOrder(totalAmount, packAMount, shopTable, tbMerchantAccount.getId().toString(), jsonObject, originAmount); - orderInfo.setMerchantId(String.valueOf(tbMerchantAccount.getId())); - orderInfo.setUserCouponId(couponId); - orderInfo.setOriginAmount(originAmount); - orderInfo.setUserCouponAmount(couponAmount); - - JSONObject object = new JSONObject(); - String outNumber = redisUtil.getMessage(RedisCst.OUT_NUMBER.concat(jsonObject.getString("shopId"))); - Integer number = 1; - if (Objects.isNull(outNumber)) { - object.put("outNumber", number); - object.put("times", DateUtils.getDay()); - } else { - object = JSONObject.parseObject(outNumber); - if (object.getString("times").equals(DateUtils.getDay())) { - number = object.getInteger("outNumber") + 1; - object.put("outNumber", number); - } else { - object.put("outNumber", number); - object.put("times", DateUtils.getDay()); - } - } - orderInfo.setOutNumber(number + ""); - redisUtil.saveMessage(RedisCst.OUT_NUMBER.concat(jsonObject.getString("shopId")), object.toString()); - - - orderInfoMapper.insert(orderInfo); - orderId = orderInfo.getId(); - } - for (TbOrderDetail orderDetail : orderDetails) { - orderDetail.setOrderId(orderId); - orderDetailMapper.insert(orderDetail); - } - for (int i = 0; i < array.size(); i++) { - JSONObject object = array.getJSONObject(i); - TbCashierCart cashierCart = JSONUtil.parseJSONStr2T(object.toJSONString(), TbCashierCart.class); - cashierCart.setUpdatedAt(System.currentTimeMillis()); - cashierCart.setOrderId(orderId + ""); - cashierCart.setStatus("closed"); - cashierCartMapper.updateByPrimaryKeySelective(cashierCart); - object.put("updatedAt", System.currentTimeMillis()); - object.put("orderId", orderId + ""); - } - redisUtil.saveMessage(tableCartKey, array.toJSONString()); - orderInfo.setDetailList(orderDetails); - JSONObject jsonObject1 = new JSONObject(); - jsonObject1.put("status", "success"); - jsonObject1.put("msg", "成功"); - jsonObject1.put("type", jsonObject.getString("type")); - jsonObject1.put("data", orderInfo); - redisUtil.deleteByKey(tableCartKey); - redisUtil.saveMessage(RedisCst.TABLE_ORDER.concat(orderInfo.getOrderNo()), JSONObject.toJSONString(orderInfo), 24 * 60 * 60L); - PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), tableCartKey, jsonObject.getString("userId"), true); - JSONObject jsonObject12 = new JSONObject(); - jsonObject12.put("status", "success"); - jsonObject12.put("msg", "成功"); - jsonObject12.put("type", "order"); - jsonObject12.put("amount", BigDecimal.ZERO); - - jsonObject12.put("data", new JSONArray()); - PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject12.toString(), tableCartKey, "", false); - } catch (Exception e) { - log.info("长链接错误 pendingOrder{}", e.getMessage()); - e.printStackTrace(); - } - } public void queryCart(JSONObject jsonObject) { try { @@ -1413,7 +1495,7 @@ public class CartService { } }); - }else { + } else { // 查询购物车所有信息 ShopEatTypeInfoDTO shopEatTypeInfoDTO = shopUtils.checkEatModel(choseEatModelDTO.getTableId(), choseEatModelDTO.getShopId()); LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper() diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/PayService.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/PayService.java index 9ce9312..15a5ce2 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/service/PayService.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/PayService.java @@ -12,10 +12,7 @@ import com.chaozhanggui.system.cashierservice.constant.TableConstant; import com.chaozhanggui.system.cashierservice.dao.*; import com.chaozhanggui.system.cashierservice.entity.Enum.OrderUseTypeEnum; import com.chaozhanggui.system.cashierservice.entity.*; -import com.chaozhanggui.system.cashierservice.entity.dto.MemberInDTO; -import com.chaozhanggui.system.cashierservice.entity.dto.OrderPayDTO; -import com.chaozhanggui.system.cashierservice.entity.dto.ReturnGroupOrderDto; -import com.chaozhanggui.system.cashierservice.entity.dto.ShopEatTypeInfoDTO; +import com.chaozhanggui.system.cashierservice.entity.dto.*; import com.chaozhanggui.system.cashierservice.entity.vo.ActivateInInfoVO; import com.chaozhanggui.system.cashierservice.entity.vo.ShopUserListVo; import com.chaozhanggui.system.cashierservice.entity.vo.TbUserCouponVo; @@ -28,6 +25,7 @@ import com.chaozhanggui.system.cashierservice.netty.PushToClientChannelHandlerAd import com.chaozhanggui.system.cashierservice.rabbit.RabbitProducer; import com.chaozhanggui.system.cashierservice.redis.RedisCst; import com.chaozhanggui.system.cashierservice.redis.RedisUtil; +import com.chaozhanggui.system.cashierservice.service.impl.TbMemberPointsServiceImpl; import com.chaozhanggui.system.cashierservice.sign.CodeEnum; import com.chaozhanggui.system.cashierservice.sign.Result; import com.chaozhanggui.system.cashierservice.thirdpay.resp.OrderStatusQueryResp; @@ -192,6 +190,8 @@ public class PayService { private final TbFreeDineConfigService freeDineConfigService; private final TbShopCouponService shopCouponService; private final MpMemberInMapper mpMemberInMapper; + private final TbMemberPointsServiceImpl memberPointsService; + @Qualifier("tbShopCouponService") @Autowired private TbShopCouponService tbShopCouponService; @@ -203,12 +203,13 @@ public class PayService { private TbFreeDineRecordMapper tbFreeDineRecordMapper; private final TbFreeDineRecordService freeDineRecordService; - public PayService(@Qualifier("tbShopSongOrderServiceImpl") TbShopSongOrderService shopSongOrderService, MpShopTableService mpShopTableService, TbFreeDineConfigService freeDineConfigService, TbShopCouponService shopCouponService, MpMemberInMapper mpMemberInMapper, TbFreeDineRecordService freeDineRecordService) { + public PayService(@Qualifier("tbShopSongOrderServiceImpl") TbShopSongOrderService shopSongOrderService, MpShopTableService mpShopTableService, TbFreeDineConfigService freeDineConfigService, TbShopCouponService shopCouponService, MpMemberInMapper mpMemberInMapper, TbMemberPointsServiceImpl memberPointsService, TbFreeDineRecordService freeDineRecordService) { this.shopSongOrderService = shopSongOrderService; this.mpShopTableService = mpShopTableService; this.freeDineConfigService = freeDineConfigService; this.shopCouponService = shopCouponService; this.mpMemberInMapper = mpMemberInMapper; + this.memberPointsService = memberPointsService; this.freeDineRecordService = freeDineRecordService; } @@ -381,7 +382,7 @@ public class PayService { throw new MsgException("支付失败"); } - private BigDecimal getFreeDineOrderInfo(MemberInDTO payDTO) { + private BigDecimal getFreeDineOrderInfo(MemberInDTO payDTO, TbUserInfo userInfo) { TbOrderInfo orderInfo = mpOrderInfoMapper.selectOne(new LambdaQueryWrapper() .eq(TbOrderInfo::getId, payDTO.getOrderId()) .in(TbOrderInfo::getStatus, TableConstant.OrderInfo.Status.UNPAID.getValue(), TableConstant.OrderInfo.Status.PAYING.getValue())); @@ -405,7 +406,7 @@ public class PayService { throw new MsgException("当前店铺未开启与优惠券同享"); } - if (payDTO.isUsePoints() && freeDineConfig.getWithPoints() == 0) { + if (payDTO.getPointsNum() != null && freeDineConfig.getWithPoints() == 0) { throw new MsgException("当前店铺未开启与积分同享"); } @@ -415,6 +416,25 @@ public class PayService { } BigDecimal shouldPayAmount = orderInfo.getOriginAmount().multiply(BigDecimal.valueOf(freeDineConfig.getRechargeTimes())); + + // 霸王餐积分抵扣 + if (payDTO.getPointsNum() != null) { + OrderDeductionPointsDTO memberUsablePoints = memberPointsService.getMemberUsablePoints(Long.valueOf(userInfo.getId()), shouldPayAmount); + if (!memberUsablePoints.getUsable()) { + throw new MsgException(memberUsablePoints.getUnusableReason()); + } + if (payDTO.getPointsNum() < memberUsablePoints.getMinDeductionPoints() || payDTO.getPointsNum() > memberUsablePoints.getMaxUsablePoints()) { + throw new MsgException("可抵扣积分区间为: [" + memberUsablePoints.getMinDeductionPoints() + "-" + memberUsablePoints.getMaxUsablePoints() + "]"); + } + + BigDecimal discountAmount = memberPointsService.calcDeductionAmount(Long.valueOf(userInfo.getId()), shouldPayAmount, payDTO.getPointsNum()); + orderInfo.setPointsNum(payDTO.getPointsNum()); + orderInfo.setPointsDiscountAmount(discountAmount); + shouldPayAmount = shouldPayAmount.subtract(discountAmount); + memberPointsService.deductPoints(Long.valueOf(userInfo.getId()), payDTO.getPointsNum(), "霸王餐充值抵扣", Long.valueOf(orderInfo.getId())); + } + + // 霸王餐优惠券抵扣 TbFreeDineRecord record = tbFreeDineRecordMapper.selectOne(new LambdaQueryWrapper().eq(TbFreeDineRecord::getOrderId, orderInfo.getId())); if (record == null) { record = new TbFreeDineRecord(); @@ -423,41 +443,37 @@ public class PayService { record.setOrderId(orderInfo.getId()); record.setOrderAmount(orderInfo.getOrderAmount()); if (!payDTO.getUserCouponIds().isEmpty()) { - List userCouponList = shopCouponService.getActivateCouponByAmount(Integer.valueOf(orderInfo.getShopId()), String.valueOf(payDTO.getUserId()), shouldPayAmount); - if (userCouponList.isEmpty()) { - throw new MsgException("存在不可用优惠券"); - } - - ArrayList activateInInfoVOS = new ArrayList<>(); - for (Integer userCouponId : payDTO.getUserCouponIds()) { - TbUserCouponVo userCouponVo = userCouponList.stream().filter(item -> item.getId().equals(userCouponId)).findFirst().orElse(null); - if (userCouponVo == null) { + List userCouponList = shopCouponService.getActivateCouponByAmount(Integer.valueOf(orderInfo.getShopId()), String.valueOf(payDTO.getUserId()), shouldPayAmount); + if (userCouponList.isEmpty()) { throw new MsgException("存在不可用优惠券"); } - shouldPayAmount = shouldPayAmount.subtract(userCouponVo.getDiscountAmount()); - ActivateInInfoVO activateInInfoVO = new ActivateInInfoVO() - .setId(userCouponVo.getId()) - .setCouponId(userCouponVo.getCouponId()) - .setNum(1); - activateInInfoVOS.add(activateInInfoVO); - } + ArrayList activateInInfoVOS = new ArrayList<>(); + for (Integer userCouponId : payDTO.getUserCouponIds()) { + TbUserCouponVo userCouponVo = userCouponList.stream().filter(item -> item.getId().equals(userCouponId)).findFirst().orElse(null); + if (userCouponVo == null) { + throw new MsgException("存在不可用优惠券"); + } - List tbShopCoupons = mpShopCouponMapper.selectBatchIds(activateInInfoVOS.stream().map(ActivateInInfoVO::getCouponId).collect(Collectors.toList())); - if (tbShopCoupons.size() != payDTO.getUserCouponIds().size()) { - throw new MsgException("存在不可用优惠券"); - } + shouldPayAmount = shouldPayAmount.subtract(userCouponVo.getDiscountAmount()); + ActivateInInfoVO activateInInfoVO = new ActivateInInfoVO() + .setId(userCouponVo.getId()) + .setCouponId(userCouponVo.getCouponId()) + .setNum(1); + activateInInfoVOS.add(activateInInfoVO); + } - // 设置优惠券信息 - orderInfo.setActivateInInfoList(JSONObject.toJSONString(activateInInfoVOS)); - orderInfo.setUserCouponAmount(BigDecimal.valueOf(tbShopCoupons.stream().map(TbShopCoupon::getDiscountAmount).reduce(0, Integer::sum))); - record.setCouponInfo(JSONObject.toJSONString(userCouponList)); + List tbShopCoupons = mpShopCouponMapper.selectBatchIds(activateInInfoVOS.stream().map(ActivateInInfoVO::getCouponId).collect(Collectors.toList())); + if (tbShopCoupons.size() != payDTO.getUserCouponIds().size()) { + throw new MsgException("存在不可用优惠券"); + } + + // 设置优惠券信息 +// orderInfo.seta(JSONObject.toJSONString(activateInInfoVOS)); + orderInfo.setUserCouponAmount(BigDecimal.valueOf(tbShopCoupons.stream().map(TbShopCoupon::getDiscountAmount).reduce(0, Integer::sum))); + record.setCouponInfo(JSONObject.toJSONString(userCouponList)); } - // TODO 霸王餐积分 - if (payDTO.isUsePoints()) { - - } record.setRechargeAmount(shouldPayAmount); record.setVipUserId(payDTO.getUserId()); record.setShopId(Integer.valueOf(orderInfo.getShopId())); @@ -469,8 +485,6 @@ public class PayService { return shouldPayAmount; } - private void createFreeDineOrder(TbOrderInfo orderInfo) { - } @Transactional(rollbackFor = Exception.class) public Result payOrder(String openId, OrderPayDTO payDTO, String ip) throws Exception { @@ -1057,13 +1071,12 @@ public class PayService { BigDecimal payAmount; TbMemberIn memberIn = new TbMemberIn(); if (memberInDTO.getOrderId() != null) { - payAmount = getFreeDineOrderInfo(memberInDTO); + payAmount = getFreeDineOrderInfo(memberInDTO, userInfo); memberIn.setType(TableConstant.MemberIn.Type.FREE_DINE.getValue()); // 会员充值 }else { payAmount = memberInDTO.getAmount().setScale(2, RoundingMode.DOWN); memberIn.setType(TableConstant.MemberIn.Type.NORMAL.getValue()); - } memberIn.setAmount(payAmount); @@ -1560,23 +1573,23 @@ public class PayService { Integer shopId = Integer.valueOf(orderInfo.getShopId()); // 销毁使用的优惠券 - if (StrUtil.isNotBlank(orderInfo.getActivateInInfoList())) { - ArrayList activateOutRecords = new ArrayList<>(); - JSONArray activateInfoList = JSONObject.parseArray(orderInfo.getActivateInInfoList()); - activateInfoList.forEach(item -> { - ActivateInInfoVO infoVO = ((JSONObject)item).toJavaObject(ActivateInInfoVO.class); - TbActivateOutRecord tbActivateOutRecord = new TbActivateOutRecord(); - tbActivateOutRecord.setShopId(shopId); - tbActivateOutRecord.setGiveId(infoVO.getId()); - tbActivateOutRecord.setVipUserId(Integer.valueOf(orderInfo.getUserId())); - tbActivateOutRecord.setType(TableConstant.ActivateOutRecord.Type.FULL_REDUCTION.getValue()); - tbActivateOutRecord.setUseNum(infoVO.getNum()); - tbActivateOutRecord.setStatus(TableConstant.ActivateOutRecord.Status.CLOSED.getValue()); - tbActivateOutRecord.setCreateTime(DateUtil.date()); - activateOutRecords.add(tbActivateOutRecord); - }); - shopCouponService.use(shopId, orderInfo.getId(), Integer.valueOf(orderInfo.getUserId()), activateOutRecords); - } +// if (StrUtil.isNotBlank(orderInfo.getActivateInInfoList())) { +// ArrayList activateOutRecords = new ArrayList<>(); +// JSONArray activateInfoList = JSONObject.parseArray(orderInfo.getActivateInInfoList()); +// activateInfoList.forEach(item -> { +// ActivateInInfoVO infoVO = ((JSONObject)item).toJavaObject(ActivateInInfoVO.class); +// TbActivateOutRecord tbActivateOutRecord = new TbActivateOutRecord(); +// tbActivateOutRecord.setShopId(shopId); +// tbActivateOutRecord.setGiveId(infoVO.getId()); +// tbActivateOutRecord.setVipUserId(Integer.valueOf(orderInfo.getMemberId())); +// tbActivateOutRecord.setType(TableConstant.ActivateOutRecord.Type.FULL_REDUCTION.getValue()); +// tbActivateOutRecord.setUseNum(infoVO.getNum()); +// tbActivateOutRecord.setStatus(TableConstant.ActivateOutRecord.Status.CLOSED.getValue()); +// tbActivateOutRecord.setCreateTime(DateUtil.date()); +// activateOutRecords.add(tbActivateOutRecord); +// }); +// shopCouponService.use(shopId, orderInfo.getId(), Integer.valueOf(orderInfo.getUserId()), activateOutRecords); +// } // 更改订单状态 orderSuccessPay(orderInfo, payType, payOrderNo); diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/TbCashierCartService.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/TbCashierCartService.java new file mode 100644 index 0000000..48fac1a --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/TbCashierCartService.java @@ -0,0 +1,18 @@ +package com.chaozhanggui.system.cashierservice.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.chaozhanggui.system.cashierservice.entity.TbCashierCart; +import com.chaozhanggui.system.cashierservice.entity.dto.ShopEatTypeInfoDTO; + +import java.util.List; + +public interface TbCashierCartService extends IService { + /** + * 根据就餐类型获取购物车信息 + * @param shopEatTypeInfoDTO 就餐类型信息 + * @param userId 用户id + * @return 购物车信息 + */ + List selectByShopEatTypeInfo(ShopEatTypeInfoDTO shopEatTypeInfoDTO, Integer userId); + +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/TbOrderDetailService.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/TbOrderDetailService.java new file mode 100644 index 0000000..e65c57e --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/TbOrderDetailService.java @@ -0,0 +1,21 @@ +package com.chaozhanggui.system.cashierservice.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.chaozhanggui.system.cashierservice.constant.TableConstant; +import com.chaozhanggui.system.cashierservice.entity.TbCashierCart; +import com.chaozhanggui.system.cashierservice.entity.TbOrderDetail; +import com.chaozhanggui.system.cashierservice.entity.dto.ShopEatTypeInfoDTO; + +import java.util.List; + +public interface TbOrderDetailService extends IService { + + /** + * 根据购物车id和订单id查询订单详情 + * @param shopId 店铺id + * @param cartIdList 购物车id + * @param orderId 订单id + * @return 详情信息 + */ + List selectByCartIdOrOrderId(Integer shopId, List cartIdList, Integer orderId); +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/TbShopCouponService.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/TbShopCouponService.java index 51956b0..ba3dd36 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/service/TbShopCouponService.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/TbShopCouponService.java @@ -2,6 +2,7 @@ package com.chaozhanggui.system.cashierservice.service; import com.chaozhanggui.system.cashierservice.entity.TbActivateOutRecord; import com.chaozhanggui.system.cashierservice.entity.TbOrderInfo; +import com.chaozhanggui.system.cashierservice.entity.TbShopUser; import com.chaozhanggui.system.cashierservice.entity.dto.CouponDto; import com.chaozhanggui.system.cashierservice.entity.dto.CouponUseDto; import com.chaozhanggui.system.cashierservice.entity.vo.TbUserCouponVo; @@ -10,6 +11,7 @@ import org.springframework.context.annotation.Primary; import java.math.BigDecimal; import java.util.List; +import java.util.Set; /** * 优惠券(TbShopCoupon)表服务接口 @@ -29,4 +31,13 @@ public interface TbShopCouponService { boolean use(Integer shopId,Integer orderId,Integer vipUserId,List param); boolean refund(List param); + + /** + * 根据金额获取可用优惠券数据 + * @param tbShopUser 店铺id + * @param orderAmount 用户id + * @param productIds 商品id + * @return 优惠券信息 + */ + List getActivateCoupon(TbShopUser tbShopUser, BigDecimal orderAmount, Integer shopId, Set productIds); } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/TbShopUserService.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/TbShopUserService.java new file mode 100644 index 0000000..a1df2d8 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/TbShopUserService.java @@ -0,0 +1,18 @@ +package com.chaozhanggui.system.cashierservice.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.chaozhanggui.system.cashierservice.entity.TbCashierCart; +import com.chaozhanggui.system.cashierservice.entity.TbShopUser; +import com.chaozhanggui.system.cashierservice.entity.dto.ShopEatTypeInfoDTO; + +import java.util.List; + +public interface TbShopUserService extends IService { + + /** + * 根据店铺id和用户id获取店铺会员信息 + * @param userId 用户id + * @param shopId 店铺id + */ + TbShopUser selectByUserIdAndShopId(String userId, String shopId); +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/impl/TbCashierCartServiceImpl.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/impl/TbCashierCartServiceImpl.java new file mode 100644 index 0000000..578c21a --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/impl/TbCashierCartServiceImpl.java @@ -0,0 +1,52 @@ +package com.chaozhanggui.system.cashierservice.service.impl; + +import cn.hutool.core.date.DateUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.chaozhanggui.system.cashierservice.entity.TbCashierCart; +import com.chaozhanggui.system.cashierservice.entity.TbShopTable; +import com.chaozhanggui.system.cashierservice.entity.dto.ShopEatTypeInfoDTO; +import com.chaozhanggui.system.cashierservice.exception.MsgException; +import com.chaozhanggui.system.cashierservice.mapper.MpCashierCartMapper; +import com.chaozhanggui.system.cashierservice.service.TbCashierCartService; +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Service; + +import java.util.Collections; +import java.util.List; + +/** +* @author Administrator +* @description 针对表【tb_call_table】的数据库操作Service实现 +* @createDate 2024-09-13 13:44:34 +*/ +@Service +@Primary +public class TbCashierCartServiceImpl extends ServiceImpl + implements TbCashierCartService { + + @Override + public List selectByShopEatTypeInfo(ShopEatTypeInfoDTO shopEatTypeInfoDTO, Integer userId) { + // 查询购物车所有信息 + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper() + .eq(TbCashierCart::getShopId, shopEatTypeInfoDTO.getShopInfo().getId()) + .gt(TbCashierCart::getCreatedAt, DateUtil.offsetDay(DateUtil.date(), -1).getTime()) + .eq(TbCashierCart::getStatus, "create"); + + // 外带模式 + if (shopEatTypeInfoDTO.isTakeout()) { + queryWrapper.eq(TbCashierCart::getUserId, userId); + // 台桌点单 + } else { + queryWrapper.and(q -> q.eq(TbCashierCart::getTableId, shopEatTypeInfoDTO.getTableId()).or().eq(TbCashierCart::getUserId, userId)) + .and(q -> q.eq(TbCashierCart::getUseType, shopEatTypeInfoDTO.getUseType()).or().isNull(TbCashierCart::getUseType)); + } + + // 所有订单信息 + return list(queryWrapper); + } +} + + + + diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/impl/TbMemberPointsServiceImpl.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/impl/TbMemberPointsServiceImpl.java index e207954..cc729fd 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/service/impl/TbMemberPointsServiceImpl.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/impl/TbMemberPointsServiceImpl.java @@ -23,6 +23,7 @@ import com.chaozhanggui.system.cashierservice.service.TbMemberPointsService; import com.chaozhanggui.system.cashierservice.service.TbPointsBasicSettingService; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; +import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -39,6 +40,7 @@ import java.util.Map; * @since 2.0 2024-10-25 */ @Service +@Primary public class TbMemberPointsServiceImpl extends ServiceImpl implements TbMemberPointsService { @Resource @@ -285,4 +287,4 @@ public class TbMemberPointsServiceImpl extends ServiceImpl + implements TbOrderDetailService { + @Override + public List selectByCartIdOrOrderId(Integer shopId, List cartIdList, Integer orderId) { + return list(new LambdaQueryWrapper() + .and(q -> q.in(TbOrderDetail::getCartId, cartIdList).or().eq(TbOrderDetail::getOrderId, orderId)) + .eq(TbOrderDetail::getShopId, shopId)); + } +} + + + + diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/impl/TbShopCouponServiceImpl.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/impl/TbShopCouponServiceImpl.java index 2b1cc86..91148ae 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/service/impl/TbShopCouponServiceImpl.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/impl/TbShopCouponServiceImpl.java @@ -74,42 +74,42 @@ public class TbShopCouponServiceImpl implements TbShopCouponService { return canUseCoupon; } - private void setCouponInfo( Map coupons, TbUserCouponVo tbUserCouponVo, BigDecimal amount, String week, LocalTime now, DateTimeFormatter formatter) { - JsonObject json = new JsonObject(); - boolean isUse = true; - TbShopCoupon tbShopCoupon = couponMapper.queryById(tbUserCouponVo.getCouponId()); - StringBuilder useRestrictions = new StringBuilder("每天 "); - if (tbShopCoupon.getType().equals(1)) { - if (amount.compareTo(new BigDecimal(tbShopCoupon.getFullAmount())) < 0) { - isUse = false; + private void setCouponInfo( Map coupons, TbUserCouponVo tbUserCouponVo, BigDecimal amount, String week, LocalTime now, DateTimeFormatter formatter) { + JsonObject json = new JsonObject(); + boolean isUse = true; + TbShopCoupon tbShopCoupon = couponMapper.queryById(tbUserCouponVo.getCouponId()); + StringBuilder useRestrictions = new StringBuilder("每天 "); + if (tbShopCoupon.getType().equals(1)) { + if (amount.compareTo(new BigDecimal(tbShopCoupon.getFullAmount())) < 0) { + isUse = false; + } } - } - if (StringUtils.isNotBlank(tbShopCoupon.getUserDays())) { - String[] split = tbShopCoupon.getUserDays().split(","); - if (split.length != 7) { - useRestrictions = new StringBuilder(tbShopCoupon.getUserDays() + " "); + if (StringUtils.isNotBlank(tbShopCoupon.getUserDays())) { + String[] split = tbShopCoupon.getUserDays().split(","); + if (split.length != 7) { + useRestrictions = new StringBuilder(tbShopCoupon.getUserDays() + " "); + } + if (!tbShopCoupon.getUserDays().contains(week)) { + isUse = false; + } } - if (!tbShopCoupon.getUserDays().contains(week)) { - isUse = false; + if (tbShopCoupon.getUseTimeType().equals("custom")) { + if (now.isBefore(tbShopCoupon.getUseStartTime()) || now.isAfter(tbShopCoupon.getUseEndTime())) { + isUse = false; + } + useRestrictions.append( + tbShopCoupon.getUseStartTime().format(formatter) + + "-" + + tbShopCoupon.getUseEndTime().format(formatter)); + } else { + useRestrictions.append("全时段"); } - } - if (tbShopCoupon.getUseTimeType().equals("custom")) { - if (now.isBefore(tbShopCoupon.getUseStartTime()) || now.isAfter(tbShopCoupon.getUseEndTime())) { - isUse = false; - } - useRestrictions.append( - tbShopCoupon.getUseStartTime().format(formatter) - + "-" - + tbShopCoupon.getUseEndTime().format(formatter)); - } else { - useRestrictions.append("全时段"); - } - useRestrictions.append(" 可用"); - json.addProperty("isUse", isUse); - json.addProperty("useRestrictions", useRestrictions.toString()); + useRestrictions.append(" 可用"); + json.addProperty("isUse", isUse); + json.addProperty("useRestrictions", useRestrictions.toString()); - coupons.put(tbUserCouponVo.getCouponId(), json); - } + coupons.put(tbUserCouponVo.getCouponId(), json); + } @Override @@ -206,4 +206,32 @@ public class TbShopCouponServiceImpl implements TbShopCouponService { return true; } + @Override + public List getActivateCoupon(TbShopUser tbShopUser, BigDecimal orderAmount, Integer shopId, Set productIds) { + List tbUserCouponVos = inRecordMapper.queryByVipIdAndShopId(Collections.singletonList(Integer.valueOf(tbShopUser.getId())), shopId); + if (tbUserCouponVos.isEmpty()) { + return tbUserCouponVos; + } + String week = DateUtil.dayOfWeekEnum(new Date()).toChinese("周"); + LocalTime now = LocalTime.now(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss"); + //券id 券使用描述 + Map coupons = new HashMap<>(); + for (TbUserCouponVo tbUserCouponVo : tbUserCouponVos) { + if (!coupons.containsKey(tbUserCouponVo.getCouponId())) { + setCouponInfo(coupons, tbUserCouponVo, orderAmount, week, now, formatter); + } + JsonObject couponJson = coupons.get(tbUserCouponVo.getCouponId()); + tbUserCouponVo.setUseRestrictions(couponJson.get("useRestrictions").toString()); + if (tbUserCouponVo.getType().equals(1)) { + tbUserCouponVo.setUse(couponJson.get("isUse").getAsBoolean()); + } else if (tbUserCouponVo.getType().equals(2) && couponJson.get("isUse").getAsBoolean()) { + if (!productIds.contains(tbUserCouponVo.getProId().toString())) { + tbUserCouponVo.setUse(false); + } + } + } + tbUserCouponVos.sort(Comparator.comparing(TbUserCouponVo::isUse).reversed().thenComparing(TbUserCouponVo::getExpireTime)); + return tbUserCouponVos; + } } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/impl/TbShopUserServiceImpl.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/impl/TbShopUserServiceImpl.java new file mode 100644 index 0000000..b892012 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/impl/TbShopUserServiceImpl.java @@ -0,0 +1,33 @@ +package com.chaozhanggui.system.cashierservice.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.chaozhanggui.system.cashierservice.entity.TbShopUser; +import com.chaozhanggui.system.cashierservice.mapper.MpShopUserMapper; +import com.chaozhanggui.system.cashierservice.service.TbShopUserService; +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** +* @author Administrator +* @description 针对表【tb_call_table】的数据库操作Service实现 +* @createDate 2024-09-13 13:44:34 +*/ +@Service +@Primary +public class TbShopUserServiceImpl extends ServiceImpl + implements TbShopUserService { + + @Override + public TbShopUser selectByUserIdAndShopId(String userId, String shopId) { + return getOne(new LambdaQueryWrapper() + .eq(TbShopUser::getShopId, shopId) + .eq(TbShopUser::getUserId, userId)); + } +} + + + + diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/util/ShopUtils.java b/src/main/java/com/chaozhanggui/system/cashierservice/util/ShopUtils.java index 80abd0a..24ef19f 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/util/ShopUtils.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/util/ShopUtils.java @@ -55,10 +55,17 @@ public class ShopUtils { boolean isTakeout = isOpenTakeout && ShopInfoEatModelEnum.TAKE_OUT.getValue().equals(eatModel); boolean isDineInAfter = isOpenDineIn && !isMunchies && !isTakeout; boolean isDineInBefore = isOpenDineIn && isMunchies && !isTakeout; + boolean hasTable = StrUtil.isNotBlank(tableId); + boolean isNoneTable = !hasTable && !isTakeout; - return new ShopEatTypeInfoDTO(isTakeout, isMunchies, isDineInAfter, isDineInBefore, shopInfo, isTakeout ? OrderUseTypeEnum.TAKEOUT.getValue() : - isDineInBefore ? OrderUseTypeEnum.DINE_IN_BEFORE.getValue() : isDineInAfter ? OrderUseTypeEnum.DINE_IN_AFTER.getValue() : null, isOpenTakeout, isOpenDineIn); + boolean needSeatFee = shopInfo.getIsTableFee() == null || shopInfo.getIsTableFee() == 0; + boolean isIncrMasterId = isTakeout || isNoneTable; + + + + return new ShopEatTypeInfoDTO(isTakeout, isMunchies, isDineInAfter, isDineInBefore, needSeatFee, isNoneTable, isIncrMasterId, shopInfo, isTakeout ? OrderUseTypeEnum.TAKEOUT.getValue() : + isDineInBefore ? OrderUseTypeEnum.DINE_IN_BEFORE.getValue() : isDineInAfter ? OrderUseTypeEnum.DINE_IN_AFTER.getValue() : null, isOpenTakeout, isOpenDineIn, tableId); } public ShopEatTypeInfoDTO getEatModel(String tableId, Object shopId) { @@ -76,13 +83,20 @@ public class ShopUtils { boolean isMunchies = StrUtil.isNotBlank(shopInfo.getRegisterType()) && ShopInfoRegisterlEnum.MUNCHIES.getValue().equals(shopInfo.getRegisterType()); - boolean isDineInAfter = !isMunchies && !isTakeout; - boolean isDineInBefore = isMunchies && !isTakeout; + boolean hasTable = StrUtil.isNotBlank(tableId); + boolean isNoneTable = !hasTable && !isTakeout; + + + boolean needSeatFee = shopInfo.getIsTableFee() == null || shopInfo.getIsTableFee() == 0; + boolean isIncrMasterId = isTakeout || isNoneTable; + boolean isOpenTakeout = shopInfo.getEatModel().contains(ShopInfoEatModelEnum.TAKE_OUT.getValue()); boolean isOpenDineIn = shopInfo.getEatModel().contains(ShopInfoEatModelEnum.DINE_IN.getValue()); + boolean isDineInAfter = isOpenDineIn && !isMunchies && !isTakeout; + boolean isDineInBefore = isOpenDineIn && isMunchies && !isTakeout; - return new ShopEatTypeInfoDTO(isTakeout, isMunchies, isDineInAfter, isDineInBefore, shopInfo, isTakeout ? OrderUseTypeEnum.TAKEOUT.getValue() : - isMunchies ? OrderUseTypeEnum.DINE_IN_BEFORE.getValue() : OrderUseTypeEnum.DINE_IN_AFTER.getValue(), isOpenTakeout, isOpenDineIn); + return new ShopEatTypeInfoDTO(isTakeout, isMunchies, isDineInAfter, isDineInBefore, needSeatFee, isNoneTable, isIncrMasterId, shopInfo, isTakeout ? OrderUseTypeEnum.TAKEOUT.getValue() : + isDineInBefore ? OrderUseTypeEnum.DINE_IN_BEFORE.getValue() : isDineInAfter ? OrderUseTypeEnum.DINE_IN_AFTER.getValue() : null, isOpenTakeout, isOpenDineIn, tableId); } }