From 04c5f783bdc7994e3ad03a63746a35f58a3bdf8b Mon Sep 17 00:00:00 2001 From: wangw <1594593906@qq.com> Date: Wed, 19 Jun 2024 15:06:46 +0800 Subject: [PATCH] =?UTF-8?q?=E6=97=A0=E6=95=88=E4=BB=A3=E7=A0=81=E7=A7=BB?= =?UTF-8?q?=E9=99=A4=20=E8=B4=AD=E7=89=A9=E8=BD=A6=20=E8=A7=84=E6=A0=BC?= =?UTF-8?q?=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cashierservice/config/ChangeHandler.java | 35 - .../cashierservice/config/ClearHandler.java | 33 - .../config/CreateOrderHandler.java | 79 - .../system/cashierservice/config/Handler.java | 26 - .../cashierservice/config/OtherHandler.java | 30 - .../cashierservice/config/SyncHandler.java | 46 - .../config/WebSocketCustomEncoding.java | 31 - .../config/NettyChannelHandlerAdapter.java | 114 -- .../cashierservice/rabbit/CartConsumer.java | 14 +- .../cashierservice/service/CartService.java | 1521 +++++++++-------- .../cashierservice/service/CartService1.java | 783 --------- .../socket/AppWebSocketServer.java | 359 ---- .../socket/AppWebSocketServerCopy.java | 311 ---- .../cashierservice/socket/SocketSession.java | 14 - .../socket/WebSocketConfig.java | 27 - .../socket/WebSocketServer.java | 113 -- .../resources/mapper/TbCashierCartMapper.xml | 6 +- 17 files changed, 790 insertions(+), 2752 deletions(-) delete mode 100644 src/main/java/com/chaozhanggui/system/cashierservice/config/ChangeHandler.java delete mode 100644 src/main/java/com/chaozhanggui/system/cashierservice/config/ClearHandler.java delete mode 100644 src/main/java/com/chaozhanggui/system/cashierservice/config/CreateOrderHandler.java delete mode 100644 src/main/java/com/chaozhanggui/system/cashierservice/config/Handler.java delete mode 100644 src/main/java/com/chaozhanggui/system/cashierservice/config/OtherHandler.java delete mode 100644 src/main/java/com/chaozhanggui/system/cashierservice/config/SyncHandler.java delete mode 100644 src/main/java/com/chaozhanggui/system/cashierservice/config/WebSocketCustomEncoding.java delete mode 100644 src/main/java/com/chaozhanggui/system/cashierservice/service/CartService1.java delete mode 100644 src/main/java/com/chaozhanggui/system/cashierservice/socket/AppWebSocketServer.java delete mode 100644 src/main/java/com/chaozhanggui/system/cashierservice/socket/AppWebSocketServerCopy.java delete mode 100644 src/main/java/com/chaozhanggui/system/cashierservice/socket/SocketSession.java delete mode 100644 src/main/java/com/chaozhanggui/system/cashierservice/socket/WebSocketConfig.java delete mode 100644 src/main/java/com/chaozhanggui/system/cashierservice/socket/WebSocketServer.java diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/config/ChangeHandler.java b/src/main/java/com/chaozhanggui/system/cashierservice/config/ChangeHandler.java deleted file mode 100644 index 9295ff5..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/config/ChangeHandler.java +++ /dev/null @@ -1,35 +0,0 @@ -//package com.chaozhanggui.system.cashierservice.config; -// -//import com.alibaba.fastjson.JSONObject; -//import com.chaozhanggui.system.cashierservice.socket.AppWebSocketServer; -// -//import java.io.IOException; -//import java.util.ArrayList; -//import java.util.List; -//import java.util.concurrent.ConcurrentHashMap; -// -////处理前端改变购物车的行为,并记录 -//public class ChangeHandler extends Handler { -// -// @Override -// public void handleRequest(ConcurrentHashMap> webSocketMap, -// JSONObject jsonObject, ConcurrentHashMap> recordMap, -// AppWebSocketServer webSocke) throws IOException { -// -// if (jsonObject.containsKey("change")) { -// ArrayList jsonObjects = new ArrayList<>(); -// jsonObjects.add(jsonObject); -//// producerMq.syncShopCar(jsonObjects); -// //记录每一次购物车变化的记录 -// List objects = recordMap.get(webSocke.getTableId()); -// objects.add(jsonObject); -// } else { -// // 无法处理,传递给下一个处理器 -// if (nextHandler != null) { -// nextHandler.handleRequest(webSocketMap,jsonObject,recordMap,webSocke); -// } -// } -// } -//} -// diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/config/ClearHandler.java b/src/main/java/com/chaozhanggui/system/cashierservice/config/ClearHandler.java deleted file mode 100644 index e1b92a7..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/config/ClearHandler.java +++ /dev/null @@ -1,33 +0,0 @@ -//package com.chaozhanggui.system.cashierservice.config; -// -//import com.alibaba.fastjson.JSONObject; -//import com.chaozhanggui.system.cashierservice.socket.AppWebSocketServer; -//import org.apache.commons.lang3.StringUtils; -// -//import java.io.IOException; -//import java.util.List; -//import java.util.concurrent.ConcurrentHashMap; -// -////处理前端订单已完成,把订单标志位置为false -//public class ClearHandler extends Handler{ -// -// @Override -// public void handleRequest(ConcurrentHashMap> webSocketMap, -// JSONObject jsonObject, ConcurrentHashMap> recordMap, -// AppWebSocketServer webSocke) throws IOException { -// if (jsonObject.containsKey("clear")) { -// if (StringUtils.isNotBlank(webSocke.getTableId()) && webSocketMap.containsKey(webSocke.getTableId())) { -// List serverList = webSocketMap.get(webSocke.getTableId()); -// //遍历所有对象,把订单都改为未提交,为了下一次点餐 -// serverList.forEach(m -> m.getCreateOrder().set(false)); -// -// } -// } else { -// // 无法处理,传递给下一个处理器 -// if (nextHandler != null) { -// nextHandler.handleRequest(webSocketMap,jsonObject,recordMap,webSocke); -// } -// } -// } -//} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/config/CreateOrderHandler.java b/src/main/java/com/chaozhanggui/system/cashierservice/config/CreateOrderHandler.java deleted file mode 100644 index 7d52894..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/config/CreateOrderHandler.java +++ /dev/null @@ -1,79 +0,0 @@ -//package com.chaozhanggui.system.cashierservice.config; -// -//import com.alibaba.fastjson.JSONArray; -//import com.alibaba.fastjson.JSONObject; -//import com.chaozhanggui.system.cashierservice.socket.AppWebSocketServer; -//import org.apache.commons.lang3.StringUtils; -// -//import java.io.IOException; -//import java.math.BigDecimal; -//import java.util.List; -//import java.util.concurrent.ConcurrentHashMap; -// -////处理前端创建订单 -//public class CreateOrderHandler extends Handler{ -// -// @Override -// public void handleRequest(ConcurrentHashMap> webSocketMap, -// JSONObject jsonObject, ConcurrentHashMap> recordMap, -// AppWebSocketServer webSocke) throws IOException { -// -// -// if (jsonObject.containsKey("createOrdwebSockeer")) { -// if (StringUtils.isNotBlank(webSocke.getTableId()) && webSocketMap.containsKey(webSocke.getTableId())) { -// List serverList = webSocketMap.get(webSocke.getTableId()); -// //有一个为true就说明已经有订单了 -// if (serverList.stream().anyMatch(m -> m.getCreateOrder().get())) { -// webSocke.sendMessage("已有人提交订单,请稍后"); -// return; -// } -// } -// synchronized (webSocke) { -// if (StringUtils.isNotBlank(webSocke.getTableId()) && webSocketMap.containsKey(webSocke.getTableId())) { -// List serverList = webSocketMap.get(webSocke.getTableId()); -// //有一个为true就说明已经有订单了 -// if (serverList.stream().anyMatch(m -> m.getCreateOrder().get())) { -// webSocke.sendMessage("已有人提交订单,请稍后"); -// return; -// } -// -// BigDecimal amount = new BigDecimal((Integer) jsonObject.get("amount")); -// JSONArray shopCarList = jsonObject.getJSONArray("shopCarList"); -// String remark = jsonObject.get("remark").toString(); -// -// -//// List list=shopCarList.toJavaList(ShopListDto.class); -//// //TODO 加个拦截加个shopid,抛出异常,前端展示 -//// setShopId(list.get(0).getShopId()); -//// try { -//// Result order = orderFeign.createOrder(new CreateOrderDto(Long.parseLong(webSocke.getTableId()), amount, list, remark)); -//// if (order.getCode() == 200){ -//// //通知清空购物车 -//// AppSendInfo("订单提交成功", webSocke.getTableId()); -//// //清空本地的购物记录 -//// recordMap.get(webSocke.getTableId()).clear(); -//// webSocke.getCreateOrder().set(true); -//// }else { -//// AppSendInfo("订单提交失败",webSocke.getTableId()); -//// } -//// -//// -//// }catch (Exception e){ -//// e.printStackTrace(); -//// AppSendInfo("订单提交失败",webSocke.getTableId()); -//// } -// -// -// -// } -// } -// -// } else { -// // 无法处理,传递给下一个处理器 -// if (nextHandler != null) { -// nextHandler.handleRequest(webSocketMap,jsonObject,recordMap,webSocke); -// } -// } -// } -//} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/config/Handler.java b/src/main/java/com/chaozhanggui/system/cashierservice/config/Handler.java deleted file mode 100644 index b269f84..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/config/Handler.java +++ /dev/null @@ -1,26 +0,0 @@ -//package com.chaozhanggui.system.cashierservice.config; -// -//import com.alibaba.fastjson.JSONObject; -//import com.chaozhanggui.system.cashierservice.socket.AppWebSocketServer; -// -//import java.io.IOException; -//import java.util.List; -//import java.util.concurrent.ConcurrentHashMap; -// -//public abstract class Handler { -// protected Handler nextHandler; -// -// -// public Handler addNextHandler(Handler handler) { -// this.nextHandler = handler; -// return handler; -// } -// -// -// -// -// public abstract void handleRequest(ConcurrentHashMap> webSocketMap, -// JSONObject jsonObject, ConcurrentHashMap> recordMap, -// AppWebSocketServer webSocke) throws IOException; -//} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/config/OtherHandler.java b/src/main/java/com/chaozhanggui/system/cashierservice/config/OtherHandler.java deleted file mode 100644 index 6e613b7..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/config/OtherHandler.java +++ /dev/null @@ -1,30 +0,0 @@ -//package com.chaozhanggui.system.cashierservice.config; -// -//import com.alibaba.fastjson.JSONObject; -//import com.chaozhanggui.system.cashierservice.socket.AppWebSocketServer; -//import org.apache.commons.lang3.StringUtils; -// -//import java.io.IOException; -//import java.util.List; -//import java.util.concurrent.ConcurrentHashMap; -// -//import static com.chaozhanggui.system.cashierservice.socket.AppWebSocketServer.AppSendInfo; -// -// -////兜底处理器 -//public class OtherHandler extends Handler{ -// @Override -// public void handleRequest(ConcurrentHashMap> webSocketMap, -// JSONObject jsonObject, -// ConcurrentHashMap> recordMap, -// AppWebSocketServer webSocke) throws IOException { -// -// //传送给对应tableId用户的websocket -// if (StringUtils.isNotBlank(webSocke.getTableId()) && webSocketMap.containsKey(webSocke.getTableId())) { -// AppSendInfo("1", webSocke.getTableId(),"",false); -// -// } else { -// System.out.println("请求的tableId:" + webSocke.getTableId() + "不在该服务器上"); -// } -// } -//} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/config/SyncHandler.java b/src/main/java/com/chaozhanggui/system/cashierservice/config/SyncHandler.java deleted file mode 100644 index 8474c6f..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/config/SyncHandler.java +++ /dev/null @@ -1,46 +0,0 @@ -//package com.chaozhanggui.system.cashierservice.config; -// -//import com.alibaba.fastjson.JSONObject; -//import com.chaozhanggui.system.cashierservice.socket.AppWebSocketServer; -//import org.apache.commons.lang3.StringUtils; -// -//import java.io.IOException; -//import java.util.ArrayList; -//import java.util.List; -//import java.util.concurrent.ConcurrentHashMap; -// -////处理前端初次扫码同步购物车 -//public class SyncHandler extends Handler { -// -// @Override -// public void handleRequest(ConcurrentHashMap> webSocketMap, -// JSONObject jsonObject, ConcurrentHashMap> recordMap, -// AppWebSocketServer webSocke) throws IOException { -// if (jsonObject.containsKey("sync")) { -// //这个是判断是否有这个桌号,也就是 是否有人点过餐 -// -// List recordList = recordMap.get(webSocke.getTableId()); -// //指定发送对象 -// if (StringUtils.isNotBlank(webSocke.getTableId()) && webSocketMap.containsKey(webSocke.getTableId()) && recordList != null) { -// List serverList = webSocketMap.get(webSocke.getTableId()); -// for (AppWebSocketServer server : serverList) { -// if (server.getSync().get()) { -// server.sendMessage(recordList); -// } -// -// } -// } else { -// ArrayList objects = new ArrayList<>(); -// recordMap.put(webSocke.getTableId(), objects); -// } -// webSocke.getSync().set(!webSocke.getSync().get()); -// -// } else { -// // 无法处理,传递给下一个处理器 -// if (nextHandler != null) { -// nextHandler.handleRequest(webSocketMap, jsonObject, recordMap, webSocke); -// } -// } -// } -//} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/config/WebSocketCustomEncoding.java b/src/main/java/com/chaozhanggui/system/cashierservice/config/WebSocketCustomEncoding.java deleted file mode 100644 index 33a7658..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/config/WebSocketCustomEncoding.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.chaozhanggui.system.cashierservice.config; - - -import com.alibaba.fastjson.JSON; - -import javax.websocket.Encoder; -import javax.websocket.EndpointConfig; - -/** - * 为了websocket发送对象 - */ - -public class WebSocketCustomEncoding implements Encoder.Text { -// public String encode(Object vo) 这个就是指定发送的类型 - @Override - public String encode(Object vo) { - assert vo!=null; - return JSON.toJSONString(vo); - } - - - @Override - public void init(EndpointConfig endpointConfig) { - - } - @Override - public void destroy() { - - } - -} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/netty/config/NettyChannelHandlerAdapter.java b/src/main/java/com/chaozhanggui/system/cashierservice/netty/config/NettyChannelHandlerAdapter.java index 20422b3..94008fd 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/netty/config/NettyChannelHandlerAdapter.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/netty/config/NettyChannelHandlerAdapter.java @@ -1,20 +1,12 @@ package com.chaozhanggui.system.cashierservice.netty.config; -import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.codec.http.FullHttpRequest; -import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.QueryStringDecoder; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; -import io.netty.handler.codec.mqtt.*; -import io.netty.util.CharsetUtil; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.io.Charsets; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; @@ -87,66 +79,6 @@ public abstract class NettyChannelHandlerAdapter extends ChannelInboundHandlerAd */ @Override public final void channelRead(ChannelHandlerContext ctx, Object msg) throws InterruptedException { - if (msg instanceof MqttMessage) { - MqttMessage mqttMessage = (MqttMessage) msg; - - MqttMessageType messageType = mqttMessage.fixedHeader().messageType(); - switch (messageType) { - case PINGREQ: - sendPingResponse(ctx); - break; - case CONNECT: - MqttConnectMessage connectMessage = (MqttConnectMessage) mqttMessage; - MqttConnectVariableHeader variableHeader = connectMessage.variableHeader(); - String id = connectMessage.payload().clientIdentifier(); - channelRead(ctx, "CONNECT#"+id); - // 发送连接回执 - sendConnectAck(ctx, connectMessage.variableHeader().isCleanSession()); - break; - case SUBSCRIBE: - // 处理接收到的 SUBSCRIBE 消息 - MqttSubscribeMessage subscribeMessage = (MqttSubscribeMessage) mqttMessage; - List mqttTopicSubscriptions = subscribeMessage.payload().topicSubscriptions(); - if (mqttTopicSubscriptions != null && !mqttTopicSubscriptions.isEmpty()) { - for (MqttTopicSubscription topicSubscription : mqttTopicSubscriptions) { - String topicFilter = topicSubscription.topicName(); - MqttQoS qos = topicSubscription.qualityOfService(); -// log.info("订阅主题:" + topicFilter + ",服务质量等级:" + qos.name()); - } - } else { -// log.info("没有订阅主题。"); - } - // 发送订阅回执 - sendSubscribeAck(ctx, subscribeMessage.variableHeader().messageId(), subscribeMessage.payload().topicSubscriptions()); - break; - case PUBLISH: - // 处理接收到的消息 - MqttPublishMessage publishMessage = (MqttPublishMessage) mqttMessage; - int i = publishMessage.variableHeader().packetId(); - String topic = publishMessage.variableHeader().topicName(); - // 提取发布消息的数据和主题等信息 - ByteBuf publishPayload = publishMessage.payload(); - String payloadContent = publishPayload.toString(CharsetUtil.UTF_8); // 将数据转换为字符串 - log.info("主题:"+topic+"数据:"+payloadContent); - if (i >= 1 && i <= 65535) { - sendPublishAck(ctx, publishMessage); - } else { -// log.info("无效消息id"); - } - channelRead(ctx, topic+"#"+payloadContent); - break; - case DISCONNECT: - ctx.close(); - break; - case PUBACK: - MqttPubAckMessage pubAckMessage = (MqttPubAckMessage) mqttMessage; - int messageId = pubAckMessage.variableHeader().messageId(); - break; - default: - log.info("收到其他类型的消息:" + messageType); - break; - } - } if (msg instanceof TextWebSocketFrame) { String text =((TextWebSocketFrame) msg).text(); // 获取消息内容 channelRead(ctx, text); @@ -166,52 +98,6 @@ public abstract class NettyChannelHandlerAdapter extends ChannelInboundHandlerAd } } - private void sendConnectAck(ChannelHandlerContext ctx, boolean cleanSession) { - MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.CONNACK, false, MqttQoS.AT_MOST_ONCE, false, 0); - MqttConnAckVariableHeader variableHeader = new MqttConnAckVariableHeader(MqttConnectReturnCode.CONNECTION_ACCEPTED, cleanSession); - MqttConnAckMessage connAckMessage = new MqttConnAckMessage(fixedHeader, variableHeader); - - ctx.writeAndFlush(connAckMessage); - } - - private void sendPingResponse(ChannelHandlerContext ctx) { - MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PINGRESP, false, MqttQoS.AT_MOST_ONCE, false, 0); - MqttMessage pingRespMessage = new MqttMessage(fixedHeader); - ctx.writeAndFlush(pingRespMessage); - } - - private void sendPublishAck(ChannelHandlerContext ctx, MqttPublishMessage publishMessage) { - MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBACK, false, MqttQoS.AT_LEAST_ONCE, false, 0); - MqttMessageIdVariableHeader variableHeader = MqttMessageIdVariableHeader.from(publishMessage.variableHeader().packetId()); - MqttPubAckMessage pubAckMessage = new MqttPubAckMessage(fixedHeader, variableHeader); - ctx.writeAndFlush(pubAckMessage); - } - - private void sendSubscribeAck(ChannelHandlerContext ctx, int messageId, List subscriptions) { - MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.SUBACK, false, MqttQoS.AT_LEAST_ONCE, false, 0); - MqttMessageIdVariableHeader variableHeader = MqttMessageIdVariableHeader.from(messageId); - MqttSubAckPayload payload = createSubAckPayload(subscriptions); // 自定义方法,创建订阅回执的有效载荷 - - MqttSubAckMessage subAckMessage = new MqttSubAckMessage(fixedHeader, variableHeader, payload); - - ctx.writeAndFlush(subAckMessage); - } - - private MqttSubAckPayload createSubAckPayload(List subscriptions) { - List grantedQosLevels = new ArrayList<>(); - for (MqttTopicSubscription subscription : subscriptions) { - int qosLevel = getGrantedQosLevel(subscription); // 自定义方法,根据订阅主题获取授予的 QoS 等级 - grantedQosLevels.add(qosLevel); - } - return new MqttSubAckPayload(grantedQosLevels); - } - private int getGrantedQosLevel(MqttTopicSubscription subscription) { - // 根据实际情况对订阅主题进行处理,并返回授予的 QoS 等级 - - // 这里我们简单地返回 1,即“至少一次”QoS 等级 - return 1; - } - /** * 服务器接受客户端的数据信息时触发 * 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 4d83336..fc41fcd 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/CartConsumer.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/CartConsumer.java @@ -6,7 +6,7 @@ import com.alibaba.fastjson.JSONObject; import com.chaozhanggui.system.cashierservice.exception.MsgException; import com.chaozhanggui.system.cashierservice.redis.RedisCst; import com.chaozhanggui.system.cashierservice.redis.RedisUtil; -import com.chaozhanggui.system.cashierservice.service.CartService1; +import com.chaozhanggui.system.cashierservice.service.CartService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.amqp.rabbit.annotation.RabbitHandler; @@ -25,7 +25,7 @@ public class CartConsumer { @Autowired private RedisUtil redisUtil; @Autowired - private CartService1 cartService; + private CartService cartService; @RabbitHandler @RabbitListener(queues = {"${queue}"}) public void listener(String message) { @@ -54,16 +54,6 @@ public class CartConsumer { cartService.createOrder(jsonObject); } } -// else if(jsonObject.getString("type").equals("pendingOrder")){ -// String cartDetail = redisUtil.getMessage(RedisCst.TABLE_CART.concat(tableId).concat("-").concat(shopId)); -// if (StringUtils.isEmpty(cartDetail)){ -// throw new MsgException("购物车为空无法下单"); -// } -// JSONArray array = JSON.parseArray(cartDetail); -// if (array.size() > 0){ -// cartService.pendingOrder(jsonObject); -// } -// } else if(jsonObject.getString("type").equals("clearCart")){ cartService.clearCart(jsonObject); } 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 5089bbf..94db48d 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/service/CartService.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/CartService.java @@ -1,736 +1,785 @@ -//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.redis.RedisCst; -//import com.chaozhanggui.system.cashierservice.redis.RedisUtil; -//import com.chaozhanggui.system.cashierservice.socket.AppWebSocketServer; -//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 java.io.IOException; -//import java.math.BigDecimal; -//import java.time.Instant; -//import java.util.*; -// -///** -// * @author lyf -// */ -//@Service -//@Slf4j -//public class CartService { -// @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; -// -// // @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) { -// JSONObject jsonObject1 = new JSONObject(); -// jsonObject1.put("status", "fail"); -// jsonObject1.put("msg", "该商品库存已售罄"); -// jsonObject1.put("data", new ArrayList<>()); -// AppWebSocketServer.AppSendInfo(jsonObject1, key,jsonObject.getString("userId"), true); -// throw new MsgException("该商品库存已售罄"); -// } -// if (jsonObject.getInteger("num") > 0) { -// String result = redisUtil.seckill(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), jsonObject.getInteger("num").toString()); -// if (result.equals("0")) { -// JSONObject jsonObject1 = new JSONObject(); -// jsonObject1.put("status", "fail"); -// jsonObject1.put("msg", "该商品库存已售罄"); -// jsonObject1.put("data", new ArrayList<>()); -// AppWebSocketServer.AppSendInfo(jsonObject1,key, jsonObject.getString("userId"), true); -// throw new MsgException("该商品库存已售罄"); -// } -// } else { -// String result = redisUtil.seckill(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), jsonObject.getInteger("num").toString()); -// } -// -// 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); -// if (object.getString("skuId").equals(jsonObject.getString("skuId"))) { -// object.put("totalNumber", object.getIntValue("totalNumber") + jsonObject.getInteger("num")); -// object.put("number", object.getIntValue("number") + jsonObject.getInteger("num")); -// flag = false; -// } -// TbCashierCart cashierCart = JSONUtil.parseJSONStr2T(object.toJSONString(), TbCashierCart.class); -// if (cashierCart.getNumber() > 0) { -// cashierCart.setTotalAmount(new BigDecimal(cashierCart.getTotalNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee()))); -// cashierCart.setUserId(jsonObject.getIntValue("userId")); -// if (StringUtils.isNotEmpty(cashierCart.getStatus())) { -// cashierCart.setStatus("create"); -// } -// cashierCartMapper.updateByPrimaryKeySelective(cashierCart); -// if (cashierCart.getNumber() > 0) { -// jsonArray.add(cashierCart); -// amount = amount.add(new BigDecimal(cashierCart.getTotalNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee()))); -// } else { -// cashierCartMapper.deleteByPrimaryKey(cashierCart.getId()); -// } -// } else { -// cashierCartMapper.deleteByPrimaryKey(cashierCart.getId()); -// } -// } -// 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); -// AppWebSocketServer.AppSendInfo(jsonObject1, jsonObject.getString("tableId").concat("-").concat(shopId),"", false); -// } catch (Exception e) { -// log.info("长链接错误 createCart{}",e.getMessage()); -// } -// } -// -// private TbCashierCart addCart(String productId, String skuId, Integer userId, Integer num, String tableId, String shopId) throws Exception { -// try { -// //productId 235 skuId 85 userId 78 num 1 tableId 55246240 shopId 10 -// 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<>()); -// AppWebSocketServer.AppSendInfo(jsonObject1,key, userId.toString(), true); -// 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<>()); -// AppWebSocketServer.AppSendInfo(jsonObject1,key, userId.toString(), true); -// 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.info("长链接错误 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 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) { -// 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()); -// } -// } -// //总金额 -// 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", ""); -// AppWebSocketServer.AppSendInfo(jsonObject1,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", ""); -// AppWebSocketServer.AppSendInfo(jsonObject1,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", ""); -// AppWebSocketServer.AppSendInfo(jsonObject1,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", ""); -// AppWebSocketServer.AppSendInfo(jsonObject1,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", ""); -// AppWebSocketServer.AppSendInfo(jsonObject1,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)); -// AppWebSocketServer.AppSendInfo(jsonObject1,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()); -// AppWebSocketServer.AppSendInfo(jsonObject12, 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<>()); -// AppWebSocketServer.AppSendInfo(jsonObject1, 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 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("生成订单错误"); -// } -// -// 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", ""); -// AppWebSocketServer.AppSendInfo(jsonObject1,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", ""); -// AppWebSocketServer.AppSendInfo(jsonObject1,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", ""); -// AppWebSocketServer.AppSendInfo(jsonObject1,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", ""); -// AppWebSocketServer.AppSendInfo(jsonObject1,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", ""); -// AppWebSocketServer.AppSendInfo(jsonObject1,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); -// AppWebSocketServer.AppSendInfo(jsonObject1,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()); -// AppWebSocketServer.AppSendInfo(jsonObject12, 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); -// AppWebSocketServer.AppSendInfo(jsonObject1, jsonObject.getString("tableId").concat("-").concat(shopId),"", false); -// }catch (Exception e){ -// log.info("长链接错误 queryCart{}",e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +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 CartService { + + @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 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 productId = jsonObject.getString("productId"); + 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")); + TbProduct tbProduct = productMapper.selectById(Integer.valueOf(productId)); + if (tbProduct.getIsStock() == 1) { + if (Integer.valueOf(skuNum) < 1 && jsonObject.getInteger("num") > 0) { + 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 (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()))); + if (jsonObject.getInteger("num") > 0) { + redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "1"); + } else { + redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "2"); + } + productSkuMapper.updateStockById(jsonObject.getString("skuId"), jsonObject.getInteger("num")); + } + } 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 (jsonObject.getInteger("num") > 0) { + redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "1"); + } else { + redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "2"); + } + productSkuMapper.updateStockById(jsonObject.getString("skuId"), jsonObject.getInteger("num")); + if (cashierCart.getNumber() > 0) { + cashierCart.setTotalAmount(new BigDecimal(cashierCart.getTotalNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee()))); + cashierCart.setUpdatedAt(Instant.now().toEpochMilli()); + 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()))); + if (jsonObject.getInteger("num") > 0) { + redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "1"); + } else { + redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "2"); + } + productSkuMapper.updateStockById(jsonObject.getString("skuId"), jsonObject.getInteger("num")); + } + } + } 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()))); + redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "1"); + productSkuMapper.updateStockById(jsonObject.getString("skuId"), jsonObject.getInteger("num")); + } + } + 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 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; + List 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()); + } + 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); +// orderInfo.setRemark(StringUtils.isBlank(jsonObject.getString("remark"))?"":jsonObject.getString("remark")); + 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); +// orderInfo.setRemark(StringUtils.isBlank(jsonObject.getString("remark"))?"":jsonObject.getString("remark")); + 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); + redisUtil.saveMessage(RedisCst.ORDER_EXPIRED.concat(orderId.toString()), orderId.toString(), 60 * 16L); + } 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); + 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 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("生成订单错误"); + } + + 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(); + } + } + +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/CartService1.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/CartService1.java deleted file mode 100644 index 11d7f0b..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/service/CartService1.java +++ /dev/null @@ -1,783 +0,0 @@ -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 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 productId = jsonObject.getString("productId"); - 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")); - TbProduct tbProduct = productMapper.selectById(Integer.valueOf(productId)); - if (tbProduct.getIsStock() == 1) { - if (Integer.valueOf(skuNum) < 1 && jsonObject.getInteger("num") > 0) { - 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 (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()))); - if (jsonObject.getInteger("num") > 0) { - redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "1"); - } else { - redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "2"); - } - productSkuMapper.updateStockById(jsonObject.getString("skuId"), jsonObject.getInteger("num")); - } - } 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 (jsonObject.getInteger("num") > 0) { - redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "1"); - } else { - redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "2"); - } - productSkuMapper.updateStockById(jsonObject.getString("skuId"), jsonObject.getInteger("num")); - if (cashierCart.getNumber() > 0) { - cashierCart.setTotalAmount(new BigDecimal(cashierCart.getTotalNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee()))); - cashierCart.setUpdatedAt(Instant.now().toEpochMilli()); - 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()))); - if (jsonObject.getInteger("num") > 0) { - redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "1"); - } else { - redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "2"); - } - productSkuMapper.updateStockById(jsonObject.getString("skuId"), jsonObject.getInteger("num")); - } - } - } 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()))); - redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "1"); - productSkuMapper.updateStockById(jsonObject.getString("skuId"), jsonObject.getInteger("num")); - } - } - 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 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; - List 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()); - } - 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); - redisUtil.saveMessage(RedisCst.ORDER_EXPIRED.concat(orderId.toString()), orderId.toString(), 60 * 16L); - } 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); - 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 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("生成订单错误"); - } - - 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(); - } - } - -} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/socket/AppWebSocketServer.java b/src/main/java/com/chaozhanggui/system/cashierservice/socket/AppWebSocketServer.java deleted file mode 100644 index ed72b89..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/socket/AppWebSocketServer.java +++ /dev/null @@ -1,359 +0,0 @@ -//package com.chaozhanggui.system.cashierservice.socket; -// -//import com.alibaba.fastjson.JSON; -//import com.alibaba.fastjson.JSONArray; -//import com.alibaba.fastjson.JSONObject; -//import com.chaozhanggui.system.cashierservice.config.WebSocketCustomEncoding; -//import com.chaozhanggui.system.cashierservice.dao.TbShopTableMapper; -//import com.chaozhanggui.system.cashierservice.entity.TbCashierCart; -//import com.chaozhanggui.system.cashierservice.entity.TbShopTable; -//import com.chaozhanggui.system.cashierservice.exception.MsgException; -//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.util.JSONUtil; -//import com.chaozhanggui.system.cashierservice.util.SpringUtils; -//import lombok.Data; -//import lombok.extern.slf4j.Slf4j; -//import org.apache.commons.lang3.StringUtils; -//import org.springframework.stereotype.Component; -// -//import javax.annotation.PostConstruct; -//import javax.annotation.Resource; -//import javax.websocket.*; -//import javax.websocket.server.PathParam; -//import javax.websocket.server.ServerEndpoint; -//import java.io.*; -//import java.math.BigDecimal; -//import java.util.*; -//import java.util.concurrent.ConcurrentHashMap; -//import java.util.concurrent.atomic.AtomicBoolean; -// -//@ServerEndpoint(value = "/websocket/table", encoders = WebSocketCustomEncoding.class) -//@Component -//@Slf4j -//@Data -//public class AppWebSocketServer { -// -// -// @Resource -// private RabbitProducer a; -// -// //注入为空 -// public static RabbitProducer rabbitProducer; -// -// @PostConstruct -// public void b() { -// rabbitProducer = this.a; -// } -// -// -// private RedisUtil redisUtils = SpringUtils.getBean(RedisUtil.class); -// private TbShopTableMapper shopTableMapper = SpringUtils.getBean(TbShopTableMapper.class); -// /** -// * concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。 -// */ -// //一个 AppWebSocketServer 就是一个用户,一个tableId下有一个 List 也就是多个用户 -// private static HashMap> webSocketMap = new HashMap<>(); -// public static ConcurrentHashMap> userMap = new ConcurrentHashMap<>(); -// -// /** -// * 与某个客户端的连接会话,需要通过它来给客户端发送数据 -// */ -// private Session session; -// -// /** -// * 接收tableId -// */ -// private String tableId = ""; -// private String shopId = ""; -// private String userId = ""; -// -// /** -// * 用来标识这个用户需要接收同步的购物车信息 -// */ -// private volatile AtomicBoolean sync = new AtomicBoolean(true); -// -// private volatile AtomicBoolean createOrder = new AtomicBoolean(false); -// -// -// /** -// * 连接建立成功调用的方法 -// */ -// @OnOpen -// public void onOpen(Session session) { -// this.session = session; -// log.info("建立连接开始"); -//// public void onOpen(Session session, @PathParam("tableId") String tableId, @PathParam("shopId") String shopId, @PathParam("userId") String userId) { -// Map queryParams = getParamMap(); -// String tableId = queryParams.get("tableId"); -// String shopId = queryParams.get("shopId"); -// String userId = queryParams.get("userId"); -// -// log.info("建立连接参数 tableId:{} shopId:{} userId:{} sessionId:{}",tableId,shopId,userId,session.getId()); -// this.tableId = tableId; -// this.shopId = shopId; -// this.userId = userId; -// try { -// String key=tableId + "-" + shopId; -// TbShopTable shopTable = shopTableMapper.selectQRcode(tableId); -// if (Objects.isNull(shopTable)) { -// JSONObject jsonObject1 = new JSONObject(); -// jsonObject1.put("status", "fail"); -// jsonObject1.put("msg", "桌码不存在"); -// jsonObject1.put("type", "addCart"); -// jsonObject1.put("data", new ArrayList<>()); -// jsonObject1.put("amount", BigDecimal.ZERO); -// sendMessage(jsonObject1); -// onClose(); -// } -// -// if (webSocketMap.containsKey(key)) { -// ConcurrentHashMap userSocketMap = webSocketMap.get(key); -// // 在放置新条目之前检查并清除同名userId的数据 -// userSocketMap.put(userId,this); -// } else { -// ConcurrentHashMap userSocketMap=new ConcurrentHashMap<>(); -// userSocketMap.put(userId,this); -// webSocketMap.put(key,userSocketMap); -// } -// -// if (userMap.containsKey(tableId)) { -// Set userSet = userMap.get(tableId); -// userSet.add(userId); -// } else { -// Set userSet = new HashSet<>(); -// userSet.add(userId); -// userMap.put(tableId,userSet); -// } -// String mes = redisUtils.getMessage(RedisCst.TABLE_CART.concat(key)); -// if (StringUtils.isEmpty(mes)) { -// JSONObject jsonObject1 = new JSONObject(); -// jsonObject1.put("status", "success"); -// jsonObject1.put("msg", "成功"); -// jsonObject1.put("type", "addCart"); -// jsonObject1.put("data", new ArrayList<>()); -// jsonObject1.put("amount", BigDecimal.ZERO); -// sendMessage(jsonObject1); -// } else { -// JSONObject jsonObject1 = new JSONObject(); -// jsonObject1.put("status", "success"); -// jsonObject1.put("msg", "成功"); -// jsonObject1.put("type", "addCart"); -// BigDecimal amount = BigDecimal.ZERO; -// JSONArray jsonArray = JSON.parseArray(redisUtils.getMessage(RedisCst.TABLE_CART.concat(key))); -// for (int i = 0; i < jsonArray.size(); i++) { -// JSONObject object = jsonArray.getJSONObject(i); -// amount = amount.add(object.getBigDecimal("totalAmount")); -// } -// jsonObject1.put("amount", amount); -// jsonObject1.put("data", jsonArray); -// sendMessage(jsonObject1); -// } -//// sendMessage(recordMap.get(tableId)); -// } catch (IOException e) { -// log.error("用户:" + tableId + ",网络异常!!!!!!"); -// } -// } -// -// /** -// * 连接关闭调用的方法 -// */ -// @OnClose -// public void onClose() throws IOException { -// String key=tableId + "-" + shopId; -// log.info("触发关闭操作 key为:{} userId为:{} sessionId:{}",key,userId,session.getId()); -// if (webSocketMap.containsKey(key)) { -// ConcurrentHashMap userSocketMap = webSocketMap.get(key); -// // 在放置新条目之前检查并清除同名userId的数据 -// userSocketMap.remove(userId); -// log.info("存在的 {}用户数3为:{}",key,userSocketMap.size()); -// } -// if (userMap.containsKey(tableId)){ -// Set userSet = userMap.get(tableId); -// userSet.remove(userId); -//// if (userSet.isEmpty()){ -//// userMap.remove(tableId + "-" + shopId); -//// } -// } -// session.close(); -// } -// -// /** -// * 收到客户端消息后调用的方法 -// * -// * @param message 客户端发送过来的消息 -// */ -// @OnMessage -// public void onMessage(String message, Session session) { -// log.info("接收消息 tableId:{} shopId:{} userId:{} message:{} sessionId:{}",this.tableId,this.shopId,this.userId,message,session.getId()); -// //可以群发消息 -// //消息保存到数据库、redis -// if (StringUtils.isNotBlank(message) && !message.equals("undefined")) { -// try { -// //解析发送的报文 -// JSONObject jsonObject = new JSONObject(); -// if (StringUtils.isNotEmpty(message)) { -// jsonObject = JSONObject.parseObject(message); -// } -// //追加发送人(防止串改) -// jsonObject.put("tableId", this.tableId); -// jsonObject.put("shopId", this.shopId); -// if ("sku".equals(jsonObject.getString("type"))){ -// boolean exist = redisUtils.exists(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId))); -// Integer num = 0; -// if (exist){ -// JSONArray array = JSON.parseArray(redisUtils.getMessage(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId)))); -// for (int i = 0; i < array.size(); i++) { -// JSONObject object = array.getJSONObject(i); -// if (object.getString("skuId").equals(jsonObject.getString("skuId"))) { -// num = object.getIntValue("totalNumber"); -// break; -// } -// } -// } -// JSONObject jsonObject1 = new JSONObject(); -// jsonObject1.put("status", "success"); -// jsonObject1.put("msg", "成功"); -// jsonObject1.put("type", "sku"); -// jsonObject1.put("data", new ArrayList<>()); -// jsonObject1.put("amount", num); -// sendMessage(jsonObject1); -// }else { -// rabbitProducer.putCart(jsonObject.toJSONString()); -// } -// } catch (Exception e) { -// log.error("接收消息 处理失败",e); -// } -// } -// } -// -// /** -// * 发生错误时候 -// * -// * @param session -// * @param error -// */ -// @OnError -// public void onError(Session session, Throwable error) throws IOException { -// log.error("用户错误:" + this.tableId + ",原因:" + error.getMessage()); -//// error.printStackTrace(); -// } -// -// /** -// * 实现服务器主动推送 -// */ -// public void sendMessage(Object message) throws IOException { -// //加入线程锁 -// synchronized (session) { -// try { -// log.info("发送消息 session:{}",session.getId()); -// //同步发送信息 -// this.session.getBasicRemote().sendObject(message); -// } catch (Exception e) { -// log.error("服务器推送失败:" + e.getMessage()); -// } -// } -// } -// -// -// /** -// * 发送自定义消息 -// * */ -// /** -// * 发送自定义消息 -// * -// * @param message 发送的信息 -// * @param tableId 如果为null默认发送所有 tableId-shopId(桌码-店铺ID) -// * @param userId userFlag为 true时 必填 -// * @param userFlag true 发送给指定用户 false 群发 -// * @throws IOException -// */ -// public static void AppSendInfo(Object message, String tableId,String userId, boolean userFlag) throws IOException { -// log.info("发送消息 tableId:{} userId:{} userFlag:{} message:{}",tableId,userId,userFlag,JSONUtil.toJSONString(message)); -// if (userFlag) { -// if (webSocketMap.containsKey(tableId)) { -// ConcurrentHashMap userSocketMap = webSocketMap.get(tableId); -// if(!userSocketMap.isEmpty()){ -// if(StringUtils.isNotBlank(userId)){ -// userSocketMap.get(userId).sendMessage(message); -// } -// }else { -// log.error("请求的tableId:"+tableId+"用户连接为空"); -// } -// }else { -// log.error("请求的tableId:"+tableId+" userId:" + userId + "不在该服务器上"); -// } -// } else { -// if (StringUtils.isEmpty(tableId)) { -// // 向所有用户发送信息 -// for (ConcurrentHashMap value : webSocketMap.values()) { -// for (AppWebSocketServer server : value.values()) { -// server.sendMessage(message); -// } -// } -// } else if (webSocketMap.containsKey(tableId)) { -// log.info("发送消息的webSocketMap:存在"); -// // 对应桌码发送消息 -// for (AppWebSocketServer server : webSocketMap.get(tableId).values()) { -// log.info("发送消息的webSocketMap 次数:"); -// server.sendMessage(message); -// } -// } else { -// log.error("请求的tableId:" + tableId + "不在该服务器上"); -// } -// } -// -// } -// -// public Map getParamMap(){ -// // 获取连接建立时传递的参数 -// Map> queryParams = session.getRequestParameterMap(); -// // 创建新的Map来存储转换后的参数 -// Map parameterMap = new HashMap<>(); -// -// // 遍历原始参数Map的键值对 -// for (Map.Entry> entry : queryParams.entrySet()) { -// String key = entry.getKey(); -// List values = entry.getValue(); -// -// // 如果值列表不为空,则将第一个值作为键的值存储在新的Map中 -// if (!values.isEmpty()) { -// String value = values.get(0); -// parameterMap.put(key, value); -// } -// } -// return parameterMap; -// } -// -// -//// public static synchronized ConcurrentHashMap> getWebSocketMap() { -//// return AppWebSocketServer.webSocketMap; -//// } -//// -//// public static synchronized ConcurrentHashMap> getRecordMap() { -//// return AppWebSocketServer.recordMap; -//// } -//// private byte[] serialize(Object obj) { -//// try { -//// ByteArrayOutputStream bos = new ByteArrayOutputStream(); -//// ObjectOutputStream oos = new ObjectOutputStream(bos); -//// oos.writeObject(obj); -//// return bos.toByteArray(); -//// } catch (IOException e) { -//// e.printStackTrace(); -//// return null; -//// } -//// } -//// -//// private Object deserialize(byte[] bytes) { -//// try { -//// ByteArrayInputStream bis = new ByteArrayInputStream(bytes); -//// ObjectInputStream ois = new ObjectInputStream(bis); -//// return ois.readObject(); -//// } catch (IOException | ClassNotFoundException e) { -//// e.printStackTrace(); -//// return null; -//// } -//// } -//} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/socket/AppWebSocketServerCopy.java b/src/main/java/com/chaozhanggui/system/cashierservice/socket/AppWebSocketServerCopy.java deleted file mode 100644 index d6af3e2..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/socket/AppWebSocketServerCopy.java +++ /dev/null @@ -1,311 +0,0 @@ -//package com.chaozhanggui.system.cashierservice.socket; -// -//import com.alibaba.fastjson.JSON; -//import com.alibaba.fastjson.JSONArray; -//import com.alibaba.fastjson.JSONObject; -//import com.chaozhanggui.system.cashierservice.config.WebSocketCustomEncoding; -//import com.chaozhanggui.system.cashierservice.dao.TbShopTableMapper; -//import com.chaozhanggui.system.cashierservice.entity.TbShopTable; -//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.util.SpringUtils; -//import lombok.Data; -//import lombok.extern.slf4j.Slf4j; -//import org.apache.commons.lang3.StringUtils; -//import org.springframework.stereotype.Component; -// -//import javax.annotation.PostConstruct; -//import javax.annotation.Resource; -//import javax.websocket.*; -//import javax.websocket.server.PathParam; -//import javax.websocket.server.ServerEndpoint; -//import java.io.IOException; -//import java.math.BigDecimal; -//import java.util.*; -//import java.util.concurrent.ConcurrentHashMap; -//import java.util.concurrent.atomic.AtomicBoolean; -// -//@ServerEndpoint(value = "/websocket/table/{tableId}/{shopId}/{userId}", encoders = WebSocketCustomEncoding.class) -//@Component -//@Slf4j -//@Data -//public class AppWebSocketServerCopy { -// -// -// @Resource -// private RabbitProducer a; -// -// //注入为空 -// public static RabbitProducer rabbitProducer; -// -// @PostConstruct -// public void b() { -// rabbitProducer = this.a; -// } -// -// -// private RedisUtil redisUtils = SpringUtils.getBean(RedisUtil.class); -// private TbShopTableMapper shopTableMapper = SpringUtils.getBean(TbShopTableMapper.class); -// /** -// * concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。 -// */ -// //一个 AppWebSocketServer 就是一个用户,一个tableId下有一个 List 也就是多个用户 -// private static ConcurrentHashMap> webSocketMap = new ConcurrentHashMap<>(); -// public static ConcurrentHashMap> userMap = new ConcurrentHashMap<>(); -// private static ConcurrentHashMap userSocketMap = new ConcurrentHashMap<>(); -// //购物车的记录,用于第一次扫码的人同步购物车 -// private static ConcurrentHashMap> recordMap = new ConcurrentHashMap<>(); -// private static ConcurrentHashMap sessionMap = new ConcurrentHashMap<>(); -// -// /** -// * 与某个客户端的连接会话,需要通过它来给客户端发送数据 -// */ -// private Session session; -// -// /** -// * 接收tableId -// */ -// private String tableId = ""; -// private String shopId = ""; -// private String userId = ""; -// -// /** -// * 用来标识这个用户需要接收同步的购物车信息 -// */ -// private volatile AtomicBoolean sync = new AtomicBoolean(true); -// -// private volatile AtomicBoolean createOrder = new AtomicBoolean(false); -// -// -// /** -// * 连接建立成功调用的方法 -// */ -// @OnOpen -// public void onOpen(Session session, @PathParam("tableId") String tableId, @PathParam("shopId") String shopId, @PathParam("userId") String userId) { -// this.session = session; -// this.tableId = tableId; -// this.shopId = shopId; -// this.userId = userId; -// try { -// TbShopTable shopTable = shopTableMapper.selectQRcode(tableId); -// if (Objects.isNull(shopTable)) { -// JSONObject jsonObject1 = new JSONObject(); -// jsonObject1.put("status", "fail"); -// jsonObject1.put("msg", "桌码不存在"); -// jsonObject1.put("type", "addCart"); -// jsonObject1.put("data", new ArrayList<>()); -// jsonObject1.put("amount", BigDecimal.ZERO); -// sendMessage(jsonObject1); -// onClose(); -// } -// if (webSocketMap.containsKey(tableId + "-" + shopId)) { -// List serverList = webSocketMap.get(tableId + "-" + shopId); -// serverList.add(this); -// } else { -// List serverList = new ArrayList<>(); -// serverList.add(this); -// webSocketMap.put(tableId + "-" + shopId, serverList); -// } -// if (userMap.containsKey(tableId + "-" + shopId)) { -// Set userSet = userMap.get(tableId + "-" + shopId); -// userSet.add(userId); -// } else { -// Set userSet = new HashSet<>(); -// userSet.add(userId); -// userMap.put(tableId + "-" + shopId,userSet); -// } -// -// userSocketMap.put(userId, this); -//// sessionMap.put(userId,session); -// String mes = redisUtils.getMessage(RedisCst.TABLE_CART.concat(tableId + "-" + shopId)); -// if (StringUtils.isEmpty(mes)) { -// JSONObject jsonObject1 = new JSONObject(); -// jsonObject1.put("status", "success"); -// jsonObject1.put("msg", "成功"); -// jsonObject1.put("type", "addCart"); -// jsonObject1.put("data", new ArrayList<>()); -// jsonObject1.put("amount", BigDecimal.ZERO); -// sendMessage(jsonObject1); -// } else { -// JSONObject jsonObject1 = new JSONObject(); -// jsonObject1.put("status", "success"); -// jsonObject1.put("msg", "成功"); -// jsonObject1.put("type", "addCart"); -// BigDecimal amount = BigDecimal.ZERO; -// JSONArray jsonArray = JSON.parseArray(redisUtils.getMessage(RedisCst.TABLE_CART.concat(tableId + "-" + shopId))); -// for (int i = 0; i < jsonArray.size(); i++) { -// JSONObject object = jsonArray.getJSONObject(i); -// amount = amount.add(object.getBigDecimal("totalAmount")); -// } -// jsonObject1.put("amount", amount); -// jsonObject1.put("data", jsonArray); -// sendMessage(jsonObject1); -// } -//// sendMessage(recordMap.get(tableId)); -// } catch (IOException e) { -// log.error("用户:" + tableId + ",网络异常!!!!!!"); -// } -// } -// -// /** -// * 连接关闭调用的方法 -// */ -// @OnClose -// public void onClose() { -// if (webSocketMap.containsKey(tableId + "-" + shopId)) { -// List serverList = webSocketMap.get(tableId + "-" + shopId); -// if (serverList.isEmpty()) { -// webSocketMap.remove(tableId + "-" + shopId); -// } -// serverList.remove(this); -// -// } -// if (userMap.containsKey(tableId + "-" + shopId)){ -// Set userSet = userMap.get(tableId + "-" + shopId); -// if (userSet.isEmpty()){ -// userMap.remove(tableId + "-" + shopId); -// } -// userSet.remove(userId); -// } -// } -// public static void onClosed(String user) throws IOException { -// Session session1 = sessionMap.get(user); -// session1.close(); -// } -// /** -// * 收到客户端消息后调用的方法 -// * -// * @param message 客户端发送过来的消息 -// */ -// @OnMessage -// public void onMessage(String message, Session session) { -// -// System.out.println(message); -// //可以群发消息 -// //消息保存到数据库、redis -// if (StringUtils.isNotBlank(message) && !message.equals("undefined")) { -// try { -// //解析发送的报文 -// JSONObject jsonObject = new JSONObject(); -// if (StringUtils.isNotEmpty(message)) { -// jsonObject = JSONObject.parseObject(message); -// } -// //追加发送人(防止串改) -// jsonObject.put("tableId", this.tableId); -// jsonObject.put("shopId", this.shopId); -// -// //这里采用责任链模式,每一个处理器对应一个前段发过来的请,这里还可以用工厂模式来生成对象 -//// ChangeHandler changeHandler = new ChangeHandler(); -//// CreateOrderHandler createOrderHandler = new CreateOrderHandler(); -//// SyncHandler syncHandler = new SyncHandler(); -//// ClearHandler clearHandler = new ClearHandler(); -//// OtherHandler otherHandler = new OtherHandler(); -//// -//// changeHandler.addNextHandler(syncHandler).addNextHandler(createOrderHandler).addNextHandler(clearHandler).addNextHandler(otherHandler); -//// changeHandler.handleRequest(webSocketMap,jsonObject,recordMap,this); -// if ("sku".equals(jsonObject.getString("type"))){ -// boolean exist = redisUtils.exists(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId))); -// Integer num = 0; -// if (exist){ -// JSONArray array = JSON.parseArray(redisUtils.getMessage(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId)))); -// for (int i = 0; i < array.size(); i++) { -// JSONObject object = array.getJSONObject(i); -// if (object.getString("skuId").equals(jsonObject.getString("skuId"))) { -// num = object.getIntValue("totalNumber"); -// break; -// } -// } -// } -// JSONObject jsonObject1 = new JSONObject(); -// jsonObject1.put("status", "success"); -// jsonObject1.put("msg", "成功"); -// jsonObject1.put("type", "sku"); -// jsonObject1.put("data", new ArrayList<>()); -// jsonObject1.put("amount", num); -// sendMessage(jsonObject1); -// }else { -// rabbitProducer.putCart(jsonObject.toJSONString()); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// } -// -// /** -// * 发生错误时候 -// * -// * @param session -// * @param error -// */ -// @OnError -// public void onError(Session session, Throwable error) { -// log.error("用户错误:" + this.tableId + ",原因:" + error.getMessage()); -// error.printStackTrace(); -// } -// -// /** -// * 实现服务器主动推送 -// */ -// public void sendMessage(Object message) throws IOException { -// //加入线程锁 -// synchronized (session) { -// try { -// //同步发送信息 -// this.session.getBasicRemote().sendObject(message); -// } catch (Exception e) { -// log.error("服务器推送失败:" + e.getMessage()); -// } -// } -// } -// -// -// /** -// * 发送自定义消息 -// * */ -// /** -// * 发送自定义消息 -// * -// * @param message 发送的信息 -// * @param tableId 如果为null默认发送所有 -// * @throws IOException -// */ -// public static void AppSendInfo(Object message, String tableId, boolean userFlag) throws IOException { -// if (userFlag) { -// if (userSocketMap.containsKey(tableId)) { -// AppWebSocketServerCopy server = userSocketMap.get(tableId); -// server.sendMessage(message); -// } else { -// log.error("请求的userId:" + tableId + "不在该服务器上"); -// } -// } else { -// if (StringUtils.isEmpty(tableId)) { -// // 向所有用户发送信息 -// for (List serverList : webSocketMap.values()) { -// for (AppWebSocketServerCopy server : serverList) { -// server.sendMessage(message); -// } -// } -// } else if (webSocketMap.containsKey(tableId)) { -// // 发送给指定用户信息 -// List serverList = webSocketMap.get(tableId); -// for (AppWebSocketServerCopy server : serverList) { -// server.sendMessage(message); -// } -// } else { -// log.error("请求的tableId:" + tableId + "不在该服务器上"); -// } -// } -// -// } -// -// -// public static synchronized ConcurrentHashMap> getWebSocketMap() { -// return AppWebSocketServerCopy.webSocketMap; -// } -// -// public static synchronized ConcurrentHashMap> getRecordMap() { -// return AppWebSocketServerCopy.recordMap; -// } -//} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/socket/SocketSession.java b/src/main/java/com/chaozhanggui/system/cashierservice/socket/SocketSession.java deleted file mode 100644 index ee626f1..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/socket/SocketSession.java +++ /dev/null @@ -1,14 +0,0 @@ -//package com.chaozhanggui.system.cashierservice.socket; -// -//import lombok.Data; -// -//import javax.websocket.Session; -//import java.io.Serializable; -// -//@Data -//public class SocketSession implements Serializable { -// private Session session; -// private String tableId ; -// private String shopId ; -// private String userId ; -//} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/socket/WebSocketConfig.java b/src/main/java/com/chaozhanggui/system/cashierservice/socket/WebSocketConfig.java deleted file mode 100644 index bf08678..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/socket/WebSocketConfig.java +++ /dev/null @@ -1,27 +0,0 @@ -//package com.chaozhanggui.system.cashierservice.socket; -// -//import org.springframework.boot.web.servlet.ServletContextInitializer; -//import org.springframework.context.annotation.Bean; -//import org.springframework.context.annotation.Configuration; -//import org.springframework.stereotype.Component; -//import org.springframework.web.socket.config.annotation.EnableWebSocket; -//import org.springframework.web.socket.server.standard.ServerEndpointExporter; -// -//import javax.servlet.ServletContext; -//import javax.servlet.ServletException; -// -///** -// * WebSocket配置 -// */ -//@Configuration -//public class WebSocketConfig implements ServletContextInitializer { -// -// @Bean -// public ServerEndpointExporter serverEndpointExporter () { -// return new ServerEndpointExporter(); -// } -// @Override -// public void onStartup(ServletContext servletContext) throws ServletException { -// -// } -//} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/socket/WebSocketServer.java b/src/main/java/com/chaozhanggui/system/cashierservice/socket/WebSocketServer.java deleted file mode 100644 index 3aac705..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/socket/WebSocketServer.java +++ /dev/null @@ -1,113 +0,0 @@ -//package com.chaozhanggui.system.cashierservice.socket; -// -//import org.springframework.stereotype.Component; -// -//import javax.websocket.*; -//import javax.websocket.server.ServerEndpoint; -//import java.io.IOException; -//import java.util.concurrent.CopyOnWriteArraySet; -//import java.util.concurrent.atomic.AtomicInteger; -// -// -//@Component -//@ServerEndpoint(value = "/ws") -//public class WebSocketServer { -// -// //与某个客户端的连接会话,需要通过它来给客户端发送数据 -// private Session session; -// -// private static final AtomicInteger OnlineCount = new AtomicInteger(0); -// -// private static CopyOnWriteArraySet SessionSet = new CopyOnWriteArraySet<>(); -// -// /** -// * 连接建立成功调用的方法 -// */ -// @OnOpen -// public void onOpen(Session session) { -// SessionSet.add(session); -// this.session = session; -// int cnt = OnlineCount.incrementAndGet(); // 在线数加1 -// System.out.println("有连接加入,当前连接数为:" + cnt); -// } -// -// /** -// * 连接关闭调用的方法 -// */ -// @OnClose -// public void onClose() { -// SessionSet.remove(this.session); -// int cnt = OnlineCount.decrementAndGet(); -// System.out.println("有连接关闭,当前连接数为:" + cnt); -// } -// -// /** -// * 收到客户端消息后调用的方法 -// * @param message 客户端发送过来的消息 -// */ -// @OnMessage -// public void onMessage(String message, Session session) { -// System.out.println(message); -// BroadCastInfo(message); -// } -// -// /** -// * 出现错误 -// * @param error -// */ -// @OnError -// public void onError(Throwable error) { -// error.printStackTrace(); -// } -// -// -// /** -// * 发送消息 -// * -// * @param session -// * @param message -// */ -// public static void SendMessage(Session session, String message) { -// try { -// if (session.isOpen()) { -// session.getBasicRemote().sendText(message); -// } -// } catch (IOException e) { -// e.printStackTrace(); -// } -// } -// -// /** -// * 群发消息 -// * -// * @param message -// * @throws IOException -// */ -// public static void BroadCastInfo(String message) { -// for (Session session : SessionSet) { -// SendMessage(session, message); -// } -// } -// -// /** -// * 指定Session发送消息 -// * -// * @param sessionId -// * @param message -// * @throws IOException -// */ -// public static void SendMessage(String message, String sessionId) { -// Session session = null; -// for (Session s : SessionSet) { -// if (s.getId().equals(sessionId)) { -// session = s; -// break; -// } -// } -// if (session != null) { -// SendMessage(session, message); -// } -// } -// -//} -// diff --git a/src/main/resources/mapper/TbCashierCartMapper.xml b/src/main/resources/mapper/TbCashierCartMapper.xml index dc3d287..0674893 100644 --- a/src/main/resources/mapper/TbCashierCartMapper.xml +++ b/src/main/resources/mapper/TbCashierCartMapper.xml @@ -32,7 +32,7 @@ - + id, master_id, order_id, ref_order_id, total_amount, product_id, cover_img, is_sku,pack_fee,is_pack,is_gift,pending_at, @@ -103,7 +103,7 @@ name, sale_price, number, total_number, refund_number, category_id, status, type, merchant_id, - shop_id, created_at, updated_at, pack_fee,trade_day,is_pack,is_gift,table_id,user_id + shop_id, created_at, updated_at, pack_fee,trade_day,is_pack,is_gift,table_id,user_id,sku_name ) values (#{id,jdbcType=INTEGER}, #{masterId,jdbcType=VARCHAR}, #{orderId,jdbcType=VARCHAR}, #{refOrderId,jdbcType=VARCHAR}, #{totalAmount,jdbcType=DECIMAL}, #{productId,jdbcType=VARCHAR}, @@ -112,7 +112,7 @@ #{totalNumber,jdbcType=REAL}, #{refundNumber,jdbcType=REAL}, #{categoryId,jdbcType=VARCHAR}, #{status,jdbcType=VARCHAR}, #{type,jdbcType=TINYINT}, #{merchantId,jdbcType=VARCHAR}, #{shopId,jdbcType=VARCHAR}, #{createdAt,jdbcType=BIGINT}, #{updatedAt,jdbcType=BIGINT}, #{packFee,jdbcType=DECIMAL} - , #{tradeDay,jdbcType=VARCHAR}, #{isPack,jdbcType=VARCHAR}, #{isGift,jdbcType=VARCHAR}, #{tableId,jdbcType=VARCHAR}, #{userId,jdbcType=INTEGER} + , #{tradeDay,jdbcType=VARCHAR}, #{isPack,jdbcType=VARCHAR}, #{isGift,jdbcType=VARCHAR}, #{tableId,jdbcType=VARCHAR}, #{userId,jdbcType=INTEGER},#{skuName,jdbcType=VARCHAR} )