diff --git a/pom.xml b/pom.xml index 9252fdc..bd06fb1 100644 --- a/pom.xml +++ b/pom.xml @@ -183,6 +183,10 @@ spring-boot-starter-websocket + + io.netty + netty-all + org.springframework.boot spring-boot-starter-amqp diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/config/ChangeHandler.java b/src/main/java/com/chaozhanggui/system/cashierservice/config/ChangeHandler.java index 969a880..9295ff5 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/config/ChangeHandler.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/config/ChangeHandler.java @@ -1,35 +1,35 @@ -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); - } - } - } -} - +//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 index c5b8981..e1b92a7 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/config/ClearHandler.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/config/ClearHandler.java @@ -1,33 +1,33 @@ -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); - } - } - } -} +//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 index ef2c04c..7d52894 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/config/CreateOrderHandler.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/config/CreateOrderHandler.java @@ -1,79 +1,79 @@ -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()); -// } +//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 { // // -// }catch (Exception e){ -// e.printStackTrace(); -// AppSendInfo("订单提交失败",webSocke.getTableId()); +// 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; // } - - - - } - } - - } else { - // 无法处理,传递给下一个处理器 - if (nextHandler != null) { - nextHandler.handleRequest(webSocketMap,jsonObject,recordMap,webSocke); - } - } - } -} +// +// 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 index 9529bc3..b269f84 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/config/Handler.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/config/Handler.java @@ -1,26 +1,26 @@ -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 +//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 index 44ecf80..6e613b7 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/config/OtherHandler.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/config/OtherHandler.java @@ -1,30 +1,30 @@ -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() + "不在该服务器上"); - } - } -} +//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 index 44a0298..8474c6f 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/config/SyncHandler.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/config/SyncHandler.java @@ -1,46 +1,46 @@ -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 +//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/dao/TbCashierCartMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbCashierCartMapper.java index e9ed13b..4f2e299 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbCashierCartMapper.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbCashierCartMapper.java @@ -20,6 +20,7 @@ public interface TbCashierCartMapper { int updateByPrimaryKeySelective(TbCashierCart record); + List selectByShopIdAndTableId(@Param("shopId") String shopId,@Param("tableId") String tableId); List selectALlByMasterId(@Param("masterId") String masterId, @Param("status") String status); @@ -55,4 +56,5 @@ public interface TbCashierCartMapper { List selectByOrderId(@Param("orderId") String orderId,@Param("status") String status); void updateStatusByTableId(@Param("tableId")String tableId,@Param("status") String status); + void updateStatusById(@Param("id")Integer id,@Param("status") String status); } \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/netty/HeartbeatHandler.java b/src/main/java/com/chaozhanggui/system/cashierservice/netty/HeartbeatHandler.java new file mode 100644 index 0000000..f163b9b --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/netty/HeartbeatHandler.java @@ -0,0 +1,38 @@ +package com.chaozhanggui.system.cashierservice.netty; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelFutureListener; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; +import io.netty.handler.timeout.IdleState; +import io.netty.handler.timeout.IdleStateEvent; +import io.netty.util.CharsetUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.annotation.Resource; + +@Slf4j +public class HeartbeatHandler extends ChannelDuplexHandler { + private static final ByteBuf HEARTBEAT_SEQUENCE = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("HEARTBEAT", CharsetUtil.UTF_8)); + + + @Override + public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { + if (evt instanceof IdleStateEvent) { + IdleStateEvent event = (IdleStateEvent) evt; + if (event.state() == IdleState.READER_IDLE) { + ctx.close(); + super.userEventTriggered(ctx, evt); + } else if (event.state() == IdleState.WRITER_IDLE) { +// log.info("发送心跳"); + ctx.channel().writeAndFlush(new TextWebSocketFrame("Heartbeat")).addListener(ChannelFutureListener.CLOSE_ON_FAILURE); +// ctx.writeAndFlush(HEARTBEAT_SEQUENCE.duplicate()).addListener(ChannelFutureListener.CLOSE_ON_FAILURE); + } + } else { + super.userEventTriggered(ctx, evt); + } + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/netty/PushToAppChannelHandlerAdapter.java b/src/main/java/com/chaozhanggui/system/cashierservice/netty/PushToAppChannelHandlerAdapter.java new file mode 100644 index 0000000..4ba7064 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/netty/PushToAppChannelHandlerAdapter.java @@ -0,0 +1,233 @@ +package com.chaozhanggui.system.cashierservice.netty; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.chaozhanggui.system.cashierservice.netty.config.NettyChannelHandlerAdapter; +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 io.netty.channel.ChannelFutureListener; +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; +import io.netty.handler.timeout.IdleState; +import io.netty.handler.timeout.IdleStateEvent; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.annotation.Resource; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + + +/** + * 摄像机TCP通讯的信息存储处理 + */ +@Slf4j +@Sharable +@Component +public class PushToAppChannelHandlerAdapter extends NettyChannelHandlerAdapter { + + /** + * [tableID-shopId, [userId, ctx]] + */ + private static Map> webSocketMap = new HashMap<>(); + + /** + * [ctx, tableID-shopId:userId] + */ + private static Map ctxToUserIdMap = new ConcurrentHashMap<>(); + + private RedisUtil redisUtils = SpringUtils.getBean(RedisUtil.class); + private String tableId = ""; + private String shopId = ""; + @Resource + private RabbitProducer a; + //注入为空 + public static RabbitProducer rabbitProducer; + @PostConstruct + public void b() { + rabbitProducer = this.a; + } + + public PushToAppChannelHandlerAdapter() { + } + + public static PushToAppChannelHandlerAdapter getInstance() { + return new PushToAppChannelHandlerAdapter(); + } + + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + super.channelActive(ctx); + } + + @Override + public void channelInactive(ChannelHandlerContext ctx) { + log.info("netty连接 长连接关闭:{}, {}",tableId,shopId); + ctx.close(); + removeCtx(ctx); + } + + public void close(ChannelHandlerContext ctx) { + log.info("netty连接 长连接关闭:{}, {}",tableId,shopId); + ctx.close(); + } + + /** + * 移除ctx + */ + private void removeCtx(ChannelHandlerContext ctx) { + // 遍历webSocketMap,查找并移除对应的ChannelHandlerContext + String key = ctxToUserIdMap.get(ctx); + if (StringUtils.isNotBlank(key)) { + String[] split = key.split(":"); + ConcurrentHashMap tableMap = webSocketMap.get(split[0]); + if (tableMap != null && !tableMap.isEmpty() && tableMap.size() > 0) { + tableMap.remove(split[1]); + if (tableMap.isEmpty() || tableMap.size() == 0) { + webSocketMap.remove(split[0]); + redisUtils.deleteByKey(RedisCst.TABLE_CART.concat(split[0])); + } + } + } + ctxToUserIdMap.remove(ctx); + } + + @Override + public void channelReadComplete(ChannelHandlerContext ctx) { + super.channelReadComplete(ctx); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { + super.exceptionCaught(ctx, cause); + removeCtx(ctx); + } + + @Override + public void channelRead(ChannelHandlerContext ctx, String msg) { + log.info("netty连接 接收到数据:{}",msg); + JSONObject jsonObject = new JSONObject(); + if (StringUtils.isNotEmpty(msg)) { + jsonObject = JSONObject.parseObject(msg); + }else { + log.info("netty连接 接收到空数据:{}",msg); + } + String type = jsonObject.getString("type"); + if(type.equals("heartbeat")){//心跳 + log.info("netty连接 接收到数据:tableId:{} meg:{}",tableId,msg); + }else { + if (type.equals("connect")) { + String tableId = jsonObject.getString("tableId"); + String shopId = jsonObject.getString("shopId"); + String userId = jsonObject.getString("userId"); + if (StringUtils.isBlank(type) || StringUtils.isBlank(shopId) || StringUtils.isBlank(userId)) { + log.info("netty连接 建立连接请求失败:{}",jsonObject); + channelInactive(ctx); + return; + } + String key = tableId + "-" + shopId; + log.info("netty连接 接收到数据 建立连接参数 param:{}",jsonObject); + this.tableId=tableId; + this.shopId=shopId; + if (webSocketMap.containsKey(key)) { + ConcurrentHashMap userSocketMap = webSocketMap.get(key); +// ChannelHandlerContext channelHandlerContext = userSocketMap.get(userId); +// if (channelHandlerContext != null) { +// channelHandlerContext.close(); +// } + userSocketMap.put(userId, ctx); + } else { + ConcurrentHashMap userSocketMap = new ConcurrentHashMap<>(); + userSocketMap.put(userId, ctx); + webSocketMap.put(key,userSocketMap); + } + ctxToUserIdMap.put(ctx, key + ":" + userId); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("status", "success"); + jsonObject1.put("msg", "连接成功"); + jsonObject1.put("type", "connect"); + sendMesToApp(jsonObject1.toString(), ctx); + + jsonObject.put("type","initCart"); + rabbitProducer.putCart(jsonObject.toJSONString()); + } + else{ + jsonObject.put("tableId", this.tableId); + jsonObject.put("shopId", this.shopId); + if("sku".equals(type)){ + boolean exist = redisUtils.exists(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId))); + Integer num = 0; + if (exist){ + String message = redisUtils.getMessage(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId))); + JSONArray array = JSON.parseArray(message); + 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); + sendMesToApp(jsonObject1.toString(),ctx); + }else { + rabbitProducer.putCart(jsonObject.toJSONString()); + } + } + } + //业务逻辑代码处理框架。。。 + ctx.flush(); + } + + public void sendMesToApp(String str, ChannelHandlerContext ctx) { + sendMessage(ctx, str); + } + + @Async + public void AppSendInfo(String message, String tableId,String userId, boolean userFlag) { + log.info("netty连接 发送消息 tableId:{} userId:{} userFlag:{} message:{}",tableId,userId,userFlag, JSONUtil.toJSONString(message)); + if (userFlag) { + if (webSocketMap.containsKey(tableId)) { + ConcurrentHashMap webSockets = webSocketMap.get(tableId); + if(!webSockets.isEmpty()){ + if (StringUtils.isNotBlank(userId)) { + ChannelHandlerContext ctx = webSockets.get(userId); + if (ctx != null) { + sendMesToApp(message,ctx); + } + } + } + } + } else { + if (StringUtils.isEmpty(tableId)) { + // 向所有用户发送信息 + for (ConcurrentHashMap value : webSocketMap.values()) { + for (ChannelHandlerContext ctx : value.values()) { + sendMesToApp(message,ctx); + } + } + } else if (webSocketMap.containsKey(tableId)) { + ConcurrentHashMap webSockets = webSocketMap.get(tableId); + if(!webSockets.isEmpty()) { + for (ChannelHandlerContext ctx : webSockets.values()) { + sendMesToApp(message,ctx); + } + } + } + } + + } +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/netty/PushToAppChannelInitializer.java b/src/main/java/com/chaozhanggui/system/cashierservice/netty/PushToAppChannelInitializer.java new file mode 100644 index 0000000..0da7d2c --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/netty/PushToAppChannelInitializer.java @@ -0,0 +1,55 @@ +package com.chaozhanggui.system.cashierservice.netty; + +import io.netty.channel.ChannelInitializer; +import io.netty.channel.ChannelPipeline; +import io.netty.channel.socket.nio.NioSocketChannel; +import io.netty.handler.codec.http.HttpObjectAggregator; +import io.netty.handler.codec.http.HttpServerCodec; +import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; +import io.netty.handler.ssl.SslContext; +import io.netty.handler.ssl.SslContextBuilder; +import io.netty.handler.stream.ChunkedWriteHandler; +import io.netty.handler.timeout.IdleStateHandler; +import lombok.extern.slf4j.Slf4j; +import org.springframework.core.io.ClassPathResource; +import org.springframework.stereotype.Component; + +import javax.net.ssl.SSLException; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.concurrent.TimeUnit; + +@Component +@Slf4j +public class PushToAppChannelInitializer extends ChannelInitializer { + + + + @Override + protected void initChannel(NioSocketChannel ch) throws SSLException { + ChannelPipeline pipeline = ch.pipeline(); + + // 添加心跳处理器 多久没收到消息 断开 心跳时间(秒) 读写空闲时间(秒) + pipeline.addLast(new IdleStateHandler(30, 10, 120, TimeUnit.SECONDS)); + pipeline.addLast(new HeartbeatHandler()); + + //本地试调时使用 +// SslContext sslContext = SslContextBuilder.forServer(loadResourceAsByteArrayInputStream("\\pem\\fullchain.pem"), loadResourceAsByteArrayInputStream("\\pem\\privkey.key")).build(); +// pipeline.addLast(sslContext.newHandler(ch.alloc())); + + // 添加HttpServerCodec用于处理HTTP编解码 + pipeline.addLast(new HttpServerCodec()); + pipeline.addLast(new ChunkedWriteHandler()); + pipeline.addLast(new HttpObjectAggregator(65536)); + pipeline.addLast(new WebSocketServerProtocolHandler("/netty")); + ch.pipeline().addLast(new PushToAppChannelHandlerAdapter()); + } + + + public static InputStream loadResourceAsByteArrayInputStream(String path) { + InputStream inputStream = PushToAppChannelInitializer.class.getClassLoader().getResourceAsStream(path); + return inputStream; + } +} 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 new file mode 100644 index 0000000..20422b3 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/netty/config/NettyChannelHandlerAdapter.java @@ -0,0 +1,262 @@ +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; + +/** + * netty核心处理类 + * 通道的信息需要自己存储,一般实现存储在一个ConcurrentHashMap中 + */ +@Slf4j +public abstract class NettyChannelHandlerAdapter extends ChannelInboundHandlerAdapter { + + /** + * 给客户端发送消息 + */ + public static void sendMessage(ChannelHandlerContext ctx, String content) { +// ctx.channel().writeAndFlush(content); + ctx.channel().writeAndFlush(new TextWebSocketFrame(content)); + } + + /** + * 群发消息 + */ + public static void sendAllMessage(Collection c, String content) { + for (ChannelHandlerContext ctx : c) { + ctx.channel().writeAndFlush(content); + } + } + + /** + * 客户端与服务器建立连接的时候触发 + * + * @param ctx 连接信息 + */ + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + super.channelActive(ctx); + } + + /** + * 客户端与服务器关闭连接的时候触发 + * + * @param ctx 连接信息 + */ + @Override + public void channelInactive(ChannelHandlerContext ctx) throws Exception { + super.channelInactive(ctx); +// ctx.close(); + } + + /** + * 服务端接收客户端发送过来的数据结束之后调用 + */ + @Override + public void channelReadComplete(ChannelHandlerContext ctx) { + ctx.flush(); + } + + /** + * 工程出现异常的时候调用
+ * 需要自己remove掉map中的内容 + */ + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { + log.info("netty出现异常:", cause); + ctx.close(); + } + + /** + * 服务器接受客户端的数据信息时触发 + */ + @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); + } + else if (msg instanceof FullHttpRequest) { + FullHttpRequest httpRequest =(FullHttpRequest) msg; // 获取消息内容 + String uri = httpRequest.uri(); + // 使用QueryStringDecoder来解析查询参数 + QueryStringDecoder decoder = new QueryStringDecoder(uri); + // 获取所有的参数 + Map> params = decoder.parameters(); + // 如果是普通的 HTTP 请求,进行相应的处理 + channelRead(ctx, uri); + } + else{ + channelRead(ctx, msg.toString()); + } + } + + 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; + } + + /** + * 服务器接受客户端的数据信息时触发 + * + * @param ctx 连接信息 + * @param msg 消息内容 + */ + public abstract void channelRead(ChannelHandlerContext ctx, String msg); + + @Override + public final void channelRegistered(ChannelHandlerContext ctx) throws Exception { + super.channelRegistered(ctx); + } + + @Override + public final void channelUnregistered(ChannelHandlerContext ctx) throws Exception { + super.channelUnregistered(ctx); + } + + @Override + public final void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { + super.userEventTriggered(ctx, evt); + } + + @Override + public final void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { + super.channelWritabilityChanged(ctx); + } + + @Override + protected final void ensureNotSharable() { + super.ensureNotSharable(); + } + + @Override + public final boolean isSharable() { + return super.isSharable(); + } + + @Override + public final void handlerAdded(ChannelHandlerContext ctx) throws Exception { + super.handlerAdded(ctx); + } + + @Override + public final void handlerRemoved(ChannelHandlerContext ctx) throws Exception { + super.handlerRemoved(ctx); + } +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/netty/config/NettyConfig.java b/src/main/java/com/chaozhanggui/system/cashierservice/netty/config/NettyConfig.java new file mode 100644 index 0000000..07793ec --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/netty/config/NettyConfig.java @@ -0,0 +1,38 @@ +package com.chaozhanggui.system.cashierservice.netty.config; + +import com.chaozhanggui.system.cashierservice.netty.PushToAppChannelInitializer; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.annotation.Resource; + +@Service +@Slf4j +public class NettyConfig { + + /** + * 端口号 + */ + @Value("${netty.server.port}") + private int port; + + /** + * 接收者的线程数 + */ + @Value("${netty.server.parent-group-threads}") + private int parentGroupThreads; + /** + * 客户端的线程数 + */ + @Value("${netty.server.child-group-threads}") + private int childGroupThreads; + + @Resource + private PushToAppChannelInitializer pushToAppChannelInitializer; + @PostConstruct + public void startCameraNetty() { + NettyUtils.getInstance().initNetty(port, parentGroupThreads, childGroupThreads, pushToAppChannelInitializer); + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/netty/config/NettyUtils.java b/src/main/java/com/chaozhanggui/system/cashierservice/netty/config/NettyUtils.java new file mode 100644 index 0000000..673e932 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/netty/config/NettyUtils.java @@ -0,0 +1,73 @@ +package com.chaozhanggui.system.cashierservice.netty.config; + +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.ChannelOption; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.channel.socket.nio.NioSocketChannel; +import io.netty.handler.logging.LogLevel; +import io.netty.handler.logging.LoggingHandler; +import lombok.extern.slf4j.Slf4j; + +import java.net.InetSocketAddress; + +@Slf4j +public class NettyUtils { + + private ChannelFuture channelFuture; + private EventLoopGroup parentGroup; + private EventLoopGroup childGroup; + private int port; + + private NettyUtils() { + } + + public static NettyUtils getInstance() { + return new NettyUtils(); + } + + /** + * netty 工具方法 + * + * @param port 端口号 + * @param parentGroupThreads 接收者的线程数 + * @param childGroupThreads 客户端的线程数 + * @param channelInitializer 客户端成功connect后执行的handler + */ + public void initNetty(int port, int parentGroupThreads, int childGroupThreads, ChannelInitializer channelInitializer) { + log.info("netty初始化 "); + // 接收者 线程组用于处理链接工作 + parentGroup = new NioEventLoopGroup(parentGroupThreads); + // 客户端 线程组用户处理数据工作 + childGroup = new NioEventLoopGroup(childGroupThreads); + this.port = port; + + ServerBootstrap bootstrap = new ServerBootstrap(); + bootstrap.group(parentGroup, childGroup) + // 指定channel + .channel(NioServerSocketChannel.class) + // 定义日志等级 + .handler(new LoggingHandler(LogLevel.INFO)) + // 指定端口 + .localAddress(new InetSocketAddress(port)) + //服务端可连接队列数,对应TCP/IP协议listen函数中backlog参数 + .option(ChannelOption.SO_BACKLOG, 1024) + //设置TCP长连接,一般如果两个小时内没有数据通信时,tcp会自动发一个活动探测数据报文 + .childOption(ChannelOption.SO_KEEPALIVE, true) + //将小的数据包包装成跟更大的帧进行传送,提高网络负载 + .childOption(ChannelOption.TCP_NODELAY, true) + //设置超时时间 + .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000 * 60 * 10) + // handler 在初始化时就会执行,而 childHandler 会在客户端成功connect后才执行,这是两者的区别。 + // .handler + .childHandler(channelInitializer); + try { + channelFuture = bootstrap.bind(port).sync(); + } catch (Exception e) { + log.error("netty 启动时出错:" + e); + } + } +} 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 d0d0e61..793b538 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.CartService; +import com.chaozhanggui.system.cashierservice.service.CartService1; 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 CartService cartService; + private CartService1 cartService; @RabbitHandler @RabbitListener(queues = {"${queue}"}) public void listener(String message) { @@ -34,8 +34,9 @@ public class CartConsumer { JSONObject jsonObject = JSON.parseObject(message); String tableId = jsonObject.getString("tableId"); String shopId = jsonObject.getString("shopId"); - log.info("推送信息"+jsonObject.toJSONString()); - if (jsonObject.getString("type").equals("addcart") ) { + if (jsonObject.getString("type").equals("initCart") ) { + cartService.initCart(jsonObject); + }else if (jsonObject.getString("type").equals("addcart") ) { if (!jsonObject.containsKey("num")) { throw new MsgException("商品数量错误"); } @@ -46,12 +47,6 @@ public class CartConsumer { String cartDetail = redisUtil.getMessage(RedisCst.TABLE_CART.concat(tableId).concat("-").concat(shopId)); if (StringUtils.isEmpty(cartDetail)){ log.info("createOrder购物车为空"); -// JSONObject jsonObject1 = new JSONObject(); -// jsonObject1.put("status", "success"); -// jsonObject1.put("msg", "订单已存在"); -// jsonObject1.put("type", jsonObject.getString("type")); -// jsonObject1.put("data", "{\"id\": \"-1\"}"); -// AppWebSocketServer.AppSendInfo(jsonObject1,tableId+"-"+shopId, jsonObject.getString("userId"), true); throw new MsgException("购物车为空无法下单"); } JSONArray array = JSON.parseArray(cartDetail); 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 d0910d1..5089bbf 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,736 @@ -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.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(); +// } +// } +//} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/CartService1.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/CartService1.java new file mode 100644 index 0000000..b7f2bff --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/CartService1.java @@ -0,0 +1,766 @@ +package com.chaozhanggui.system.cashierservice.service; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.chaozhanggui.system.cashierservice.dao.*; +import com.chaozhanggui.system.cashierservice.entity.*; +import com.chaozhanggui.system.cashierservice.exception.MsgException; +import com.chaozhanggui.system.cashierservice.netty.PushToAppChannelHandlerAdapter; +import com.chaozhanggui.system.cashierservice.redis.RedisCst; +import com.chaozhanggui.system.cashierservice.redis.RedisUtil; +import com.chaozhanggui.system.cashierservice.util.DateUtils; +import com.chaozhanggui.system.cashierservice.util.JSONUtil; +import com.chaozhanggui.system.cashierservice.util.N; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; + +import java.io.IOException; +import java.math.BigDecimal; +import java.time.Instant; +import java.util.*; + +/** + * @author lyf + */ +@Service +@Slf4j +public class CartService1 { + + @Autowired + private RedisUtil redisUtil; + @Autowired + private TbOrderInfoMapper orderInfoMapper; + @Autowired + private TbCashierCartMapper cashierCartMapper; + @Autowired + private TbProductMapper productMapper; + @Autowired + private TbProductSkuMapper productSkuMapper; + @Autowired + private TbMerchantAccountMapper merchantAccountMapper; + @Autowired + private TbUserInfoMapper userInfoMapper; + @Autowired + private TbOrderDetailMapper orderDetailMapper; + @Autowired + private TbShopTableMapper shopTableMapper; + @Autowired + private TbUserCouponsMapper userCouponsMapper; + @Autowired + private TbSystemCouponsMapper systemCouponsMapper; + + public void initCart(JSONObject jsonObject) { + String tableId = jsonObject.getString("tableId"); + String shopId = jsonObject.getString("shopId"); + String key = tableId + "-" + shopId; + BigDecimal amount = BigDecimal.ZERO; + JSONArray array = new JSONArray(); + if (redisUtil.exists(RedisCst.TABLE_CART.concat(key))) { + array = JSON.parseArray(redisUtil.getMessage(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId)))); + for (int i = 0; i < array.size(); i++) { + JSONObject object = array.getJSONObject(i); + TbCashierCart cashierCart = JSONUtil.parseJSONStr2T(object.toJSONString(), TbCashierCart.class); + if (cashierCart.getNumber() > 0) { + amount = amount.add(new BigDecimal(cashierCart.getTotalNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee()))); + } + } + } else { + List tbCashierCarts = cashierCartMapper.selectByShopIdAndTableId(shopId, tableId); + if (!CollectionUtils.isEmpty(tbCashierCarts)) { + for (TbCashierCart cashierCart : tbCashierCarts) { + array.add(cashierCart); + amount = amount.add(new BigDecimal(cashierCart.getTotalNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee()))); + } + redisUtil.saveMessage(RedisCst.TABLE_CART.concat(key), array.toString()); + } + } + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("status", "success"); + jsonObject1.put("msg", "成功"); + jsonObject1.put("type", "addCart"); + jsonObject1.put("data", array); + jsonObject1.put("amount", amount); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), jsonObject.getString("tableId").concat("-").concat(shopId), "", false); + } + + // @Transactional(rollbackFor = Exception.class) + public void createCart(JSONObject jsonObject) { + try { + String tableId = jsonObject.getString("tableId"); + String shopId = jsonObject.getString("shopId"); + String key = tableId + "-" + shopId; + JSONArray jsonArray = new JSONArray(); + BigDecimal amount = BigDecimal.ZERO; + boolean exist = redisUtil.exists(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId")); + if (!exist) { + TbProductSkuWithBLOBs tbProductSkuWithBLOBs = productSkuMapper.selectByPrimaryKey(Integer.valueOf(jsonObject.getString("skuId"))); + Double stock = tbProductSkuWithBLOBs.getStockNumber(); + redisUtil.saveMessage(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), Math.round(stock) + ""); + } + String skuNum = redisUtil.getMessage(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId")); + if (Integer.valueOf(skuNum) < 1) { + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("status", "fail"); + jsonObject1.put("msg", "该商品库存已售罄"); + jsonObject1.put("data", new ArrayList<>()); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), key, jsonObject.getString("userId"), true); + log.error("该商品库存已售罄 skuId:{}", jsonObject.getString("skuId")); + throw new MsgException("该商品库存已售罄"); + } + if (jsonObject.getInteger("num") > 0) { + redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "1"); + } else { + redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "2"); + } + + if (redisUtil.exists(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId)))) { + JSONArray array = JSON.parseArray(redisUtil.getMessage(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId)))); + if (Objects.isNull(array) || array.isEmpty() || array.size() < 1) { + if (jsonObject.getInteger("num") > 0) { + TbCashierCart cashierCart = addCart(jsonObject.getString("productId"), jsonObject.getString("skuId"), + jsonObject.getInteger("userId"), jsonObject.getInteger("num"), tableId, jsonObject.getString("shopId")); + jsonArray.add(cashierCart); + amount = amount.add(new BigDecimal(cashierCart.getNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee()))); + } + } else { + boolean flag = true; + for (int i = 0; i < array.size(); i++) { + JSONObject object = array.getJSONObject(i); + TbCashierCart cashierCart = JSONUtil.parseJSONStr2T(object.toJSONString(), TbCashierCart.class); + if (cashierCart.getSkuId().equals(jsonObject.getString("skuId"))) { + cashierCart.setTotalNumber(cashierCart.getTotalNumber() + jsonObject.getInteger("num")); + cashierCart.setNumber(cashierCart.getNumber() + jsonObject.getInteger("num")); + if (cashierCart.getNumber() > 0) { + cashierCart.setTotalAmount(new BigDecimal(cashierCart.getTotalNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee()))); + cashierCartMapper.updateByPrimaryKeySelective(cashierCart); + } else { + cashierCartMapper.deleteByPrimaryKey(cashierCart.getId()); + continue; + } + flag = false; + } + jsonArray.add(cashierCart); + amount = amount.add(new BigDecimal(cashierCart.getTotalNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee()))); + } + if (flag && jsonObject.getInteger("num") > 0) { + TbCashierCart cashierCart = addCart(jsonObject.getString("productId"), jsonObject.getString("skuId"), + jsonObject.getInteger("userId"), jsonObject.getInteger("num"), tableId, jsonObject.getString("shopId")); + jsonArray.add(cashierCart); + amount = amount.add(new BigDecimal(cashierCart.getTotalNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee()))); + } + } + } else { + if (jsonObject.getInteger("num") > 0) { + TbCashierCart cashierCart = addCart(jsonObject.getString("productId"), jsonObject.getString("skuId"), + jsonObject.getInteger("userId"), jsonObject.getInteger("num"), tableId, jsonObject.getString("shopId")); + jsonArray.add(cashierCart); + amount = amount.add(new BigDecimal(cashierCart.getTotalNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee()))); + } + } + productSkuMapper.updateStockById(jsonObject.getString("skuId"), jsonObject.getInteger("num")); +// AppWebSocketServer.getRecordMap().put(jsonObject.getString("tableId"), returnList); + redisUtil.saveMessage(RedisCst.TABLE_CART.concat(tableId).concat("-").concat(shopId), jsonArray.toJSONString()); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("status", "success"); + jsonObject1.put("msg", "成功"); + jsonObject1.put("type", jsonObject.getString("type")); + jsonObject1.put("data", jsonArray); + jsonObject1.put("amount", amount); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), jsonObject.getString("tableId").concat("-").concat(shopId), "", false); + } catch (Exception e) { + log.error("长链接错误 createCart{}", e.getMessage()); + } + } + + private TbCashierCart addCart(String productId, String skuId, Integer userId, Integer num, String tableId, String shopId) throws Exception { + try { + TbProduct product = productMapper.selectById(Integer.valueOf(productId)); + String key = tableId + "-" + shopId; + if (Objects.isNull(product)) { + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("status", "fail"); + jsonObject1.put("msg", "该商品不存在"); + jsonObject1.put("data", new ArrayList<>()); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), key, userId.toString(), true); + log.error("购物车添加商品异常,该商品不存在:{}",productId); + throw new MsgException("该商品不存在"); + } + TbProductSkuWithBLOBs productSku = productSkuMapper.selectByPrimaryKey(Integer.valueOf(skuId)); + if (Objects.isNull(productSku)) { + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("status", "fail"); + jsonObject1.put("msg", "该商品规格不存在"); + jsonObject1.put("data", new ArrayList<>()); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), key, userId.toString(), true); + log.error("购物车添加商品异常,该商品sku不存在:{}",productId); + throw new MsgException("该商品规格不存在"); + } + TbCashierCart cashierCart = new TbCashierCart(); + cashierCart.setProductId(productId); + cashierCart.setSkuId(skuId); + cashierCart.setNumber(num); + cashierCart.setCoverImg(product.getCoverImg()); + cashierCart.setName(product.getName()); + cashierCart.setCategoryId(product.getCategoryId()); + cashierCart.setShopId(shopId); + cashierCart.setUserId(userId); + cashierCart.setTableId(tableId); + cashierCart.setSkuName(productSku.getSpecSnap()); + cashierCart.setIsPack("false"); + cashierCart.setIsGift("false"); + cashierCart.setStatus("create"); + cashierCart.setType((byte) 0); + cashierCart.setSalePrice(productSku.getSalePrice()); + cashierCart.setCreatedAt(Instant.now().toEpochMilli()); + cashierCart.setUpdatedAt(Instant.now().toEpochMilli()); + cashierCart.setTotalNumber(num); + cashierCart.setPackFee(BigDecimal.ZERO); + cashierCart.setRefundNumber(0); + cashierCart.setTotalAmount(new BigDecimal(cashierCart.getTotalNumber()).multiply(productSku.getSalePrice().add(cashierCart.getPackFee()))); + cashierCartMapper.insert(cashierCart); + return cashierCart; + } catch (Exception e) { + log.error("长链接错误 addCart{}", e.getMessage()); + throw e; + } + } + + @Transactional(rollbackFor = Exception.class) + public void createOrder(JSONObject jsonObject) { + try { + String shopId = jsonObject.getString("shopId"); + String tableId = jsonObject.getString("tableId"); + String key = tableId + "-" + shopId; + JSONArray array = JSON.parseArray(redisUtil.getMessage(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId)))); + List 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()); + } + cashierCartMapper.updateStatusById(cashierCart.getId(), "final"); + } + //总金额 + TbShopTable shopTable = shopTableMapper.selectQRcode(jsonObject.getString("tableId")); + //生成订单 + TbOrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId); + String isBuyYhq = "false"; + String isuseYhq = "false"; + if (jsonObject.containsKey("isYhq") && jsonObject.getString("isYhq").equals("1")) { + couponId = jsonObject.getString("couponsId"); + //1:购买优惠券,0:自己持有优惠券 + Integer couponsId = jsonObject.getInteger("couponsId"); + if (jsonObject.getString("isBuyYhq").equals("1")) { + TbSystemCoupons systemCoupons = systemCouponsMapper.selectByPrimaryKey(couponsId); + if (Objects.isNull(systemCoupons) || !systemCoupons.getStatus().equals("0")) { + log.info("开始处理订单"); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("status", "fail"); + jsonObject1.put("msg", "优惠券已售空"); + jsonObject1.put("type", jsonObject.getString("type")); + jsonObject1.put("data", ""); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), key, jsonObject.getString("userId"), true); + log.info("消息推送"); + return; + } + if (N.gt(systemCoupons.getCouponsAmount(), totalAmount)) { + log.info("开始处理订单"); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("status", "fail"); + jsonObject1.put("msg", "订单金额小于优惠价金额"); + jsonObject1.put("type", jsonObject.getString("type")); + jsonObject1.put("data", ""); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), key, jsonObject.getString("userId"), true); + log.info("消息推送"); + return; + } + totalAmount = totalAmount.add(systemCoupons.getCouponsPrice()).subtract(systemCoupons.getCouponsAmount()); + originAmount = originAmount.add(systemCoupons.getCouponsPrice()); + couponAmount = systemCoupons.getCouponsAmount(); + systemCoupons.setStatus("1"); + systemCouponsMapper.updateByPrimaryKeySelective(systemCoupons); + TbUserCoupons userCoupons = new TbUserCoupons(); + userCoupons.setEndTime(DateUtils.getNewDate(new Date(), 3, systemCoupons.getDayNum())); + userCoupons.setCouponsAmount(systemCoupons.getCouponsAmount()); + userCoupons.setCouponsPrice(systemCoupons.getCouponsPrice()); + userCoupons.setStatus("1"); + userCoupons.setUserId(userId); + userCoupons.setCreateTime(new Date()); + userCouponsMapper.insert(userCoupons); + couponId = userCoupons.getId() + ""; + couponAmount = userCoupons.getCouponsAmount(); + } else { + TbUserCoupons userCoupons = userCouponsMapper.selectByPrimaryKey(couponsId); + if (Objects.isNull(userCoupons) || !userCoupons.getStatus().equals("0")) { + log.info("开始处理订单"); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("status", "fail"); + jsonObject1.put("msg", "优惠券已使用"); + jsonObject1.put("type", jsonObject.getString("type")); + jsonObject1.put("data", ""); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), key, jsonObject.getString("userId"), true); + log.info("消息推送"); + return; + } + if (N.gt(userCoupons.getCouponsAmount(), totalAmount)) { + log.info("开始处理订单"); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("status", "fail"); + jsonObject1.put("msg", "订单金额小于优惠价金额"); + jsonObject1.put("type", jsonObject.getString("type")); + jsonObject1.put("data", ""); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), key, jsonObject.getString("userId"), true); + log.info("消息推送"); + return; + } + totalAmount = totalAmount.subtract(userCoupons.getCouponsAmount()); + userCoupons.setStatus("1"); + userCoupons.setEndTime(DateUtils.getNewDate(new Date(), 5, 30)); + userCouponsMapper.updateByPrimaryKeySelective(userCoupons); + couponAmount = userCoupons.getCouponsAmount(); + } + isuseYhq = "true"; + + } + if (Objects.nonNull(orderInfo)) { + log.info("订单状态:" + orderInfo.getStatus()); + if (!"unpaid".equals(orderInfo.getStatus())) { + log.info("开始处理订单"); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("status", "fail"); + jsonObject1.put("msg", "订单正在支付中,请稍后再试"); + jsonObject1.put("type", jsonObject.getString("type")); + jsonObject1.put("data", ""); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), key, jsonObject.getString("userId"), true); + log.info("消息推送"); + return; + } + + orderDetailMapper.deleteByOUrderId(orderId); + orderInfo.setUpdatedAt(System.currentTimeMillis()); + orderInfo.setSettlementAmount(totalAmount); + orderInfo.setUserCouponId(couponId); + orderInfo.setUserCouponAmount(couponAmount); + orderInfo.setAmount(totalAmount); + orderInfo.setOriginAmount(originAmount); + orderInfo.setOrderAmount(totalAmount.add(packAMount)); + orderInfo.setFreightAmount(BigDecimal.ZERO); + orderInfo.setProductAmount(saleAmount); + orderInfo.setIsBuyCoupon(isBuyYhq); + orderInfo.setIsUseCoupon(isuseYhq); + orderInfoMapper.updateByPrimaryKeySelective(orderInfo); + } else { + orderInfo = getOrder(totalAmount, packAMount, shopTable, tbMerchantAccount.getId().toString(), jsonObject, originAmount); + orderInfo.setMerchantId(String.valueOf(tbMerchantAccount.getId())); + orderInfo.setUserCouponId(couponId); + orderInfo.setOriginAmount(originAmount); + orderInfo.setIsBuyCoupon(isBuyYhq); + orderInfo.setIsUseCoupon(isuseYhq); + orderInfo.setUserCouponAmount(couponAmount); + orderInfoMapper.insert(orderInfo); + orderId = orderInfo.getId(); + } + for (TbOrderDetail orderDetail : orderDetails) { + orderDetail.setOrderId(orderId); + orderDetailMapper.insert(orderDetail); + } + for (int i = 0; i < array.size(); i++) { + JSONObject object = array.getJSONObject(i); + TbCashierCart cashierCart = JSONUtil.parseJSONStr2T(object.toJSONString(), TbCashierCart.class); + cashierCart.setUpdatedAt(System.currentTimeMillis()); + cashierCart.setOrderId(orderId + ""); + cashierCart.setStatus("closed"); + cashierCartMapper.updateByPrimaryKeySelective(cashierCart); + object.put("updatedAt", System.currentTimeMillis()); + object.put("orderId", orderId + ""); + } + redisUtil.saveMessage(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId")).concat("-").concat(shopId), array.toJSONString()); + orderInfo.setDetailList(orderDetails); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("status", "success"); + jsonObject1.put("msg", "成功"); + jsonObject1.put("type", jsonObject.getString("type")); + jsonObject1.put("data", orderInfo); + redisUtil.deleteByKey(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId")).concat("-").concat(shopId)); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), key, jsonObject.getString("userId"), true); + JSONObject jsonObject12 = new JSONObject(); + jsonObject12.put("status", "success"); + jsonObject12.put("msg", "成功"); + jsonObject12.put("type", "order"); + jsonObject12.put("amount", BigDecimal.ZERO); + + jsonObject12.put("data", new JSONArray()); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject12.toString(), jsonObject.getString("tableId").concat("-").concat(shopId), "", false); + } catch (Exception e) { + log.info("长链接错误 addCart{}", e.getMessage()); + e.printStackTrace(); + } + } + + private TbOrderInfo getOrder(BigDecimal totalAmount, BigDecimal packAMount, + TbShopTable shopTable, String merchantId, JSONObject jsonObject, BigDecimal originAmount) { + TbOrderInfo orderInfo = new TbOrderInfo(); + String orderNo = generateOrderNumber(); + orderInfo.setOrderNo(orderNo); + orderInfo.setSettlementAmount(totalAmount); + orderInfo.setPackFee(packAMount); + orderInfo.setOriginAmount(originAmount); + orderInfo.setProductAmount(originAmount); + orderInfo.setAmount(totalAmount); + orderInfo.setOrderAmount(totalAmount.add(packAMount)); + orderInfo.setPayAmount(BigDecimal.ZERO); + orderInfo.setRefundAmount(new BigDecimal("0.00")); + orderInfo.setTableId(jsonObject.getString("tableId")); + orderInfo.setSendType("table"); + orderInfo.setOrderType("miniapp"); + orderInfo.setTradeDay(DateUtils.getDay()); + orderInfo.setStatus("unpaid"); + orderInfo.setShopId(jsonObject.getString("shopId")); + orderInfo.setUserId(jsonObject.getString("userId")); + orderInfo.setCreatedAt(Instant.now().toEpochMilli()); + orderInfo.setSystemTime(Instant.now().toEpochMilli()); + orderInfo.setUpdatedAt(Instant.now().toEpochMilli()); + orderInfo.setIsAccepted((byte) 1); + if (Objects.nonNull(shopTable)) { + orderInfo.setTableName(shopTable.getName()); + } + orderInfo.setMerchantId(merchantId); + return orderInfo; + } + + public String generateOrderNumber() { + String date = DateUtils.getSdfTimes(); + Random random = new Random(); + int randomNum = random.nextInt(900) + 100; + return "WX" + date + randomNum; + } + + public void clearCart(JSONObject jsonObject) { + try { + String shopId = jsonObject.getString("shopId"); + if (redisUtil.exists(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId)))) { + JSONArray array = JSON.parseArray(redisUtil.getMessage(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId)))); + if (Objects.isNull(array) || array.isEmpty() || array.size() < 1) { + for (int i = 0; i < array.size(); i++) { + TbCashierCart cashierCart = JSONUtil.parseJSONStr2T(array.get(i).toString(), TbCashierCart.class); +// String result = redisUtil.secAdd(RedisCst.PRODUCT+shopId+":"+jsonObject.getString("skuId"),cashierCart.getNumber().toString()); + productSkuMapper.updateAddStockById(jsonObject.getString("skuId"), cashierCart.getNumber()); + + } + } + } + cashierCartMapper.updateStatusByTableId(jsonObject.getString("tableId"), "closed"); + redisUtil.saveMessage(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId)), new JSONArray().toJSONString()); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("status", "success"); + jsonObject1.put("msg", "成功"); + jsonObject1.put("type", "clearCart"); + jsonObject1.put("amount", BigDecimal.ZERO); + jsonObject1.put("data", new ArrayList<>()); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), jsonObject.getString("tableId").concat("-").concat(shopId), "", false); + } catch (Exception e) { + log.info("长链接错误 clearCart{}", e.getMessage()); + e.printStackTrace(); + } + } + + @Transactional(rollbackFor = Exception.class) + public void pendingOrder(JSONObject jsonObject) throws IOException { + try { + String shopId = jsonObject.getString("shopId"); + String tableId = jsonObject.getString("tableId"); + String key = tableId + "-" + shopId; + JSONArray array = JSON.parseArray(redisUtil.getMessage(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId)))); + List 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/PayService.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/PayService.java index 34ae139..c49d9b0 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/service/PayService.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/PayService.java @@ -1,7 +1,6 @@ package com.chaozhanggui.system.cashierservice.service; import cn.hutool.core.util.ObjectUtil; -import cn.hutool.json.JSONUtil; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.chaozhanggui.system.cashierservice.dao.*; @@ -9,14 +8,12 @@ import com.chaozhanggui.system.cashierservice.entity.*; import com.chaozhanggui.system.cashierservice.entity.dto.ReturnGroupOrderDto; import com.chaozhanggui.system.cashierservice.exception.MsgException; import com.chaozhanggui.system.cashierservice.model.PayReq; -import com.chaozhanggui.system.cashierservice.model.ReturnOrderReq; import com.chaozhanggui.system.cashierservice.model.TradeQueryReq; import com.chaozhanggui.system.cashierservice.rabbit.RabbitProducer; import com.chaozhanggui.system.cashierservice.redis.RedisCst; import com.chaozhanggui.system.cashierservice.redis.RedisUtil; import com.chaozhanggui.system.cashierservice.sign.CodeEnum; import com.chaozhanggui.system.cashierservice.sign.Result; -import com.chaozhanggui.system.cashierservice.socket.AppWebSocketServer; import com.chaozhanggui.system.cashierservice.thirdpay.resp.OrderStatusQueryResp; import com.chaozhanggui.system.cashierservice.thirdpay.resp.PublicResp; import com.chaozhanggui.system.cashierservice.thirdpay.resp.WxScanPayResp; @@ -233,7 +230,7 @@ public class PayService { jsonObject1.put("type", ""); jsonObject1.put("data", new JSONArray()); jsonObject1.put("amount", 0); - AppWebSocketServer.AppSendInfo(jsonObject1,key, "",false); +// AppWebSocketServer.AppSendInfo(jsonObject1,key, "",false); tbCashierCartMapper.updateStatusByOrderId(orderId.toString(),"final"); return Result.success(CodeEnum.SUCCESS,object.getJSONObject("data")); }else { @@ -272,7 +269,7 @@ public class PayService { jsonObject1.put("data", new JSONArray()); jsonObject1.put("amount", 0); - AppWebSocketServer.AppSendInfo(jsonObject1,key, "",false); +// AppWebSocketServer.AppSendInfo(jsonObject1,key, "",false); tbCashierCartMapper.updateStatusByOrderId(orderId.toString(),"final"); ObjectMapper mapper = new ObjectMapper(); return Result.success(CodeEnum.SUCCESS,mapper.readTree(wxScanPayResp.getPayInfo())); diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/ProductService.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/ProductService.java index ea1f497..b9b2617 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/service/ProductService.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/ProductService.java @@ -10,7 +10,6 @@ import com.chaozhanggui.system.cashierservice.entity.dto.HomeDto; import com.chaozhanggui.system.cashierservice.entity.vo.*; import com.chaozhanggui.system.cashierservice.sign.CodeEnum; import com.chaozhanggui.system.cashierservice.sign.Result; -import com.chaozhanggui.system.cashierservice.socket.AppWebSocketServer; import com.chaozhanggui.system.cashierservice.util.*; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; @@ -22,12 +21,10 @@ import org.springframework.util.CollectionUtils; import javax.annotation.Resource; import java.math.BigDecimal; -import java.math.RoundingMode; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; @Service @@ -132,22 +129,10 @@ public class ProductService { if (ObjectUtil.isNotEmpty(in) && ObjectUtil.isNotNull(in)) { - log.info("请求参数:{}", in); List products = tbProductMapper.selectByIdIn(in); if (ObjectUtil.isNotEmpty(products) && products.size() > 0) { products.parallelStream().forEach(it -> { - Integer sum = 0; - if (AppWebSocketServer.userMap.containsKey(code)) { - Set userSet = AppWebSocketServer.userMap.get(code); - if (userSet.isEmpty()) { - sum = tbProductMapper.selectByQcode(code, it.getId(), it.getShopId()); - } else { - List userList = new ArrayList<>(userSet); - sum = tbProductMapper.selectByNewQcode(code, it.getId(), it.getShopId(), userList); - } - } else { - sum = tbProductMapper.selectByQcode(code, it.getId(), it.getShopId()); - } + Integer sum = tbProductMapper.selectByQcode(code, it.getId(), it.getShopId()); it.setCartNumber(sum == null ? "0" : String.valueOf(sum)); TbProductSkuResult skuResult = tbProductSkuResultMapper.selectByPrimaryKey(it.getId()); it.setProductSkuResult(skuResult); diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/socket/AppWebSocketServer.java b/src/main/java/com/chaozhanggui/system/cashierservice/socket/AppWebSocketServer.java index 43a1beb..ed72b89 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/socket/AppWebSocketServer.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/socket/AppWebSocketServer.java @@ -1,389 +1,359 @@ -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); +//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(); // } - } - 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); -// log.info("tableId:"+this.tableId); -// log.info("shopId:"+this.shopId); - if (userMap.containsKey(tableId)) { - Set userSet = userMap.get(tableId); - userSet.add(userId); - } - if (webSocketMap.containsKey(tableId+"-"+shopId)) { - ConcurrentHashMap userSocketMap = webSocketMap.get(tableId+"-"+shopId); - // 在放置新条目之前检查并清除同名userId的数据 - if(userSocketMap.get(userId)!=null && userSocketMap.get(userId).session!=null){ - this.session=userSocketMap.get(userId).session; - userSocketMap.put(userId,this); - } - } else { - ConcurrentHashMap userSocketMap=new ConcurrentHashMap<>(); - if(userSocketMap.get(userId)!=null && userSocketMap.get(userId).session!=null){ - this.session=userSocketMap.get(userId).session; - userSocketMap.put(userId,this); - webSocketMap.put(tableId+"-"+shopId,userSocketMap); - } - } - //这里采用责任链模式,每一个处理器对应一个前段发过来的请,这里还可以用工厂模式来生成对象 -// 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) 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; -// } +// 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); +// } // -// 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(); +// 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) { -// e.printStackTrace(); -// return null; +// log.error("用户:" + tableId + ",网络异常!!!!!!"); // } // } // -// 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; +// /** +// * 连接关闭调用的方法 +// */ +// @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/SocketSession.java b/src/main/java/com/chaozhanggui/system/cashierservice/socket/SocketSession.java index 77f6b2e..ee626f1 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/socket/SocketSession.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/socket/SocketSession.java @@ -1,14 +1,14 @@ -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 ; -} +//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 index a66a79b..bf08678 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/socket/WebSocketConfig.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/socket/WebSocketConfig.java @@ -1,27 +1,27 @@ -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 { - - } -} +//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 index 66b4d29..3aac705 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/socket/WebSocketServer.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/socket/WebSocketServer.java @@ -1,113 +1,113 @@ -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); - } - } - -} - +//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/java/com/chaozhanggui/system/cashierservice/util/TokenUtil.java b/src/main/java/com/chaozhanggui/system/cashierservice/util/TokenUtil.java index 96444b2..02007bc 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/util/TokenUtil.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/util/TokenUtil.java @@ -33,7 +33,7 @@ public class TokenUtil { * @param phone * @return */ - public static String generateToken(Integer userId,String openId,String phone,String userName) throws Exception { + public static String generateToken(Integer userId,String openId,String phone,String userName){ Map claims = new HashMap<>(1); claims.put("userId", userId); if(ObjectUtil.isNotEmpty(openId)){ @@ -114,8 +114,7 @@ public class TokenUtil { }catch (Exception e){ jsonObject.put("status","-4"); jsonObject.put("message","token解析失败了"); - log.info("token解析失败token为:{} message:{}",token,e.getMessage()); - e.printStackTrace(); + log.info("token解析失败token为:{} Exception:{}",token,e.getMessage()); } return jsonObject; } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index edc4599..23bd948 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -25,6 +25,15 @@ websocket: thread: boss: 12 work: 12 + +netty: + server: + port: 9999 + # 接收者的线程数 + parent-group-threads: 10 + # 客户端的线程数 + child-group-threads: 10 + logging: level: # web日志 diff --git a/src/main/resources/mapper/TbCashierCartMapper.xml b/src/main/resources/mapper/TbCashierCartMapper.xml index ae726ec..dc3d287 100644 --- a/src/main/resources/mapper/TbCashierCartMapper.xml +++ b/src/main/resources/mapper/TbCashierCartMapper.xml @@ -37,7 +37,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, sku_id, name, sale_price, number, total_number, refund_number, category_id, status, - type, merchant_id, shop_id, created_at, updated_at, user_id, table_id,pack_fee,trade_day,uuid,,sku_name + type, merchant_id, shop_id, created_at, updated_at, user_id, table_id,pack_fee,trade_day,uuid,sku_name + select * from tb_cashier_cart where order_id=#{orderId} diff --git a/src/main/resources/mapper/TbProductMapper.xml b/src/main/resources/mapper/TbProductMapper.xml index 45e9b7d..ac7801c 100644 --- a/src/main/resources/mapper/TbProductMapper.xml +++ b/src/main/resources/mapper/TbProductMapper.xml @@ -891,7 +891,7 @@