This commit is contained in:
2024-06-11 14:52:24 +08:00
parent f348972126
commit 7367e11c92
28 changed files with 2994 additions and 1558 deletions

View File

@@ -0,0 +1,766 @@
package com.chaozhanggui.system.cashierservice.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chaozhanggui.system.cashierservice.dao.*;
import com.chaozhanggui.system.cashierservice.entity.*;
import com.chaozhanggui.system.cashierservice.exception.MsgException;
import com.chaozhanggui.system.cashierservice.netty.PushToAppChannelHandlerAdapter;
import com.chaozhanggui.system.cashierservice.redis.RedisCst;
import com.chaozhanggui.system.cashierservice.redis.RedisUtil;
import com.chaozhanggui.system.cashierservice.util.DateUtils;
import com.chaozhanggui.system.cashierservice.util.JSONUtil;
import com.chaozhanggui.system.cashierservice.util.N;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.*;
/**
* @author lyf
*/
@Service
@Slf4j
public class CartService1 {
@Autowired
private RedisUtil redisUtil;
@Autowired
private TbOrderInfoMapper orderInfoMapper;
@Autowired
private TbCashierCartMapper cashierCartMapper;
@Autowired
private TbProductMapper productMapper;
@Autowired
private TbProductSkuMapper productSkuMapper;
@Autowired
private TbMerchantAccountMapper merchantAccountMapper;
@Autowired
private TbUserInfoMapper userInfoMapper;
@Autowired
private TbOrderDetailMapper orderDetailMapper;
@Autowired
private TbShopTableMapper shopTableMapper;
@Autowired
private TbUserCouponsMapper userCouponsMapper;
@Autowired
private TbSystemCouponsMapper systemCouponsMapper;
public void initCart(JSONObject jsonObject) {
String tableId = jsonObject.getString("tableId");
String shopId = jsonObject.getString("shopId");
String key = tableId + "-" + shopId;
BigDecimal amount = BigDecimal.ZERO;
JSONArray array = new JSONArray();
if (redisUtil.exists(RedisCst.TABLE_CART.concat(key))) {
array = JSON.parseArray(redisUtil.getMessage(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId))));
for (int i = 0; i < array.size(); i++) {
JSONObject object = array.getJSONObject(i);
TbCashierCart cashierCart = JSONUtil.parseJSONStr2T(object.toJSONString(), TbCashierCart.class);
if (cashierCart.getNumber() > 0) {
amount = amount.add(new BigDecimal(cashierCart.getTotalNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee())));
}
}
} else {
List<TbCashierCart> tbCashierCarts = cashierCartMapper.selectByShopIdAndTableId(shopId, tableId);
if (!CollectionUtils.isEmpty(tbCashierCarts)) {
for (TbCashierCart cashierCart : tbCashierCarts) {
array.add(cashierCart);
amount = amount.add(new BigDecimal(cashierCart.getTotalNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee())));
}
redisUtil.saveMessage(RedisCst.TABLE_CART.concat(key), array.toString());
}
}
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("status", "success");
jsonObject1.put("msg", "成功");
jsonObject1.put("type", "addCart");
jsonObject1.put("data", array);
jsonObject1.put("amount", amount);
PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), jsonObject.getString("tableId").concat("-").concat(shopId), "", false);
}
// @Transactional(rollbackFor = Exception.class)
public void createCart(JSONObject jsonObject) {
try {
String tableId = jsonObject.getString("tableId");
String shopId = jsonObject.getString("shopId");
String key = tableId + "-" + shopId;
JSONArray jsonArray = new JSONArray();
BigDecimal amount = BigDecimal.ZERO;
boolean exist = redisUtil.exists(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"));
if (!exist) {
TbProductSkuWithBLOBs tbProductSkuWithBLOBs = productSkuMapper.selectByPrimaryKey(Integer.valueOf(jsonObject.getString("skuId")));
Double stock = tbProductSkuWithBLOBs.getStockNumber();
redisUtil.saveMessage(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), Math.round(stock) + "");
}
String skuNum = redisUtil.getMessage(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"));
if (Integer.valueOf(skuNum) < 1) {
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("status", "fail");
jsonObject1.put("msg", "该商品库存已售罄");
jsonObject1.put("data", new ArrayList<>());
PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), key, jsonObject.getString("userId"), true);
log.error("该商品库存已售罄 skuId:{}", jsonObject.getString("skuId"));
throw new MsgException("该商品库存已售罄");
}
if (jsonObject.getInteger("num") > 0) {
redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "1");
} else {
redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "2");
}
if (redisUtil.exists(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId)))) {
JSONArray array = JSON.parseArray(redisUtil.getMessage(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId))));
if (Objects.isNull(array) || array.isEmpty() || array.size() < 1) {
if (jsonObject.getInteger("num") > 0) {
TbCashierCart cashierCart = addCart(jsonObject.getString("productId"), jsonObject.getString("skuId"),
jsonObject.getInteger("userId"), jsonObject.getInteger("num"), tableId, jsonObject.getString("shopId"));
jsonArray.add(cashierCart);
amount = amount.add(new BigDecimal(cashierCart.getNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee())));
}
} else {
boolean flag = true;
for (int i = 0; i < array.size(); i++) {
JSONObject object = array.getJSONObject(i);
TbCashierCart cashierCart = JSONUtil.parseJSONStr2T(object.toJSONString(), TbCashierCart.class);
if (cashierCart.getSkuId().equals(jsonObject.getString("skuId"))) {
cashierCart.setTotalNumber(cashierCart.getTotalNumber() + jsonObject.getInteger("num"));
cashierCart.setNumber(cashierCart.getNumber() + jsonObject.getInteger("num"));
if (cashierCart.getNumber() > 0) {
cashierCart.setTotalAmount(new BigDecimal(cashierCart.getTotalNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee())));
cashierCartMapper.updateByPrimaryKeySelective(cashierCart);
} else {
cashierCartMapper.deleteByPrimaryKey(cashierCart.getId());
continue;
}
flag = false;
}
jsonArray.add(cashierCart);
amount = amount.add(new BigDecimal(cashierCart.getTotalNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee())));
}
if (flag && jsonObject.getInteger("num") > 0) {
TbCashierCart cashierCart = addCart(jsonObject.getString("productId"), jsonObject.getString("skuId"),
jsonObject.getInteger("userId"), jsonObject.getInteger("num"), tableId, jsonObject.getString("shopId"));
jsonArray.add(cashierCart);
amount = amount.add(new BigDecimal(cashierCart.getTotalNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee())));
}
}
} else {
if (jsonObject.getInteger("num") > 0) {
TbCashierCart cashierCart = addCart(jsonObject.getString("productId"), jsonObject.getString("skuId"),
jsonObject.getInteger("userId"), jsonObject.getInteger("num"), tableId, jsonObject.getString("shopId"));
jsonArray.add(cashierCart);
amount = amount.add(new BigDecimal(cashierCart.getTotalNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee())));
}
}
productSkuMapper.updateStockById(jsonObject.getString("skuId"), jsonObject.getInteger("num"));
// AppWebSocketServer.getRecordMap().put(jsonObject.getString("tableId"), returnList);
redisUtil.saveMessage(RedisCst.TABLE_CART.concat(tableId).concat("-").concat(shopId), jsonArray.toJSONString());
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("status", "success");
jsonObject1.put("msg", "成功");
jsonObject1.put("type", jsonObject.getString("type"));
jsonObject1.put("data", jsonArray);
jsonObject1.put("amount", amount);
PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), jsonObject.getString("tableId").concat("-").concat(shopId), "", false);
} catch (Exception e) {
log.error("长链接错误 createCart{}", e.getMessage());
}
}
private TbCashierCart addCart(String productId, String skuId, Integer userId, Integer num, String tableId, String shopId) throws Exception {
try {
TbProduct product = productMapper.selectById(Integer.valueOf(productId));
String key = tableId + "-" + shopId;
if (Objects.isNull(product)) {
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("status", "fail");
jsonObject1.put("msg", "该商品不存在");
jsonObject1.put("data", new ArrayList<>());
PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), key, userId.toString(), true);
log.error("购物车添加商品异常,该商品不存在:{}",productId);
throw new MsgException("该商品不存在");
}
TbProductSkuWithBLOBs productSku = productSkuMapper.selectByPrimaryKey(Integer.valueOf(skuId));
if (Objects.isNull(productSku)) {
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("status", "fail");
jsonObject1.put("msg", "该商品规格不存在");
jsonObject1.put("data", new ArrayList<>());
PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), key, userId.toString(), true);
log.error("购物车添加商品异常该商品sku不存在{}",productId);
throw new MsgException("该商品规格不存在");
}
TbCashierCart cashierCart = new TbCashierCart();
cashierCart.setProductId(productId);
cashierCart.setSkuId(skuId);
cashierCart.setNumber(num);
cashierCart.setCoverImg(product.getCoverImg());
cashierCart.setName(product.getName());
cashierCart.setCategoryId(product.getCategoryId());
cashierCart.setShopId(shopId);
cashierCart.setUserId(userId);
cashierCart.setTableId(tableId);
cashierCart.setSkuName(productSku.getSpecSnap());
cashierCart.setIsPack("false");
cashierCart.setIsGift("false");
cashierCart.setStatus("create");
cashierCart.setType((byte) 0);
cashierCart.setSalePrice(productSku.getSalePrice());
cashierCart.setCreatedAt(Instant.now().toEpochMilli());
cashierCart.setUpdatedAt(Instant.now().toEpochMilli());
cashierCart.setTotalNumber(num);
cashierCart.setPackFee(BigDecimal.ZERO);
cashierCart.setRefundNumber(0);
cashierCart.setTotalAmount(new BigDecimal(cashierCart.getTotalNumber()).multiply(productSku.getSalePrice().add(cashierCart.getPackFee())));
cashierCartMapper.insert(cashierCart);
return cashierCart;
} catch (Exception e) {
log.error("长链接错误 addCart{}", e.getMessage());
throw e;
}
}
@Transactional(rollbackFor = Exception.class)
public void createOrder(JSONObject jsonObject) {
try {
String shopId = jsonObject.getString("shopId");
String tableId = jsonObject.getString("tableId");
String key = tableId + "-" + shopId;
JSONArray array = JSON.parseArray(redisUtil.getMessage(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId))));
List<Integer> 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<Integer, TbProductSku> skuMap = new HashMap<>();
List<TbOrderDetail> orderDetails = new ArrayList<>();
Integer orderId = 0;
TbMerchantAccount tbMerchantAccount = merchantAccountMapper.selectByShopId(jsonObject.getString("shopId"));
if (tbMerchantAccount == null) {
MsgException.throwException("生成订单错误");
}
String userId = jsonObject.getString("userId");
TbUserInfo tbUserInfo = userInfoMapper.selectByPrimaryKey(Integer.valueOf(userId));
if (tbUserInfo == null) {
MsgException.throwException("生成订单失败");
}
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());
}
cashierCartMapper.updateStatusById(cashierCart.getId(), "final");
}
//总金额
TbShopTable shopTable = shopTableMapper.selectQRcode(jsonObject.getString("tableId"));
//生成订单
TbOrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId);
String isBuyYhq = "false";
String isuseYhq = "false";
if (jsonObject.containsKey("isYhq") && jsonObject.getString("isYhq").equals("1")) {
couponId = jsonObject.getString("couponsId");
//1:购买优惠券0自己持有优惠券
Integer couponsId = jsonObject.getInteger("couponsId");
if (jsonObject.getString("isBuyYhq").equals("1")) {
TbSystemCoupons systemCoupons = systemCouponsMapper.selectByPrimaryKey(couponsId);
if (Objects.isNull(systemCoupons) || !systemCoupons.getStatus().equals("0")) {
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(), key, jsonObject.getString("userId"), true);
log.info("消息推送");
return;
}
if (N.gt(systemCoupons.getCouponsAmount(), totalAmount)) {
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(), key, jsonObject.getString("userId"), true);
log.info("消息推送");
return;
}
totalAmount = totalAmount.add(systemCoupons.getCouponsPrice()).subtract(systemCoupons.getCouponsAmount());
originAmount = originAmount.add(systemCoupons.getCouponsPrice());
couponAmount = systemCoupons.getCouponsAmount();
systemCoupons.setStatus("1");
systemCouponsMapper.updateByPrimaryKeySelective(systemCoupons);
TbUserCoupons userCoupons = new TbUserCoupons();
userCoupons.setEndTime(DateUtils.getNewDate(new Date(), 3, systemCoupons.getDayNum()));
userCoupons.setCouponsAmount(systemCoupons.getCouponsAmount());
userCoupons.setCouponsPrice(systemCoupons.getCouponsPrice());
userCoupons.setStatus("1");
userCoupons.setUserId(userId);
userCoupons.setCreateTime(new Date());
userCouponsMapper.insert(userCoupons);
couponId = userCoupons.getId() + "";
couponAmount = userCoupons.getCouponsAmount();
} else {
TbUserCoupons userCoupons = userCouponsMapper.selectByPrimaryKey(couponsId);
if (Objects.isNull(userCoupons) || !userCoupons.getStatus().equals("0")) {
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(), key, jsonObject.getString("userId"), true);
log.info("消息推送");
return;
}
if (N.gt(userCoupons.getCouponsAmount(), totalAmount)) {
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(), key, jsonObject.getString("userId"), true);
log.info("消息推送");
return;
}
totalAmount = totalAmount.subtract(userCoupons.getCouponsAmount());
userCoupons.setStatus("1");
userCoupons.setEndTime(DateUtils.getNewDate(new Date(), 5, 30));
userCouponsMapper.updateByPrimaryKeySelective(userCoupons);
couponAmount = userCoupons.getCouponsAmount();
}
isuseYhq = "true";
}
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(), key, 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);
orderInfo.setIsBuyCoupon(isBuyYhq);
orderInfo.setIsUseCoupon(isuseYhq);
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.setIsBuyCoupon(isBuyYhq);
orderInfo.setIsUseCoupon(isuseYhq);
orderInfo.setUserCouponAmount(couponAmount);
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(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId")).concat("-").concat(shopId), 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(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId")).concat("-").concat(shopId));
PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), key, 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(), jsonObject.getString("tableId").concat("-").concat(shopId), "", false);
} catch (Exception e) {
log.info("长链接错误 addCart{}", e.getMessage());
e.printStackTrace();
}
}
private TbOrderInfo getOrder(BigDecimal totalAmount, BigDecimal packAMount,
TbShopTable shopTable, String merchantId, JSONObject jsonObject, BigDecimal originAmount) {
TbOrderInfo orderInfo = new TbOrderInfo();
String orderNo = generateOrderNumber();
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());
}
orderInfo.setMerchantId(merchantId);
return orderInfo;
}
public String generateOrderNumber() {
String date = DateUtils.getSdfTimes();
Random random = new Random();
int randomNum = random.nextInt(900) + 100;
return "WX" + date + randomNum;
}
public void clearCart(JSONObject jsonObject) {
try {
String shopId = jsonObject.getString("shopId");
if (redisUtil.exists(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId)))) {
JSONArray array = JSON.parseArray(redisUtil.getMessage(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId))));
if (Objects.isNull(array) || array.isEmpty() || array.size() < 1) {
for (int i = 0; i < array.size(); i++) {
TbCashierCart cashierCart = JSONUtil.parseJSONStr2T(array.get(i).toString(), TbCashierCart.class);
// String result = redisUtil.secAdd(RedisCst.PRODUCT+shopId+":"+jsonObject.getString("skuId"),cashierCart.getNumber().toString());
productSkuMapper.updateAddStockById(jsonObject.getString("skuId"), cashierCart.getNumber());
}
}
}
cashierCartMapper.updateStatusByTableId(jsonObject.getString("tableId"), "closed");
redisUtil.saveMessage(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId)), new JSONArray().toJSONString());
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("status", "success");
jsonObject1.put("msg", "成功");
jsonObject1.put("type", "clearCart");
jsonObject1.put("amount", BigDecimal.ZERO);
jsonObject1.put("data", new ArrayList<>());
PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), jsonObject.getString("tableId").concat("-").concat(shopId), "", false);
} catch (Exception e) {
log.info("长链接错误 clearCart{}", e.getMessage());
e.printStackTrace();
}
}
@Transactional(rollbackFor = Exception.class)
public void pendingOrder(JSONObject jsonObject) throws IOException {
try {
String shopId = jsonObject.getString("shopId");
String tableId = jsonObject.getString("tableId");
String key = tableId + "-" + shopId;
JSONArray array = JSON.parseArray(redisUtil.getMessage(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId))));
List<Integer> 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<Integer, TbProductSku> skuMap = new HashMap<>();
List<TbOrderDetail> orderDetails = new ArrayList<>();
Integer orderId = 0;
TbMerchantAccount tbMerchantAccount = merchantAccountMapper.selectByShopId(jsonObject.getString("shopId"));
if (tbMerchantAccount == null) {
throw new MsgException("生成订单错误");
}
String userId = jsonObject.getString("userId");
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);
String isBuyYhq = "false";
String isuseYhq = "false";
if (jsonObject.containsKey("isYhq") && jsonObject.getString("isYhq").equals("1")) {
couponId = jsonObject.getString("couponsId");
//1:购买优惠券0自己持有优惠券
Integer couponsId = jsonObject.getInteger("couponsId");
if (jsonObject.getString("isBuyYhq").equals("1")) {
TbSystemCoupons systemCoupons = systemCouponsMapper.selectByPrimaryKey(couponsId);
if (Objects.isNull(systemCoupons) || !systemCoupons.getStatus().equals("0")) {
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(), key, jsonObject.getString("userId"), true);
log.info("消息推送");
return;
}
if (N.gt(systemCoupons.getCouponsAmount(), totalAmount)) {
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(), key, jsonObject.getString("userId"), true);
log.info("消息推送");
return;
}
totalAmount = totalAmount.add(systemCoupons.getCouponsPrice()).subtract(systemCoupons.getCouponsAmount());
originAmount = originAmount.add(systemCoupons.getCouponsPrice());
couponAmount = systemCoupons.getCouponsAmount();
systemCoupons.setStatus("1");
systemCouponsMapper.updateByPrimaryKeySelective(systemCoupons);
TbUserCoupons userCoupons = new TbUserCoupons();
userCoupons.setEndTime(DateUtils.getNewDate(new Date(), 3, systemCoupons.getDayNum()));
userCoupons.setCouponsAmount(systemCoupons.getCouponsAmount());
userCoupons.setCouponsPrice(systemCoupons.getCouponsPrice());
userCoupons.setStatus("1");
userCoupons.setUserId(userId);
userCoupons.setCreateTime(new Date());
userCouponsMapper.insert(userCoupons);
couponId = userCoupons.getId() + "";
couponAmount = userCoupons.getCouponsAmount();
} else {
TbUserCoupons userCoupons = userCouponsMapper.selectByPrimaryKey(couponsId);
if (Objects.isNull(userCoupons) || !userCoupons.getStatus().equals("0")) {
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(), key, jsonObject.getString("userId"), true);
log.info("消息推送");
return;
}
if (N.gt(userCoupons.getCouponsAmount(), totalAmount)) {
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(), key, jsonObject.getString("userId"), true);
log.info("消息推送");
return;
}
totalAmount = totalAmount.subtract(userCoupons.getCouponsAmount());
userCoupons.setStatus("1");
userCoupons.setEndTime(DateUtils.getNewDate(new Date(), 5, 30));
userCouponsMapper.updateByPrimaryKeySelective(userCoupons);
couponAmount = userCoupons.getCouponsAmount();
}
isuseYhq = "true";
}
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(), key, 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);
orderInfo.setIsBuyCoupon(isBuyYhq);
orderInfo.setIsUseCoupon(isuseYhq);
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.setIsBuyCoupon(isBuyYhq);
orderInfo.setIsUseCoupon(isuseYhq);
orderInfo.setUserCouponAmount(couponAmount);
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(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId")).concat("-").concat(shopId), 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(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId")).concat("-").concat(shopId));
redisUtil.saveMessage(RedisCst.TABLE_ORDER.concat(orderInfo.getOrderNo()), JSONObject.toJSONString(orderInfo), 24 * 60 * 60L);
PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), key, 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(), jsonObject.getString("tableId").concat("-").concat(shopId), "", false);
} catch (Exception e) {
log.info("长链接错误 pendingOrder{}", e.getMessage());
e.printStackTrace();
}
}
public void queryCart(JSONObject jsonObject) {
try {
String shopId = jsonObject.getString("shopId");
JSONArray array = JSON.parseArray(redisUtil.getMessage(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId))));
BigDecimal amount = BigDecimal.ZERO;
for (int i = 0; i < array.size(); i++) {
JSONObject object = array.getJSONObject(i);
TbCashierCart cashierCart = JSONUtil.parseJSONStr2T(object.toJSONString(), TbCashierCart.class);
amount = amount.add(new BigDecimal(cashierCart.getNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee())));
}
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("status", "success");
jsonObject1.put("msg", "成功");
jsonObject1.put("type", jsonObject.getString("type"));
jsonObject1.put("data", array);
jsonObject1.put("amount", amount);
PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), jsonObject.getString("tableId").concat("-").concat(shopId), "", false);
} catch (Exception e) {
log.info("长链接错误 queryCart{}", e.getMessage());
e.printStackTrace();
}
}
}

View File

@@ -1,7 +1,6 @@
package com.chaozhanggui.system.cashierservice.service;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chaozhanggui.system.cashierservice.dao.*;
@@ -9,14 +8,12 @@ import com.chaozhanggui.system.cashierservice.entity.*;
import com.chaozhanggui.system.cashierservice.entity.dto.ReturnGroupOrderDto;
import com.chaozhanggui.system.cashierservice.exception.MsgException;
import com.chaozhanggui.system.cashierservice.model.PayReq;
import com.chaozhanggui.system.cashierservice.model.ReturnOrderReq;
import com.chaozhanggui.system.cashierservice.model.TradeQueryReq;
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.sign.CodeEnum;
import com.chaozhanggui.system.cashierservice.sign.Result;
import com.chaozhanggui.system.cashierservice.socket.AppWebSocketServer;
import com.chaozhanggui.system.cashierservice.thirdpay.resp.OrderStatusQueryResp;
import com.chaozhanggui.system.cashierservice.thirdpay.resp.PublicResp;
import com.chaozhanggui.system.cashierservice.thirdpay.resp.WxScanPayResp;
@@ -233,7 +230,7 @@ public class PayService {
jsonObject1.put("type", "");
jsonObject1.put("data", new JSONArray());
jsonObject1.put("amount", 0);
AppWebSocketServer.AppSendInfo(jsonObject1,key, "",false);
// AppWebSocketServer.AppSendInfo(jsonObject1,key, "",false);
tbCashierCartMapper.updateStatusByOrderId(orderId.toString(),"final");
return Result.success(CodeEnum.SUCCESS,object.getJSONObject("data"));
}else {
@@ -272,7 +269,7 @@ public class PayService {
jsonObject1.put("data", new JSONArray());
jsonObject1.put("amount", 0);
AppWebSocketServer.AppSendInfo(jsonObject1,key, "",false);
// AppWebSocketServer.AppSendInfo(jsonObject1,key, "",false);
tbCashierCartMapper.updateStatusByOrderId(orderId.toString(),"final");
ObjectMapper mapper = new ObjectMapper();
return Result.success(CodeEnum.SUCCESS,mapper.readTree(wxScanPayResp.getPayInfo()));

View File

@@ -10,7 +10,6 @@ import com.chaozhanggui.system.cashierservice.entity.dto.HomeDto;
import com.chaozhanggui.system.cashierservice.entity.vo.*;
import com.chaozhanggui.system.cashierservice.sign.CodeEnum;
import com.chaozhanggui.system.cashierservice.sign.Result;
import com.chaozhanggui.system.cashierservice.socket.AppWebSocketServer;
import com.chaozhanggui.system.cashierservice.util.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
@@ -22,12 +21,10 @@ import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
@Service
@@ -132,22 +129,10 @@ public class ProductService {
if (ObjectUtil.isNotEmpty(in) && ObjectUtil.isNotNull(in)) {
log.info("请求参数:{}", in);
List<TbProduct> products = tbProductMapper.selectByIdIn(in);
if (ObjectUtil.isNotEmpty(products) && products.size() > 0) {
products.parallelStream().forEach(it -> {
Integer sum = 0;
if (AppWebSocketServer.userMap.containsKey(code)) {
Set<String> userSet = AppWebSocketServer.userMap.get(code);
if (userSet.isEmpty()) {
sum = tbProductMapper.selectByQcode(code, it.getId(), it.getShopId());
} else {
List<String> userList = new ArrayList<>(userSet);
sum = tbProductMapper.selectByNewQcode(code, it.getId(), it.getShopId(), userList);
}
} else {
sum = tbProductMapper.selectByQcode(code, it.getId(), it.getShopId());
}
Integer sum = tbProductMapper.selectByQcode(code, it.getId(), it.getShopId());
it.setCartNumber(sum == null ? "0" : String.valueOf(sum));
TbProductSkuResult skuResult = tbProductSkuResultMapper.selectByPrimaryKey(it.getId());
it.setProductSkuResult(skuResult);