diff --git a/pom.xml b/pom.xml index 8c901e2..2ea4374 100644 --- a/pom.xml +++ b/pom.xml @@ -20,7 +20,11 @@ - + + com.belerweb + pinyin4j + 2.5.1 + org.apache.commons commons-lang3 @@ -56,7 +60,12 @@ com.alibaba fastjson - 1.2.9 + 1.2.83 + + + com.aliyun.oss + aliyun-sdk-oss + 3.15.1 org.projectlombok @@ -103,6 +112,18 @@ runtime + + + com.google.zxing + core + 3.5.3 + + + + com.google.zxing + javase + 3.5.3 + org.apache.commons @@ -178,6 +199,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/Shell.java b/src/main/java/com/chaozhanggui/system/cashierservice/Shell.java index 08e4839..7e62b24 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/Shell.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/Shell.java @@ -14,6 +14,7 @@ import org.springframework.context.ApplicationContext; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.web.client.RestTemplate; @@ -26,11 +27,12 @@ import java.net.Socket; @EnableScheduling @EntityScan(basePackageClasses = {Shell.class}) @MapperScan(basePackageClasses ={Shell.class} ) -@ComponentScan(basePackageClasses ={Shell.class}) +//@ComponentScan(basePackageClasses ={Shell.class}) @EnableTransactionManagement @EnableAspectJAutoProxy(proxyTargetClass = true) @Slf4j @EnableWebSocket +@EnableAsync public class Shell { private static Logger logger = LoggerFactory.getLogger(Shell.class); diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/annotation/LimitSubmit.java b/src/main/java/com/chaozhanggui/system/cashierservice/annotation/LimitSubmit.java new file mode 100644 index 0000000..c54118e --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/annotation/LimitSubmit.java @@ -0,0 +1,22 @@ +package com.chaozhanggui.system.cashierservice.annotation; + +import java.lang.annotation.*; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Inherited +public @interface LimitSubmit { + String key() ; + /** + * 默认 10s + */ + int limit() default 5; + + /** + * 请求完成后 是否一直等待 + * true则等待 + * @return + */ + boolean needAllWait() default true; +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/auth/LoginFilter.java b/src/main/java/com/chaozhanggui/system/cashierservice/auth/LoginFilter.java index 23e64c9..c2bc136 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/auth/LoginFilter.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/auth/LoginFilter.java @@ -10,6 +10,7 @@ import com.chaozhanggui.system.cashierservice.util.TokenUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import javax.servlet.*; @@ -36,11 +37,26 @@ public class LoginFilter implements Filter { // 忽略静态资源 "css/**", "js/**", + "cashierService/websocket/table",//websocket "cashierService/phoneValidateCode",//验证码 + "cashierService/tbPlatformDict",//获取菜单 "cashierService/location/**",//高德 获取行政区域 "cashierService/home/homePageUp",//首页上半 "cashierService/home",//首页 - "cashierService/login/**"//登录部分接口不校验 + "cashierService/order/testMessage",//首页 + "cashierService/common/**",//通用接口 + "cashierService/distirict/**",//首页其它接口 + +// "cashierService/login/**",//登录部分接口不校验 + "cashierService/login/wx/**",//登录部分接口不校验 + "cashierService/login/app/login",//登录部分接口不校验 + "cashierService/product/queryProduct", + "cashierService/product/queryProductSku", + "cashierService/product/productInfo", + "cashierService/notify/**",//登录部分接口不校验 + "notify/**", + "cashierService/table/**",//回调部分接口不校验 + "cashierService/pay/**" ); @Autowired @@ -62,33 +78,58 @@ public class LoginFilter implements Filter { } // 获取请求地址 String url = request.getRequestURI(); + // 不需要授权的接口直接访问的地址 if (containsUrl(NOT_LOGIN_URL, url)) { chain.doFilter(req, resp); return; } + //environment 环境标识 wx app 后续environment不可为空 String environment = request.getHeader("environment"); - //token校验目前只对app生效 - if (StringUtils.isBlank(environment) || !environment.equals("app")) { - chain.doFilter(req, resp); - return; - } // 判断用户TOKEN是否存在 String token = request.getHeader("token"); if (StringUtils.isBlank(token)) { - Result result = new Result(CodeEnum.TOKEN_EXEIST); + Result result = new Result(CodeEnum.TOKEN_EXPIRED); String jsonString = JSONObject.toJSONString(result); JSONObject jsonObject = JSONObject.parseObject(jsonString, JSONObject.class); response.getWriter().print(jsonObject); response.getWriter().flush();//流里边的缓存刷出 return; } - //获取当前登录人的用户id - String loginName = TokenUtil.parseParamFromToken(token).getString("userId"); - //获取redis中的token - String message = redisUtil.getMessage(RedisCst.ONLINE_APP_USER.concat(loginName)); + String message = ""; + String tokenKey=""; + + JSONObject jsonObject1 = TokenUtil.parseParamFromToken(token); + if (jsonObject1.containsKey("status")){ + String openId = request.getHeader("openId"); + String userId = request.getHeader("id"); + redisUtil.deleteByKey(RedisCst.ONLINE_USER.concat(openId)); + redisUtil.deleteByKey(RedisCst.ONLINE_USER.concat(userId)); + redisUtil.deleteByKey(RedisCst.ONLINE_APP_USER.concat(userId)); + Result result = new Result(CodeEnum.TOKEN_EXPIRED); + String jsonString = JSONObject.toJSONString(result); + JSONObject jsonObject = JSONObject.parseObject(jsonString, JSONObject.class); + response.getWriter().print(jsonObject); + response.getWriter().flush();//流里边的缓存刷出 + return; + } + + if(environment.equals("app")){ + //获取当前登录人的用户id + String userId = jsonObject1.getString("userId"); + tokenKey=RedisCst.ONLINE_APP_USER.concat(userId); + //获取redis中的token + }else if(environment.equals("wx")){ + //获取当前登录人的用户id + String openId = jsonObject1.getString("openId"); + if(StringUtils.isBlank(openId)){ + openId = jsonObject1.getString("userId"); + } + tokenKey=RedisCst.ONLINE_USER.concat(openId); + } + message = redisUtil.getMessage(tokenKey); if (StringUtils.isBlank(message)) { Result result = new Result(CodeEnum.TOKEN_EXPIRED); String jsonString = JSONObject.toJSONString(result); @@ -106,9 +147,19 @@ public class LoginFilter implements Filter { response.getWriter().flush();//流里边的缓存刷出 return; } + checkRenewal(tokenKey); chain.doFilter(req, resp); } + @Async + public void checkRenewal(String tokenKey) { + // 判断是否续期token,计算token的过期时间 + long time = redisUtil.getRemainingTime(tokenKey); + if(time<60*60*24*10L){ + redisUtil.setKeyExpirationTime(tokenKey,60*60*24*30L); + } + } + /** * 判断url请求是否配置在urls列表中 */ @@ -122,6 +173,9 @@ public class LoginFilter implements Filter { return true; } } else { + if (url.equals(s)) { + return true; + } if (url.equals("/" + s)) { return true; } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/config/ChangeHandler.java b/src/main/java/com/chaozhanggui/system/cashierservice/config/ChangeHandler.java deleted file mode 100644 index 969a880..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/config/ChangeHandler.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.chaozhanggui.system.cashierservice.config; - -import com.alibaba.fastjson.JSONObject; -import com.chaozhanggui.system.cashierservice.socket.AppWebSocketServer; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; - -//处理前端改变购物车的行为,并记录 -public class ChangeHandler extends Handler { - - @Override - public void handleRequest(ConcurrentHashMap> webSocketMap, - JSONObject jsonObject, ConcurrentHashMap> recordMap, - AppWebSocketServer webSocke) throws IOException { - - if (jsonObject.containsKey("change")) { - ArrayList jsonObjects = new ArrayList<>(); - jsonObjects.add(jsonObject); -// producerMq.syncShopCar(jsonObjects); - //记录每一次购物车变化的记录 - List objects = recordMap.get(webSocke.getTableId()); - objects.add(jsonObject); - } else { - // 无法处理,传递给下一个处理器 - if (nextHandler != null) { - nextHandler.handleRequest(webSocketMap,jsonObject,recordMap,webSocke); - } - } - } -} - diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/config/ClearHandler.java b/src/main/java/com/chaozhanggui/system/cashierservice/config/ClearHandler.java deleted file mode 100644 index c5b8981..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/config/ClearHandler.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.chaozhanggui.system.cashierservice.config; - -import com.alibaba.fastjson.JSONObject; -import com.chaozhanggui.system.cashierservice.socket.AppWebSocketServer; -import org.apache.commons.lang3.StringUtils; - -import java.io.IOException; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; - -//处理前端订单已完成,把订单标志位置为false -public class ClearHandler extends Handler{ - - @Override - public void handleRequest(ConcurrentHashMap> webSocketMap, - JSONObject jsonObject, ConcurrentHashMap> recordMap, - AppWebSocketServer webSocke) throws IOException { - if (jsonObject.containsKey("clear")) { - if (StringUtils.isNotBlank(webSocke.getTableId()) && webSocketMap.containsKey(webSocke.getTableId())) { - List serverList = webSocketMap.get(webSocke.getTableId()); - //遍历所有对象,把订单都改为未提交,为了下一次点餐 - serverList.forEach(m -> m.getCreateOrder().set(false)); - - } - } else { - // 无法处理,传递给下一个处理器 - if (nextHandler != null) { - nextHandler.handleRequest(webSocketMap,jsonObject,recordMap,webSocke); - } - } - } -} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/config/CorsFilter.java b/src/main/java/com/chaozhanggui/system/cashierservice/config/CorsFilter.java index 31e33e6..6690f7b 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/config/CorsFilter.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/config/CorsFilter.java @@ -28,7 +28,7 @@ public class CorsFilter implements Filter { response.setHeader("Access-Control-Allow-Origin", curOrigin == null ? "true" : curOrigin); response.setHeader("Access-Control-Allow-Methods", "*"); response.setHeader("Access-Control-Max-Age", "3600"); - response.setHeader("Access-Control-Allow-Headers", "x-requested-with,signature"); + response.setHeader("Access-Control-Allow-Headers", "environment,openId,type,version,token"); response.setHeader("Access-Control-Allow-Credentials", "true"); chain.doFilter(req, resp); } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/config/CreateOrderHandler.java b/src/main/java/com/chaozhanggui/system/cashierservice/config/CreateOrderHandler.java deleted file mode 100644 index ef2c04c..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/config/CreateOrderHandler.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.chaozhanggui.system.cashierservice.config; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.chaozhanggui.system.cashierservice.socket.AppWebSocketServer; -import org.apache.commons.lang3.StringUtils; - -import java.io.IOException; -import java.math.BigDecimal; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; - -//处理前端创建订单 -public class CreateOrderHandler extends Handler{ - - @Override - public void handleRequest(ConcurrentHashMap> webSocketMap, - JSONObject jsonObject, ConcurrentHashMap> recordMap, - AppWebSocketServer webSocke) throws IOException { - - - if (jsonObject.containsKey("createOrdwebSockeer")) { - if (StringUtils.isNotBlank(webSocke.getTableId()) && webSocketMap.containsKey(webSocke.getTableId())) { - List serverList = webSocketMap.get(webSocke.getTableId()); - //有一个为true就说明已经有订单了 - if (serverList.stream().anyMatch(m -> m.getCreateOrder().get())) { - webSocke.sendMessage("已有人提交订单,请稍后"); - return; - } - } - synchronized (webSocke) { - if (StringUtils.isNotBlank(webSocke.getTableId()) && webSocketMap.containsKey(webSocke.getTableId())) { - List serverList = webSocketMap.get(webSocke.getTableId()); - //有一个为true就说明已经有订单了 - if (serverList.stream().anyMatch(m -> m.getCreateOrder().get())) { - webSocke.sendMessage("已有人提交订单,请稍后"); - return; - } - - BigDecimal amount = new BigDecimal((Integer) jsonObject.get("amount")); - JSONArray shopCarList = jsonObject.getJSONArray("shopCarList"); - String remark = jsonObject.get("remark").toString(); - - -// List list=shopCarList.toJavaList(ShopListDto.class); -// //TODO 加个拦截加个shopid,抛出异常,前端展示 -// setShopId(list.get(0).getShopId()); -// try { -// Result order = orderFeign.createOrder(new CreateOrderDto(Long.parseLong(webSocke.getTableId()), amount, list, remark)); -// if (order.getCode() == 200){ -// //通知清空购物车 -// AppSendInfo("订单提交成功", webSocke.getTableId()); -// //清空本地的购物记录 -// recordMap.get(webSocke.getTableId()).clear(); -// webSocke.getCreateOrder().set(true); -// }else { -// AppSendInfo("订单提交失败",webSocke.getTableId()); -// } -// -// -// }catch (Exception e){ -// e.printStackTrace(); -// AppSendInfo("订单提交失败",webSocke.getTableId()); -// } - - - - } - } - - } else { - // 无法处理,传递给下一个处理器 - if (nextHandler != null) { - nextHandler.handleRequest(webSocketMap,jsonObject,recordMap,webSocke); - } - } - } -} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/config/Handler.java b/src/main/java/com/chaozhanggui/system/cashierservice/config/Handler.java deleted file mode 100644 index 9529bc3..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/config/Handler.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.chaozhanggui.system.cashierservice.config; - -import com.alibaba.fastjson.JSONObject; -import com.chaozhanggui.system.cashierservice.socket.AppWebSocketServer; - -import java.io.IOException; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; - -public abstract class Handler { - protected Handler nextHandler; - - - public Handler addNextHandler(Handler handler) { - this.nextHandler = handler; - return handler; - } - - - - - public abstract void handleRequest(ConcurrentHashMap> webSocketMap, - JSONObject jsonObject, ConcurrentHashMap> recordMap, - AppWebSocketServer webSocke) throws IOException; -} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/config/OtherHandler.java b/src/main/java/com/chaozhanggui/system/cashierservice/config/OtherHandler.java deleted file mode 100644 index 8fd78ee..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/config/OtherHandler.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.chaozhanggui.system.cashierservice.config; - -import com.alibaba.fastjson.JSONObject; -import com.chaozhanggui.system.cashierservice.socket.AppWebSocketServer; -import org.apache.commons.lang3.StringUtils; - -import java.io.IOException; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; - -import static com.chaozhanggui.system.cashierservice.socket.AppWebSocketServer.AppSendInfo; - - -//兜底处理器 -public class OtherHandler extends Handler{ - @Override - public void handleRequest(ConcurrentHashMap> webSocketMap, - JSONObject jsonObject, - ConcurrentHashMap> recordMap, - AppWebSocketServer webSocke) throws IOException { - - //传送给对应tableId用户的websocket - if (StringUtils.isNotBlank(webSocke.getTableId()) && webSocketMap.containsKey(webSocke.getTableId())) { - AppSendInfo("1", webSocke.getTableId(),false); - - } else { - System.out.println("请求的tableId:" + webSocke.getTableId() + "不在该服务器上"); - } - } -} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/config/SyncHandler.java b/src/main/java/com/chaozhanggui/system/cashierservice/config/SyncHandler.java deleted file mode 100644 index 44a0298..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/config/SyncHandler.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.chaozhanggui.system.cashierservice.config; - -import com.alibaba.fastjson.JSONObject; -import com.chaozhanggui.system.cashierservice.socket.AppWebSocketServer; -import org.apache.commons.lang3.StringUtils; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; - -//处理前端初次扫码同步购物车 -public class SyncHandler extends Handler { - - @Override - public void handleRequest(ConcurrentHashMap> webSocketMap, - JSONObject jsonObject, ConcurrentHashMap> recordMap, - AppWebSocketServer webSocke) throws IOException { - if (jsonObject.containsKey("sync")) { - //这个是判断是否有这个桌号,也就是 是否有人点过餐 - - List recordList = recordMap.get(webSocke.getTableId()); - //指定发送对象 - if (StringUtils.isNotBlank(webSocke.getTableId()) && webSocketMap.containsKey(webSocke.getTableId()) && recordList != null) { - List serverList = webSocketMap.get(webSocke.getTableId()); - for (AppWebSocketServer server : serverList) { - if (server.getSync().get()) { - server.sendMessage(recordList); - } - - } - } else { - ArrayList objects = new ArrayList<>(); - recordMap.put(webSocke.getTableId(), objects); - } - webSocke.getSync().set(!webSocke.getSync().get()); - - } else { - // 无法处理,传递给下一个处理器 - if (nextHandler != null) { - nextHandler.handleRequest(webSocketMap, jsonObject, recordMap, webSocke); - } - } - } -} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/config/WebSocketCustomEncoding.java b/src/main/java/com/chaozhanggui/system/cashierservice/config/WebSocketCustomEncoding.java deleted file mode 100644 index 33a7658..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/config/WebSocketCustomEncoding.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.chaozhanggui.system.cashierservice.config; - - -import com.alibaba.fastjson.JSON; - -import javax.websocket.Encoder; -import javax.websocket.EndpointConfig; - -/** - * 为了websocket发送对象 - */ - -public class WebSocketCustomEncoding implements Encoder.Text { -// public String encode(Object vo) 这个就是指定发送的类型 - @Override - public String encode(Object vo) { - assert vo!=null; - return JSON.toJSONString(vo); - } - - - @Override - public void init(EndpointConfig endpointConfig) { - - } - @Override - public void destroy() { - - } - -} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/controller/CloudPrinterController.java b/src/main/java/com/chaozhanggui/system/cashierservice/controller/CloudPrinterController.java index 529ff58..1a33f05 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/controller/CloudPrinterController.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/controller/CloudPrinterController.java @@ -7,6 +7,9 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; +/** + * @author admin + */ @CrossOrigin(origins = "*") @RestController @Slf4j diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/controller/CommonController.java b/src/main/java/com/chaozhanggui/system/cashierservice/controller/CommonController.java new file mode 100644 index 0000000..ba65f22 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/controller/CommonController.java @@ -0,0 +1,201 @@ +package com.chaozhanggui.system.cashierservice.controller; + +import com.chaozhanggui.system.cashierservice.dao.TbPlatformDictMapper; +import com.chaozhanggui.system.cashierservice.entity.TbPlatformDict; +import com.chaozhanggui.system.cashierservice.entity.vo.DistrictVo; +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.FileService; +import com.chaozhanggui.system.cashierservice.sign.CodeEnum; +import com.chaozhanggui.system.cashierservice.sign.Result; +import com.chaozhanggui.system.cashierservice.util.LocationUtils; +import com.chaozhanggui.system.cashierservice.util.StringUtil; +import com.chaozhanggui.system.cashierservice.util.ValidateCodeUtil; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.RequiredArgsConstructor; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.annotation.Resource; +import java.util.Collections; +import java.util.List; + +/** + * 通用接口 + * + * @author lyf + */ +@RestController +@RequestMapping +@RequiredArgsConstructor +public class CommonController { + + private final ValidateCodeUtil validateCodeUtil; + + @Autowired + private RedisUtil redisUtil; + @Resource + private TbPlatformDictMapper platformDictMapper; + @Resource + private FileService fileService; + /** + * 一分钟 + */ + protected static final long ONE_MINUTE = 1800; + + /** + * 发送短信验证码 + * + * @param phone + * @return + */ + @GetMapping("/phoneValidateCode") + public Result phoneValidateCode(@RequestParam String phone) { + if (StringUtils.isBlank(phone)) { + return Result.fail("手机号不可为空!"); + } + // 检查手机号格式是否正确 + if (!isValidPhoneNumber(phone)) { + return Result.fail("手机号格式不正确!"); + } + // 检查手机号请求次数是否超出限制 + Result isOk = isRequestLimit(phone); + if (!isOk.getCode().equals("0")) { + return isOk; + } + String random = StringUtil.random(6); + validateCodeUtil.requestValidateCodeAli(phone, random); + //存入缓存 + try { + redisUtil.saveMessage(phone, random, 60L); + } catch (Exception e) { + throw new MsgException("验证码发送失败"); + } + return Result.success(CodeEnum.SUCCESS); + } + + /** + * 获取菜单 + */ + @GetMapping("/tbPlatformDict") + public Result getPlatformDict(@RequestParam String type, @RequestHeader String environment) { + List carouselList = platformDictMapper.queryAllByType(type, environment); + return Result.success(CodeEnum.SUCCESS, carouselList); + } + + /** + * 查询省市 + */ + @GetMapping("location/districtAll") + public Result districtAll() throws JsonProcessingException { + ObjectMapper mapper = new ObjectMapper(); + if(redisUtil.exists("DISTRICTALL")){ + String str=redisUtil.getMessage("DISTRICTALL"); + JsonNode jsonNode = mapper.readTree(str); + return Result.success(CodeEnum.SUCCESS, jsonNode); + }else { + String districtJson = LocationUtils.district("100000","2");//中国 + JsonNode jsonNode = mapper.readTree(districtJson); + JsonNode districts = jsonNode.get("districts"); + List cityInfoList = mapper.readValue(districts.get(0).get("districts").toString(), mapper.getTypeFactory().constructCollectionType(List.class, DistrictVo.class)); + Collections.sort(cityInfoList, (o1, o2) -> o1.getNameAsPY().compareTo(o2.getNameAsPY())); + redisUtil.saveMessage("DISTRICTALL",mapper.writeValueAsString(cityInfoList),7*24*3600L); + return Result.success(CodeEnum.SUCCESS, cityInfoList); + } + } + + /** + * 行政区域查询 + * + * @param keywords citycode市、adcode区 + * @return + */ + @GetMapping("location/district") + public Result district(String keywords) throws JsonProcessingException { + String districtJson = LocationUtils.district(keywords,null); + ObjectMapper mapper = new ObjectMapper(); + JsonNode jsonNode = mapper.readTree(districtJson); + JsonNode districts = jsonNode.get("districts"); + String text = districts.toString(); + List cityInfoList = mapper.readValue(text, mapper.getTypeFactory().constructCollectionType(List.class, DistrictVo.class)); + DistrictVo allCity = new DistrictVo(); + allCity.setName("全城"); + cityInfoList.add(0, allCity); + return Result.success(CodeEnum.SUCCESS, cityInfoList); + } + + @GetMapping("location/geocode") + public Result geocode(@RequestParam String lat, @RequestParam String lng) { + String address="108.939645,34.343207"; + if (!StringUtils.isBlank(lat) && !StringUtils.isBlank(lng)) { + address=lng + "," + lat; + } + return Result.success(CodeEnum.SUCCESS, LocationUtils.geocode(address)); + } + + + @GetMapping("location/getGPSByIp") + public Result getGPSByIp(String ip) throws JsonProcessingException { + String gpsInfo = LocationUtils.getGPSByIp(ip); + ObjectMapper mapper = new ObjectMapper(); + JsonNode jsonNode = mapper.readTree(gpsInfo); + return Result.success(CodeEnum.SUCCESS, jsonNode); + } + + @RequestMapping("common/upload") + public Result upload(MultipartFile file) throws Exception { + return new Result(CodeEnum.SUCCESS, fileService.uploadFile(file)); + } + + // 检查手机号格式是否正确的方法 + private boolean isValidPhoneNumber(String phone) { + return phone.matches("^1[3-9]\\d{9}$"); + } + + // 检查手机号请求次数是否超出限制的方法 + public Result isRequestLimit(String phone) { + Object count = redisUtil.getMessage(RedisCst.PHONE_LIMIT + phone); + if (count != null && Integer.valueOf(count.toString()) >= 5) { + return Result.fail("请求次数超出限制!,请半小时后重试"); + } + long time = redisUtil.getRemainingTime(phone); + if (time > 0) { + return Result.fail("请" + time + "秒后重试"); + } + refreshPhoneLimit(phone,count != null); + return Result.success(CodeEnum.SUCCESS); + } + + // 从 Redis 中获取手机号码的请求次数的方法 + @Async + public void refreshPhoneLimit(String phone,boolean isExist) { + if (isExist) { + phoneRequestrinc(RedisCst.PHONE_LIMIT + phone); + } else { + phoneRequestset(RedisCst.PHONE_LIMIT + phone); + } + } + + /** + * 存储手机号和请求次数的对应关系 时间 半小时 + */ + public void phoneRequestset(String key) { + // 使用 Hash 结构存储手机号和请求次数的对应关系 时间 半小时 + redisUtil.saveMessage(key, "1", 60*30L); + } + + + /** + * 将手机号码的请求次数加1 + */ + public void phoneRequestrinc(String key) { + // 将手机号码的请求次数加1 + redisUtil.getIncrNum(key, "2"); + } +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/controller/GroupOrderInfoController.java b/src/main/java/com/chaozhanggui/system/cashierservice/controller/GroupOrderInfoController.java new file mode 100644 index 0000000..bf1d924 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/controller/GroupOrderInfoController.java @@ -0,0 +1,91 @@ +package com.chaozhanggui.system.cashierservice.controller; + +import com.chaozhanggui.system.cashierservice.entity.TbGroupOrderInfo; +import com.chaozhanggui.system.cashierservice.entity.dto.CreateGroupOrderDto; +import com.chaozhanggui.system.cashierservice.entity.dto.GroupOrderDto; +import com.chaozhanggui.system.cashierservice.service.GroupOrderCouponService; +import com.chaozhanggui.system.cashierservice.service.GroupOrderInfoService; +import com.chaozhanggui.system.cashierservice.sign.CodeEnum; +import com.chaozhanggui.system.cashierservice.sign.Result; +import com.chaozhanggui.system.cashierservice.util.TokenUtil; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; + +/** + * 团购卷订单 + * + * @author ww + * @since 2024-04-27 16:15:08 + */ +@RestController +@RequestMapping("groupOrderInfo") +public class GroupOrderInfoController { + + @Resource + private GroupOrderInfoService tbGroupOrderInfoService; + + @Resource + private GroupOrderCouponService orderCouponService; + + /** + * 分页查询 + * + * @param param 筛选条件 + * @return 查询结果 + */ + @RequestMapping("list") + public Result queryByPage(@RequestHeader String token, GroupOrderDto param) { + String userId = TokenUtil.parseParamFromToken(token).getString("userId"); + param.setUserId(userId); + return tbGroupOrderInfoService.queryByPage(param); + } + + /** + * 通过id查询卷码 + */ + @RequestMapping("getCoupon") + public Result queryCouponById(Integer id) { + return Result.success(CodeEnum.SUCCESS,orderCouponService.queryNoRefundByOrderId(id)); + } + + /** + * 团购卷 下单 + * @param token + * @param param + * @return + */ + @PostMapping("/creatGroupOrder") + public Result createOrder(@RequestHeader String token,@RequestBody CreateGroupOrderDto param){ + String userId = TokenUtil.parseParamFromToken(token).getString("userId"); + String phone = TokenUtil.parseParamFromToken(token).getString("phone"); + param.setUserId(Integer.valueOf(userId)); + param.setPhone(phone); + return tbGroupOrderInfoService.insert(param); + } + + + /** + * 通过主键查询单条数据 + * + * @param id 主键 + * @return 单条数据 + */ + @RequestMapping("get") + public Result queryById(Integer id,String lng,String lat) { + return tbGroupOrderInfoService.queryById(id,lng,lat); + } + + + /** + * 编辑数据 + * + * @param tbGroupOrderInfo 实体 + * @return 编辑结果 + */ + @RequestMapping("edit") + public Result edit(TbGroupOrderInfo tbGroupOrderInfo) { + return tbGroupOrderInfoService.update(tbGroupOrderInfo); + } +} + diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/controller/HomeController.java b/src/main/java/com/chaozhanggui/system/cashierservice/controller/HomeController.java index 0a26bbe..bf96467 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/controller/HomeController.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/controller/HomeController.java @@ -20,12 +20,13 @@ public class HomeController { @Resource private HomePageService homePageService; - @PostMapping - public Result homePage(@RequestBody HomeDto homeDto,@RequestHeader("environment") String environmen)throws Exception{ - return homePageService.homePage(homeDto, environmen); - } @PostMapping("/homePageUp") public Result homePageUp(@RequestHeader("environment") String environment){ return homePageService.homePageUp(environment); } + + @PostMapping + public Result homePage(@RequestBody HomeDto homeDto)throws Exception{ + return homePageService.proList(homeDto); + } } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/controller/HomeDistrictController.java b/src/main/java/com/chaozhanggui/system/cashierservice/controller/HomeDistrictController.java new file mode 100644 index 0000000..8ad91a1 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/controller/HomeDistrictController.java @@ -0,0 +1,61 @@ +package com.chaozhanggui.system.cashierservice.controller; + +import com.chaozhanggui.system.cashierservice.entity.dto.ComShopDto; +import com.chaozhanggui.system.cashierservice.entity.dto.HomeBaseDto; +import com.chaozhanggui.system.cashierservice.entity.dto.HomeDto; +import com.chaozhanggui.system.cashierservice.service.HomeDistrictService; +import com.chaozhanggui.system.cashierservice.sign.Result; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import javax.annotation.Resource; + +/** + * 首页其它接口 + */ +@RestController +@RequestMapping("/distirict") +@RequiredArgsConstructor +public class HomeDistrictController { + + @Resource + private HomeDistrictService districtService; + + /** + * 顶部图/菜单 + */ + @RequestMapping("/topCommon") + public Result topCommon(HomeDto param,@RequestHeader("environment") String environment){ + return districtService.topCommon(param,environment); + } + + /** + * 预约到店(店铺列表) + */ + @RequestMapping("/subShopList") + public Result subShopList(HomeBaseDto param){ + return districtService.queryShopListByPage(param); + } + + + /** + * 品类 + * + * 今日上新 + * 热榜推荐 + * 咖啡饮品 + */ + @RequestMapping("/productCate") + public Result productCate(HomeDto param){ + return districtService.proList(param); + } + + /** + * 通用门店 + */ + @RequestMapping("/comShopList") + public Result comShopList(ComShopDto param){ + return districtService.queryComShopList(param); + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/controller/LocationController.java b/src/main/java/com/chaozhanggui/system/cashierservice/controller/LocationController.java deleted file mode 100644 index 0f4be0a..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/controller/LocationController.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.chaozhanggui.system.cashierservice.controller; - -import com.chaozhanggui.system.cashierservice.sign.CodeEnum; -import com.chaozhanggui.system.cashierservice.sign.Result; -import com.chaozhanggui.system.cashierservice.util.LocationUtils; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import lombok.extern.slf4j.Slf4j; -import org.springframework.web.bind.annotation.*; - -@CrossOrigin(origins = "*") -@RestController -@Slf4j -@RequestMapping("/location") -public class LocationController { - - - /** - * 行政区域查询 - * - * @param keywords citycode市、adcode区 - * @return - */ - @GetMapping("/district") - public Result createOrder(String keywords) throws JsonProcessingException { - String district = LocationUtils.district(keywords); - ObjectMapper mapper = new ObjectMapper(); - // 将 JSON 字符串解析为 JsonNode 对象 - JsonNode jsonNode = mapper.readTree(district); - JsonNode districts = jsonNode.get("districts"); - - - return Result.success(CodeEnum.SUCCESS, districts); - } -} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/controller/LoginContoller.java b/src/main/java/com/chaozhanggui/system/cashierservice/controller/LoginContoller.java index 1e669b3..247a8ce 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/controller/LoginContoller.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/controller/LoginContoller.java @@ -6,18 +6,17 @@ import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.chaozhanggui.system.cashierservice.dao.TbMerchantAccountMapper; import com.chaozhanggui.system.cashierservice.entity.TbMerchantAccount; +import com.chaozhanggui.system.cashierservice.entity.TbUserInfo; import com.chaozhanggui.system.cashierservice.entity.dto.AuthUserDto; import com.chaozhanggui.system.cashierservice.entity.dto.OnlineUserDto; +import com.chaozhanggui.system.cashierservice.entity.dto.UserPassDto; import com.chaozhanggui.system.cashierservice.redis.RedisCst; import com.chaozhanggui.system.cashierservice.redis.RedisUtil; import com.chaozhanggui.system.cashierservice.service.LoginService; import com.chaozhanggui.system.cashierservice.service.OnlineUserService; import com.chaozhanggui.system.cashierservice.sign.CodeEnum; import com.chaozhanggui.system.cashierservice.sign.Result; -import com.chaozhanggui.system.cashierservice.util.IpUtil; -import com.chaozhanggui.system.cashierservice.util.MD5Utils; -import com.chaozhanggui.system.cashierservice.util.StringUtil; -import com.chaozhanggui.system.cashierservice.util.TokenUtil; +import com.chaozhanggui.system.cashierservice.util.*; import com.chaozhanggui.system.cashierservice.wxUtil.WechatUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.digest.DigestUtils; @@ -61,7 +60,7 @@ public class LoginContoller { RedisUtil redisUtil; - @RequestMapping("/wx/business/login") +// @RequestMapping("/wx/business/login") public Result wxBusinessLogin(@RequestParam(value = "code", required = false) String code, @RequestParam(value = "rawData", required = false) String rawData, @RequestParam(value = "signature", required = false) String signature @@ -89,33 +88,28 @@ public class LoginContoller { } - + /** + * 小程序登录 + * + * @param request + * @param map + * @return + */ @RequestMapping("/wx/custom/login") public Result wxCustomLogin(HttpServletRequest request, @RequestBody Map map // , // @RequestParam(value = "rawData", required = false) String rawData, // @RequestParam(value = "signature", required = false) String signature ) { - - if (ObjectUtil.isNull(map) || ObjectUtil.isEmpty(map) || !map.containsKey("code") || ObjectUtil.isEmpty(map.get("code"))) { Result.fail("code不能为空"); } - String code = map.get("code").toString(); - - String qrCode = map.get("qrCode"); - String rawData = map.get("rawData"); - String signature = map.get("signature"); - String encryptedData = map.get("encryptedData"); - String ivStr = map.get("iv"); - - String phone = map.get("phone"); - +// String phone = map.get("phone"); // 用户非敏感信息:rawData // 签名:signature JSONObject rawDataJson = JSON.parseObject(rawData); @@ -131,12 +125,19 @@ public class LoginContoller { if (!signature.equals(signature2)) { return Result.fail("签名校验失败"); } - + String phone = ""; + try{ + String data = WxMaCryptUtils.decrypt(sessionKey, encryptedData, ivStr); + if (ObjectUtil.isNotEmpty(data) && JSONObject.parseObject(data).containsKey("phoneNumber")) { + phone =JSONObject.parseObject(data).get("phoneNumber").toString(); + } + }catch (Exception e){ + log.info("登录传参:获取手机号失败{}",e.getMessage()); + } String nickName = rawDataJson.getString("nickName"); String avatarUrl = rawDataJson.getString("avatarUrl"); - try { - return loginService.wxCustomLogin(openid, avatarUrl, nickName, phone, qrCode, IpUtil.getIpAddr(request)); + return loginService.wxCustomLogin(openid, avatarUrl, nickName, phone, IpUtil.getIpAddr(request)); } catch (Exception e) { e.printStackTrace(); } @@ -146,7 +147,13 @@ public class LoginContoller { } - @RequestMapping("getPhoneNumber") + /** + * 小程序获取手机号 + * + * @param map + * @return + */ +// @RequestMapping("getPhoneNumber") public Result getPhoneNumber(@RequestBody Map map) { if (ObjectUtil.isNull(map) || ObjectUtil.isEmpty(map) || !map.containsKey("code") || ObjectUtil.isEmpty(map.get("code"))) { @@ -157,19 +164,24 @@ public class LoginContoller { String encryptedData = map.get("encryptedData"); String ivStr = map.get("iv"); - + if (StringUtils.isBlank(encryptedData) || StringUtils.isBlank(ivStr)) { + return Result.fail("请授权后使用"); + } JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(code, customAppId, customSecrete); // 3.接收微信接口服务 获取返回的参数 String openid = SessionKeyOpenId.getString("openid"); String sessionKey = SessionKeyOpenId.getString("session_key"); - String data = WxMaCryptUtils.decrypt(sessionKey, encryptedData, ivStr); - if (ObjectUtil.isNotEmpty(data) && JSONObject.parseObject(data).containsKey("phoneNumber")) { - return Result.success(CodeEnum.SUCCESS, JSONObject.parseObject(data).get("phoneNumber")); + try { + if (ObjectUtil.isNotEmpty(data) && JSONObject.parseObject(data).containsKey("phoneNumber")) { + log.info("登录传参 获取手机号成功 sessionKey:{}\n encryptedData:{} \nivStr:{} \n data:{},",sessionKey,encryptedData,ivStr,JSONObject.parseObject(data).get("phoneNumber")); + return Result.success(CodeEnum.SUCCESS, JSONObject.parseObject(data).get("phoneNumber")); + } + } catch (Exception e){ + log.info("登录传参 获取手机号失败 sessionKey:{}\n encryptedData:{} \nivStr:{} \n data:{},",sessionKey,encryptedData,ivStr,data); } - return Result.fail("获取手机号失败"); - + return Result.fail("获取手机号失败,请重试!"); } @Resource @@ -191,6 +203,7 @@ public class LoginContoller { //生成token String token = StringUtil.genRandomNum(6) + StringUtil.getBillno() + StringUtil.genRandomNum(6); + //存入redis OnlineUserDto jwtUserDto = onlineUserService.save(merchantAccount.getName(), merchantAccount.getAccount(), Integer.valueOf(merchantAccount.getShopId()), token, merchantAccount.getStatus()); @@ -211,17 +224,71 @@ public class LoginContoller { * @param id * @return */ - @RequestMapping("createCardNo") - public Result createCardNo(@RequestHeader("openId") String openId, @RequestHeader("token") String token, @RequestHeader("id") String id) { - return loginService.createCardNo(id, openId); + @GetMapping("createCardNo") + public Result createCardNo(@RequestHeader("openId") String openId, @RequestHeader("token") String token, @RequestHeader("id") String id, + @RequestParam("shopId") String shopId + ) { + return loginService.createCardNo(id, openId,shopId); } - @GetMapping("/wx/userInfo") - public Result userInfo(@RequestParam("userId") Integer userId, @RequestParam("shopId") String shopId) { - return loginService.userInfo(userId, shopId); + @GetMapping("/userInfo") + public Result userInfo(@RequestParam("userId") Integer userId) { + return loginService.userInfo(userId); } + /** + * 更新用户信息 + * @param token + * @param userInfo + * @return + */ + @PostMapping("/upUserInfo") + public Result userInfo(@RequestHeader String token, @RequestBody TbUserInfo userInfo) { + String userId = TokenUtil.parseParamFromToken(token).getString("userId"); + userInfo.setId(Integer.valueOf(userId)); + userInfo.setUpdatedAt(System.currentTimeMillis()); + return loginService.upUserInfo(userInfo); + } + @PostMapping(value = "/upPass") + public Result upPass(@RequestHeader String token,@RequestBody UserPassDto passVo){ + String userId = TokenUtil.parseParamFromToken(token).getString("userId"); + String newPass = MD5Utils.MD5Encode(passVo.getNewPass(), "utf-8"); + if (ObjectUtil.isNull(passVo.getCode())) { + String oldPass = MD5Utils.MD5Encode(passVo.getOldPass(), "utf-8"); + return loginService.upPass(userId,oldPass, newPass); + } else { + boolean tf = loginService.validate(passVo.getCode(), passVo.getPhone()); + if (tf) { + TbUserInfo userInfo=new TbUserInfo(); + userInfo.setId(Integer.valueOf(userId)); + userInfo.setPassword(newPass); + return loginService.upUserInfo(userInfo); + } else { + return Result.fail("验证码输入有误"); + } + } + } + + @PostMapping(value = "modityPass") + public Result modityPass(@RequestHeader String token,@RequestBody UserPassDto passVo){ + String userId = TokenUtil.parseParamFromToken(token).getString("userId"); + String newPass = MD5Utils.MD5Encode(passVo.getNewPass(), "utf-8"); + if (ObjectUtil.isNull(passVo.getCode())) { + String oldPass = MD5Utils.MD5Encode(passVo.getOldPass(), "utf-8"); + return loginService.upPass(userId,oldPass, newPass); + } else { + boolean tf = loginService.validate(passVo.getCode(), passVo.getPhone()); + if (tf) { + TbUserInfo userInfo=new TbUserInfo(); + userInfo.setId(Integer.valueOf(userId)); + userInfo.setPassword(newPass); + return loginService.upUserInfo(userInfo); + } else { + return Result.fail("验证码输入有误"); + } + } + } /** * 用户注册 * phone 手机号 @@ -244,40 +311,82 @@ public class LoginContoller { /** * App登录用户端的请求接口 登录即注册 * 查看 {@link com.chaozhanggui.system.cashierservice.entity.dto.AuthUserDto} - * username 手机号 - * password 密码登录时使用 - * code 验证码登录时使用 + * username 手机号 + * password 密码登录时使用 + * code 验证码登录时使用 + * * @return */ @PostMapping("/app/login") public Result applogin(@RequestBody AuthUserDto authUserDto) { + boolean tf = false; + JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(authUserDto.getOpencode(), customAppId, customSecrete); + // 3.接收微信接口服务 获取返回的参数 + String openid = SessionKeyOpenId.getString("openid"); if (ObjectUtil.isNull(authUserDto.getCode())) { - if(StringUtils.isBlank(authUserDto.getPassword())){ + if (StringUtils.isBlank(authUserDto.getPassword())) { return Result.fail("请输入密码,或使用验证码登录"); } //验证密码 String mdPasswordString = MD5Utils.MD5Encode(authUserDto.getPassword(), "utf-8"); - return loginService.appLogin(authUserDto.getUsername(), mdPasswordString); + return loginService.appLogin(authUserDto.getUsername(),openid, mdPasswordString); } else { - boolean tf = loginService.validate(authUserDto.getCode(), authUserDto.getUsername()); +// tf = true; + tf = loginService.validate(authUserDto.getCode(), authUserDto.getUsername()); if (tf) { - return loginService.appLogin(authUserDto.getUsername(), null); + return loginService.appLogin(authUserDto.getUsername(),openid, null); } else { return Result.fail("验证码输入有误"); } } } - - //退出登录的接口 + /** + * APP退出登录 + * + * @return + * @header token + */ @PostMapping("/loginOut") - public Result loginOut(HttpServletRequest request) { - String token = request.getHeader("token"); + public Result loginOut(@RequestHeader String token, @RequestHeader String environment, HttpServletRequest request) { //获取当前登录人的账号 String userId = TokenUtil.parseParamFromToken(token).getString("userId"); - redisUtil.deleteByKey(RedisCst.ONLINE_APP_USER.concat(userId)); + if (environment.equals("wx")) { + String openId = request.getHeader("openId"); + redisUtil.deleteByKey(RedisCst.ONLINE_USER.concat(openId)); + } else if (environment.equals("app")) { + redisUtil.deleteByKey(RedisCst.ONLINE_APP_USER.concat(userId)); + } return Result.success(CodeEnum.SUCCESS); } + /** + * 重置资金密码 + * @param token + * @param map + * @return + */ + @RequestMapping("resetPwd") + public Result resetPwd(@RequestHeader String token,@RequestBody Map map){ + + String userId = TokenUtil.parseParamFromToken(token).getString("userId"); + return loginService.resetPwd(userId,map); + + } + + + /** + * 修改密码 + * @param token + * @param map + * @return + */ + @RequestMapping("mpdifyPwd") + public Result mpdifyPwd(@RequestHeader String token,@RequestBody Map map){ + String userId = TokenUtil.parseParamFromToken(token).getString("userId"); + return loginService.modifyPwd(userId,map); + } + + } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/controller/NotifyController.java b/src/main/java/com/chaozhanggui/system/cashierservice/controller/NotifyController.java index 01ba8dc..4b33f13 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/controller/NotifyController.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/controller/NotifyController.java @@ -6,15 +6,15 @@ import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.chaozhanggui.system.cashierservice.interceptor.RequestWrapper; import com.chaozhanggui.system.cashierservice.service.PayService; +import com.chaozhanggui.system.cashierservice.util.DateUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.CrossOrigin; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; +import java.util.Date; import java.util.Map; +import java.util.Random; @CrossOrigin(origins = "*") @RestController @@ -30,21 +30,47 @@ public class NotifyController { @RequestMapping("memberInCallBack") - public String memberInCallBack(HttpServletRequest request){ + public String memberInCallBack(HttpServletRequest request) { - Map map= getParameterMap(request); - log.info("回调返回信息:{}",JSONUtil.toJsonStr(map)); - if(ObjectUtil.isNotEmpty(map)&&map.containsKey("code")&&"200".equals(map.get("code")+"")){ - JSONObject object=JSONUtil.parseObj(map.get("data")); - if(ObjectUtil.isNotEmpty(object)&&object.containsKey("status")&&"1".equals(object.getStr("status"))){ - String orderNo=object.getStr("orderNumber"); - String channelTradeNo=object.getStr("channelTradeNo"); - return payService.minsuccess(orderNo,channelTradeNo); + Map map = getParameterMap(request); + log.info("回调返回信息:{}", JSONUtil.toJsonStr(map)); + if (ObjectUtil.isNotEmpty(map) && map.containsKey("code") && "200".equals(map.get("code") + "")) { + JSONObject object = JSONUtil.parseObj(map.get("data")); + if (ObjectUtil.isNotEmpty(object) && object.containsKey("status") && "1".equals(object.getStr("status"))) { + String orderNo = object.getStr("orderNumber"); + String channelTradeNo = object.getStr("channelTradeNo"); + return payService.minsuccess(orderNo, channelTradeNo); } } return null; } + @RequestMapping("fstmemberInCallBack") + public String fstmemberInCallBack(HttpServletRequest request){ + Map map= getParameterMap(request); + log.info("fstmemberInCallBack回调返回信息:{}",JSONUtil.toJsonStr(map)); + if(ObjectUtil.isNotEmpty(map)&&map.containsKey("code")&&"000000".equals(map.get("code")+"")){ +// Map object=(Map)map.get("bizData"); + + JSONObject object=JSONUtil.parseObj(map.get("bizData").toString()); + if(ObjectUtil.isNotEmpty(object)&&object.containsKey("state")){ + if("TRADE_SUCCESS".equals(object.get("state").toString())){ + String orderNo=object.get("mchOrderNo").toString(); + String tradeNo=object.get("payOrderId").toString(); + return payService.fstMemberInSuccess(orderNo,tradeNo); + } + } + } + + return null; + + } + + @RequestMapping("test") + public void test(@RequestParam String payOrderNO){ + payService.test(payOrderNO); + } + @RequestMapping("notifyCallBack") public String notifyCallBack(HttpServletRequest request){ @@ -62,13 +88,64 @@ public class NotifyController { } + @RequestMapping("notifyfstCallBack") + public String notifyfstCallBack(HttpServletRequest request){ - private Map getParameterMap(HttpServletRequest request) { + Map map= getParameterMap(request); + log.info("notifyfstCallBack回调返回信息:{}",JSONUtil.toJsonStr(map)); + if(ObjectUtil.isNotEmpty(map)&&map.containsKey("code")&&"000000".equals(map.get("code")+"")){ + + JSONObject object=JSONUtil.parseObj(map.get("bizData").toString()); + if(ObjectUtil.isNotEmpty(object)&&object.containsKey("state")){ + if("TRADE_SUCCESS".equals(object.get("state").toString())){ + String orderNo=object.get("mchOrderNo").toString(); + String tradeNo=object.get("payOrderId").toString(); + return payService.callBackPayFST(tradeNo); + } + } + } + + return null; + } + + @RequestMapping("notifyCallBackGroupYsk") + public String notifyCallBackGroupYsk(HttpServletRequest request){ + Map map= getParameterMap(request); + log.info("团购卷回调返回信息:{}",JSONUtil.toJsonStr(map)); + if(ObjectUtil.isNotEmpty(map)&&map.containsKey("code")&&"200".equals(map.get("code")+"")){ + JSONObject object=JSONUtil.parseObj(map.get("data")); + if(ObjectUtil.isNotEmpty(object)&&object.containsKey("status")&&"1".equals(object.getStr("status"))){ + String orderNo=object.getStr("orderNumber"); + String payTime = object.getStr("payTime"); + return payService.callBackGroupPay(orderNo,payTime); + } + } + return null; + } + + @RequestMapping("notifyCallBackGroup") + public String notifyCallBackGroup(HttpServletRequest request) { + Map map = getParameterMap(request); + log.info("团购卷回调返回信息:{}", JSONUtil.toJsonStr(map)); + if (ObjectUtil.isNotEmpty(map) && map.containsKey("code") && "000000".equals(map.get("code") + "")) { + JSONObject object = JSONUtil.parseObj(map.get("bizData")); + if (ObjectUtil.isNotEmpty(object) && object.containsKey("state") && "TRADE_SUCCESS".equals(object.getStr("state"))) { + String orderNo = object.getStr("payOrderId"); + return payService.callBackGroupPay(orderNo, DateUtils.getTime(new Date())); + } + } + return null; + } + + + private Map getParameterMap(HttpServletRequest request) { RequestWrapper requestWrapper = new RequestWrapper(request); String body = requestWrapper.getBody(); if (ObjectUtil.isNotEmpty(body)) { return JSONUtil.toBean(body, Map.class); + }else { + Map parameterMap = request.getParameterMap(); + return parameterMap; } - return null; } } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/controller/OrderController.java b/src/main/java/com/chaozhanggui/system/cashierservice/controller/OrderController.java index f2974b1..5ba73f7 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/controller/OrderController.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/controller/OrderController.java @@ -9,6 +9,7 @@ import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.io.IOException; +import java.text.ParseException; @CrossOrigin(origins = "*") @RestController @@ -37,7 +38,10 @@ public class OrderController { * @return */ @GetMapping ("/orderInfo") - private Result orderInfo(@RequestParam Integer orderId){ + private Result orderInfo(@RequestParam(required = false) Integer orderId){ + if (orderId==null) { + return Result.fail("请返回首页订单列表查看"); + } return orderService.orderInfo(orderId); } @@ -50,4 +54,55 @@ public class OrderController { private void testMessage(@RequestParam("tableId") String tableId, @RequestParam("message") String message) throws IOException { orderService.testMessage(tableId,message); } + @GetMapping("/tradeIntegral") + private Result tradeIntegral(@RequestParam("userId") String userId, @RequestParam("id") String id) throws IOException, ParseException { + return orderService.tradeIntegral(userId,id); + } +// @GetMapping("/我的积分") +// private Result mineYhq(@RequestParam("userId") String userId) throws IOException { +// return orderService.mineYhq(userId); +// } + @GetMapping("/mineCoupons") + private Result mineCoupons(@RequestHeader String token, + @RequestParam("userId") String userId, + @RequestParam("status") String status, + @RequestParam(value = "page", required = false, defaultValue = "1") Integer page, + @RequestParam(value = "size", required = false, defaultValue = "1") Integer size, + @RequestParam("orderId") String orderId + ) throws IOException { + return orderService.mineCoupons(userId,orderId,status,page,size); + } + @GetMapping("/findCoupons") + private Result findCoupons(@RequestHeader String token,String type, + @RequestParam(value = "page", required = false, defaultValue = "1") Integer page, + @RequestParam(value = "size", required = false, defaultValue = "1") Integer size) throws IOException { + return orderService.findCoupons(type,page,size); + } + + @GetMapping("/findWiningUser") + private Result findWiningUser(){ + return orderService.findWiningUser(); + } + @GetMapping("/mineWinner") + private Result mineWinner(@RequestHeader String token,@RequestParam Integer userId, + @RequestParam(value = "page", required = false, defaultValue = "1") Integer page, + @RequestParam(value = "size", required = false, defaultValue = "1") Integer size){ + return orderService.mineWinner(userId,page,size); + } + @GetMapping("/getYhqPara") + private Result getYhqPara(){ + return orderService.getYhqPara(); + } + @GetMapping("/getYhqDouble") + private Result getYhqDouble(@RequestParam Integer orderId){ + return orderService.getYhqDouble(orderId); + } + @PostMapping("/yhqDouble") + private Result yhqDouble(@RequestParam Integer conponsId){ + return orderService.yhqDouble(conponsId); + } + @GetMapping("/kc") + private Result kc(){ + return orderService.kc(); + } } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/controller/PayController.java b/src/main/java/com/chaozhanggui/system/cashierservice/controller/PayController.java index fee5b56..fa090d4 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/controller/PayController.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/controller/PayController.java @@ -1,12 +1,14 @@ package com.chaozhanggui.system.cashierservice.controller; import cn.hutool.core.util.ObjectUtil; +import com.chaozhanggui.system.cashierservice.annotation.LimitSubmit; import com.chaozhanggui.system.cashierservice.service.PayService; import com.chaozhanggui.system.cashierservice.sign.Result; import com.chaozhanggui.system.cashierservice.util.IpUtil; +import com.chaozhanggui.system.cashierservice.util.TokenUtil; +import com.fasterxml.jackson.core.JsonProcessingException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; @@ -26,19 +28,20 @@ public class PayController { /** * 支付 - * @param request - * @param openId + * + * @param request payType wechatPay:微信支付;aliPay:支付宝支付; * @param map * @return */ @RequestMapping("orderPay") - public Result pay(HttpServletRequest request, @RequestHeader("openId") String openId, @RequestBody Map map) { - if(ObjectUtil.isEmpty(map)||map.size()<=0||!map.containsKey("orderId")||ObjectUtil.isEmpty(map.get("orderId"))){ + @LimitSubmit(key = "orderPay:%s") + public Result pay(HttpServletRequest request, @RequestHeader("openId") String openId, @RequestBody Map map) { + if (ObjectUtil.isEmpty(map) || map.size() <= 0 || !map.containsKey("orderId") || ObjectUtil.isEmpty(map.get("orderId"))) { return Result.fail("订单号不允许为空"); } try { - return payService.payOrder(openId,map.get("orderId").toString(), IpUtil.getIpAddr(request)); + return payService.payOrder(openId, map.get("orderId"), IpUtil.getIpAddr(request)); } catch (Exception e) { e.printStackTrace(); } @@ -46,14 +49,67 @@ public class PayController { } + /** + * 储值卡支付 + * + * @param token + * @param orderId + * @param memberId + * @return + */ + @GetMapping("accountPay") + public Result accountPay(@RequestHeader("token") String token, + @RequestParam("orderId") String orderId, + @RequestParam("memberId") String memberId, + @RequestParam("pwd") String pwd + ) { + return payService.accountPay(orderId, memberId, token,pwd); + } + + @RequestMapping("groupOrderPay") + public Result groupOrderPay(HttpServletRequest request, @RequestHeader String environment, @RequestHeader String token, @RequestBody Map map) { + if (ObjectUtil.isEmpty(map) || map.size() <= 0 || !map.containsKey("orderId") || ObjectUtil.isEmpty(map.get("orderId"))) { + return Result.fail("订单号不允许为空"); + } + String orderId = map.get("orderId"); +// String orderType = map.get("orderType").toString(); + String payType = map.get("payType"); + String userId = ""; + if (environment.equals("wx") && payType.equals("wechatPay")) { + userId = TokenUtil.parseParamFromToken(token).getString("openId"); + } else { + userId = TokenUtil.parseParamFromToken(token).getString("userId"); + } + //订单支付 orderId:62,payType=wechatPay,userId:or1l860rwM-rU_j9KrgMOwued + log.info("订单支付 orderId:{},payType={},userId:{}", orderId, payType, userId); + try { + return payService.groupOrderPay(orderId, payType, userId, IpUtil.getIpAddr(request), map.get("pwd")); + } catch (Exception e) { + e.printStackTrace(); + } + return Result.fail("支付失败"); + } + +// +// public Result memberAccountPay(@RequestHeader("openId") String openId, +// @RequestParam("orderId") String orderId, +// @RequestParam("userId") Integer userId, +// @RequestParam("shopId") String shopId, +// @RequestParam("pwd") String pwd +// ){ +// +// } + + /** * 修改订单状态 + * * @param map * @return */ @RequestMapping("modfiyOrderInfo") - public Result modfiyOrderInfo( @RequestBody Map map){ - if(ObjectUtil.isEmpty(map)||map.size()<=0||!map.containsKey("orderId")||ObjectUtil.isEmpty(map.get("orderId"))){ + public Result modfiyOrderInfo(@RequestBody Map map) { + if (ObjectUtil.isEmpty(map) || map.size() <= 0 || !map.containsKey("orderId") || ObjectUtil.isEmpty(map.get("orderId"))) { return Result.fail("订单号不允许为空"); } @@ -66,25 +122,53 @@ public class PayController { } + @RequestMapping("getActive") + public Result getActive( + @RequestHeader("token") String token, + @RequestParam("shopId") String shopId, + @RequestParam("page") int page, + @RequestParam("pageSize") int pageSize) { + return payService.getActivate(shopId, page, pageSize); + + } + /** * 充值 + * * @param request * @param openId * @param map * @return */ @RequestMapping("memeberIn") - public Result memeberIn(HttpServletRequest request,@RequestHeader("openId") String openId,@RequestHeader("id") String id, - @RequestBody Map map - ){ - return payService.memberIn(openId,id,map.get("amount").toString(),map.get("shopId").toString(),IpUtil.getIpAddr(request)); + @LimitSubmit(key = "memeberIn:%s") + public Result memeberIn(HttpServletRequest request, @RequestHeader("openId") String openId, @RequestHeader("id") String id, + @RequestBody Map map + ) { + try { + return payService.memberIn(openId, id, map.get("amount").toString(), map.get("shopId").toString(), IpUtil.getIpAddr(request)); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } } + @RequestMapping("getShopByMember") + public Result getShopByMember(@RequestHeader("token") String token, + @RequestParam("page") int page, + @RequestParam("pageSize") int pageSize, + @RequestParam("userId") String userId, + @RequestParam("shopId") String shopId + ) { + return payService.getShopByMember(userId,shopId,page,pageSize); + } - - - - + @RequestMapping("queryMemberAccount") + public Result queryMemberAccount(@RequestParam("memberId") String memberId, + @RequestParam(value = "page", defaultValue = "1") int page, + @RequestParam(value = "pageSize", defaultValue = "10") int pageSize + ) { + return payService.queryMemberAccount(memberId, page, pageSize); + } } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/controller/PhoneValidateCodeController.java b/src/main/java/com/chaozhanggui/system/cashierservice/controller/PhoneValidateCodeController.java deleted file mode 100644 index b37cd13..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/controller/PhoneValidateCodeController.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.chaozhanggui.system.cashierservice.controller; - -import com.chaozhanggui.system.cashierservice.exception.MsgException; -import com.chaozhanggui.system.cashierservice.sign.CodeEnum; -import com.chaozhanggui.system.cashierservice.sign.Result; -import com.chaozhanggui.system.cashierservice.util.RedisUtils; -import com.chaozhanggui.system.cashierservice.util.StringUtil; -import com.chaozhanggui.system.cashierservice.util.ValidateCodeUtil; -import lombok.RequiredArgsConstructor; -import org.apache.commons.lang3.StringUtils; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import javax.annotation.Resource; -import java.util.concurrent.TimeUnit; - -/** - * @author lyf - */ -@RestController -@RequestMapping("/phoneValidateCode") -@RequiredArgsConstructor -public class PhoneValidateCodeController { - - private final ValidateCodeUtil validateCodeUtil; - @Resource - private RedisUtils redisUtils; - /** - * 一分钟 - */ - protected static final long ONE_MINUTE = 60; - - /** - * 发送短信验证码 - * @param phone - * @return - */ - @GetMapping - public Result verifyPhoneIsExist(@RequestParam String phone) { - if (StringUtils.isBlank(phone)) { - return Result.fail("手机号不可为空!"); - } - String random = StringUtil.random(6); - validateCodeUtil.requestValidateCodeAli(phone, random); - //存入缓存 - try { - redisUtils.set(phone,random,ONE_MINUTE,TimeUnit.SECONDS); - }catch (Exception e){ - throw new MsgException("验证码发送失败"); - } - return Result.success(CodeEnum.SUCCESS); - } -} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/controller/ProductController.java b/src/main/java/com/chaozhanggui/system/cashierservice/controller/ProductController.java index 07ed28d..3602a64 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/controller/ProductController.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/controller/ProductController.java @@ -2,9 +2,12 @@ package com.chaozhanggui.system.cashierservice.controller; import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; import com.chaozhanggui.system.cashierservice.service.ProductService; import com.chaozhanggui.system.cashierservice.sign.Result; +import com.chaozhanggui.system.cashierservice.util.TokenUtil; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -20,25 +23,66 @@ public class ProductController { @Autowired private ProductService productService; - @RequestMapping("queryProduct") - public Result queryProduct(@RequestBody Map map){ - - if(ObjectUtil.isEmpty(map)||map.size()<=0||!map.containsKey("code")){ - return Result.fail("参数错误"); - } - return productService.queryProduct(map.get("code").toString(),(map.containsKey("productGroupId")&&ObjectUtil.isNotEmpty(map.get("productGroupId")))?map.get("productGroupId").toString():""); + /** + * 通过桌码获取shopId + * + * @param code + * @return shopid + */ + @RequestMapping("queryShopIdByTableCode") + public Result queryShopIdByTableCode( + @RequestHeader("openId") String openId, + @RequestHeader("id") String userId, + @RequestParam("code") String code) { + return productService.queryShopIdByTableCode(userId, openId, code); } + /** + * 通过code和分组Id + * + * @param map + * @return + */ + @RequestMapping("queryProduct") + public Result queryProduct(@RequestBody Map map) { + + if (ObjectUtil.isEmpty(map) || map.size() <= 0 || !map.containsKey("code")) { + return Result.fail("参数错误"); + } + return productService.queryProduct( + map.get("code").toString(), + (map.containsKey("productGroupId") && ObjectUtil.isNotEmpty(map.get("productGroupId"))) ? map.get("productGroupId").toString() : ""); + } @GetMapping("queryProductSku") public Result queryProductSku( - @RequestParam("shopId") String shopId, - @RequestParam("productId") String productId, - @RequestParam("spec_tag") String spec_tag - ){ - return productService.queryProductSku(shopId,productId,spec_tag); + @RequestParam("shopId") String shopId, + @RequestParam("productId") String productId, + @RequestParam("spec_tag") String spec_tag + ) { + return productService.queryProductSku(shopId, productId, spec_tag); } + /** + * 团购商品详情/商品类型为 套餐商品 + */ + @GetMapping("/productInfo") + public Result productInfo( + @RequestParam Integer productId, + @RequestParam String lat, + @RequestParam String lng, + @RequestHeader String environment) throws Exception { + return productService.productInfo(productId, lat, lng, environment); + } + /** + * 订单确认页 + */ + @GetMapping("/orderConfirm") + public Result orderConfirm( + @RequestParam Integer productId, + @RequestHeader String environment) throws Exception { + return productService.orderConfirm(productId, environment); + } } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/controller/UserContoller.java b/src/main/java/com/chaozhanggui/system/cashierservice/controller/UserContoller.java new file mode 100644 index 0000000..1b28a97 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/controller/UserContoller.java @@ -0,0 +1,151 @@ +package com.chaozhanggui.system.cashierservice.controller; + + +import cn.binarywang.wx.miniapp.util.crypt.WxMaCryptUtils; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.RandomUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.chaozhanggui.system.cashierservice.dao.TbMerchantAccountMapper; +import com.chaozhanggui.system.cashierservice.dao.TbShopUserMapper; +import com.chaozhanggui.system.cashierservice.dao.TbUserInfoMapper; +import com.chaozhanggui.system.cashierservice.entity.TbMerchantAccount; +import com.chaozhanggui.system.cashierservice.entity.TbShopUser; +import com.chaozhanggui.system.cashierservice.entity.TbUserInfo; +import com.chaozhanggui.system.cashierservice.entity.dto.AuthUserDto; +import com.chaozhanggui.system.cashierservice.entity.dto.OnlineUserDto; +import com.chaozhanggui.system.cashierservice.entity.vo.IntegralFlowVo; +import com.chaozhanggui.system.cashierservice.entity.vo.IntegralVo; +import com.chaozhanggui.system.cashierservice.entity.vo.OrderVo; +import com.chaozhanggui.system.cashierservice.service.LoginService; +import com.chaozhanggui.system.cashierservice.service.OnlineUserService; +import com.chaozhanggui.system.cashierservice.service.UserService; +import com.chaozhanggui.system.cashierservice.sign.CodeEnum; +import com.chaozhanggui.system.cashierservice.sign.Result; +import com.chaozhanggui.system.cashierservice.util.IpUtil; +import com.chaozhanggui.system.cashierservice.util.MD5Utils; +import com.chaozhanggui.system.cashierservice.util.StringUtil; +import com.chaozhanggui.system.cashierservice.util.TokenUtil; +import com.chaozhanggui.system.cashierservice.wxUtil.WechatUtil; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import java.math.BigDecimal; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; + +@CrossOrigin(origins = "*") +@RestController +@Slf4j +@RequestMapping("user") +public class UserContoller { + + + @Autowired + UserService userService; + + @Autowired + private TbShopUserMapper shopUserMapper; + @Autowired + private TbUserInfoMapper userInfoMapper; + +// @GetMapping("/userInfo") +// public JSONObject userInfo(@RequestParam("openId") String openId ) throws Exception { +// TbUserInfo shopUser = userInfoMapper.selectByOpenId(openId); +// JSONObject jsonObject = new JSONObject(); +// if (Objects.isNull(shopUser)){ +// jsonObject.put("status","fail"); +// jsonObject.put("msg","用户不存在"); +// return jsonObject; +// } +// String userSign = UUID.randomUUID().toString().replaceAll("-",""); +// String token = TokenUtil.generateJfToken(openId,userSign); +// JSONObject object = new JSONObject(); +// object.put("token",token); +// object.put("userSign",userSign); +// object.put("num",shopUser.getTotalScore()); +// jsonObject.put("status","success"); +// jsonObject.put("msg","成功"); +// jsonObject.put("data",object); +// return jsonObject; +// } + @GetMapping("/shopUserInfo") + public Result shopUserInfo(@RequestParam("userId") String userId ,@RequestHeader("openId") String openId,@RequestParam("shopId") String shopId ) throws Exception { + TbShopUser shopUser=new TbShopUser(); + if (StringUtils.isNotBlank(shopId) && !shopId.equals("null")) { + shopUser = shopUserMapper.selectByUserIdAndShopId(userId, shopId); + if (ObjectUtil.isEmpty(shopUser)) { + TbUserInfo tbUserInfo = userInfoMapper.selectByPrimaryKey(Integer.valueOf(userId)); + shopUser = shopUserMapper.selectByPhoneAndShopId(tbUserInfo.getTelephone(), shopId); + if(ObjectUtil.isEmpty(shopUser)){ + shopUser=new TbShopUser(); + shopUser.setName(tbUserInfo.getNickName()); + shopUser.setSex(tbUserInfo.getSex()); + shopUser.setBirthDay(tbUserInfo.getBirthDay()); + shopUser.setLevel(Byte.parseByte("1")); + String dynamicCode = RandomUtil.randomNumbers(8); + shopUser.setCode(dynamicCode); + shopUser.setTelephone(tbUserInfo.getTelephone()); + shopUser.setAmount(BigDecimal.ZERO); + shopUser.setIsVip(Byte.parseByte("0")); + shopUser.setCreditAmount(BigDecimal.ZERO); + shopUser.setConsumeAmount(BigDecimal.ZERO); + shopUser.setConsumeNumber(0); + shopUser.setLevelConsume(BigDecimal.ZERO); + shopUser.setStatus(Byte.parseByte("1")); + shopUser.setShopId(shopId); + shopUser.setUserId(userId); + shopUser.setMiniOpenId(openId); + shopUser.setCreatedAt(System.currentTimeMillis()); + shopUser.setUpdatedAt(System.currentTimeMillis()); + shopUserMapper.insert(shopUser); + }else { + shopUser.setUserId(userId); + shopUser.setUpdatedAt(System.currentTimeMillis()); + shopUserMapper.updateByPrimaryKey(shopUser); + } + } + }else { + shopUser.setAmount(BigDecimal.ZERO); + } + return Result.success(CodeEnum.SUCCESS,shopUser); + } + + @GetMapping("/userCoupon") + public Result userCoupon(@RequestParam("userId") String userId ,@RequestParam("orderNum") BigDecimal orderNum ) throws Exception { + int num = userService.userCoupon(userId,orderNum); + return Result.success(CodeEnum.SUCCESS,num); + } + @PostMapping("/modityIntegral") + public JSONObject modityIntegral(@RequestHeader String token,@RequestBody IntegralVo integralVo ) throws Exception { + JSONObject jsonObject = TokenUtil.parseParamFromToken(token); + String userSign = jsonObject.getString("userSign"); + return userService.modityIntegral(integralVo,userSign); + } + @PostMapping("/userIntegral") + public JSONObject userIntegral(@RequestHeader String token,@RequestBody IntegralFlowVo integralFlowVo ) throws Exception { + JSONObject jsonObject = TokenUtil.parseParamFromToken(token); + String userSign = jsonObject.getString("userSign"); + return userService.userIntegral(integralFlowVo,userSign); + } + @PostMapping("/userAllIntegral") + public JSONObject userAllIntegral(@RequestBody IntegralFlowVo integralFlowVo ) throws Exception { +// JSONObject jsonObject = TokenUtil.parseParamFromToken(token); +// String userSign = jsonObject.getString("userSign"); + return userService.userAllIntegral(integralFlowVo,"userSign"); + } + @PostMapping("/userAll") + public JSONObject userAll(@RequestBody IntegralFlowVo integralFlowVo ) throws Exception { +// JSONObject jsonObject = TokenUtil.parseParamFromToken(token); +// String userSign = jsonObject.getString("userSign"); + return userService.userAll(integralFlowVo,"userSign"); + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/SysDictDetailMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/SysDictDetailMapper.java deleted file mode 100644 index d8fad88..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/dao/SysDictDetailMapper.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.chaozhanggui.system.cashierservice.dao; - -import com.chaozhanggui.system.cashierservice.entity.SysDict; -import com.chaozhanggui.system.cashierservice.entity.SysDictDetail; -import org.apache.ibatis.annotations.Param; - -import java.util.List; - -public interface SysDictDetailMapper { - int deleteByPrimaryKey(Long detailId); - - int insert(SysDictDetail record); - - int insertSelective(SysDictDetail record); - - SysDictDetail selectByPrimaryKey(Long detailId); - - List selectByAll(); - - List selectByAllDetail(@Param("list") List dictId); - - List selectByDictId(@Param("dictId") Long dictId); - - int updateByPrimaryKeySelective(SysDictDetail record); - - int updateByPrimaryKey(SysDictDetail record); -} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/SysDictMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/SysDictMapper.java index 7204534..6d239cb 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/dao/SysDictMapper.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/SysDictMapper.java @@ -1,17 +1,14 @@ package com.chaozhanggui.system.cashierservice.dao; import com.chaozhanggui.system.cashierservice.entity.SysDict; +import org.apache.ibatis.annotations.Param; + +import java.util.List; public interface SysDictMapper { - int deleteByPrimaryKey(Long dictId); + List selectHot(); - int insert(SysDict record); + List selectByType(@Param("type") String type); - int insertSelective(SysDict record); - - SysDict selectByPrimaryKey(Long dictId); - - int updateByPrimaryKeySelective(SysDict record); - - int updateByPrimaryKey(SysDict record); + List selectByDictId(@Param("dictId") Long dictId); } \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TagProductDeptsMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TagProductDeptsMapper.java new file mode 100644 index 0000000..d595e87 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TagProductDeptsMapper.java @@ -0,0 +1,22 @@ +package com.chaozhanggui.system.cashierservice.dao; + +import com.chaozhanggui.system.cashierservice.entity.vo.TagProductVO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.springframework.stereotype.Component; + +import java.util.List; + +/** + * (TagProductDepts) 商品标签 表数据库访问层 + * + * @author lyf + * @since 2024-04-08 15:03:49 + */ +@Component +@Mapper +public interface TagProductDeptsMapper { + List queryTagAndProduct(@Param("list") List list); + List queryTagByProductId(@Param("productId") String productId); +} + diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbActivateMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbActivateMapper.java new file mode 100644 index 0000000..2a458b2 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbActivateMapper.java @@ -0,0 +1,29 @@ +package com.chaozhanggui.system.cashierservice.dao; + +import com.chaozhanggui.system.cashierservice.entity.TbActivate; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.springframework.stereotype.Component; + +import java.math.BigDecimal; +import java.util.List; + +@Component +@Mapper +public interface TbActivateMapper { + int deleteByPrimaryKey(Integer id); + + int insert(TbActivate record); + + int insertSelective(TbActivate record); + + TbActivate selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(TbActivate record); + + int updateByPrimaryKey(TbActivate record); + + TbActivate selectByAmount(@Param("shopId") String shopId,@Param("amount") BigDecimal amount); + + List selectByShpopId(String shopId); +} \ 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 5df9578..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,8 +20,7 @@ public interface TbCashierCartMapper { int updateByPrimaryKeySelective(TbCashierCart record); - int updateByPrimaryKey(TbCashierCart record); - + List selectByShopIdAndTableId(@Param("shopId") String shopId,@Param("tableId") String tableId); List selectALlByMasterId(@Param("masterId") String masterId, @Param("status") String status); @@ -57,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/dao/TbCouponCategoryMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbCouponCategoryMapper.java new file mode 100644 index 0000000..abfb9d0 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbCouponCategoryMapper.java @@ -0,0 +1,20 @@ +package com.chaozhanggui.system.cashierservice.dao; + +import com.chaozhanggui.system.cashierservice.entity.TbCouponCategory; +/** + * 团购卷分类(TbCouponCategory)表数据库访问层 + * + * @author ww + * @since 2024-04-24 14:09:16 + */ +public interface TbCouponCategoryMapper { + + /** + * 通过ID查询单条数据 + * + * @param id 主键 + * @return 实例对象 + */ + TbCouponCategory queryById(Integer id); +} + diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbGroupOrderCouponMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbGroupOrderCouponMapper.java new file mode 100644 index 0000000..ce5ca77 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbGroupOrderCouponMapper.java @@ -0,0 +1,72 @@ +package com.chaozhanggui.system.cashierservice.dao; + +import com.chaozhanggui.system.cashierservice.entity.TbGroupOrderCoupon; +import org.apache.ibatis.annotations.Param; +import org.springframework.data.domain.Pageable; + +import java.util.List; + +/** + * 团购卷 卷码表(TbGroupOrderCoupon)表数据库访问层 + * + * @author ww + * @since 2024-05-06 14:39:59 + */ +public interface TbGroupOrderCouponMapper { + + /** + * 通过ID查询单条数据 + * + * @param id 主键 + * @return 实例对象 + */ + TbGroupOrderCoupon queryById(Integer id); + + List queryByOrderId(Integer orderId); + + List queryNoRefundByOrderId(Integer orderId); + + /** + * 查询数据 + * + * @param tbGroupOrderCoupon 查询条件 + * @param pageable 分页对象 + * @return 对象列表 + */ + List queryAll(TbGroupOrderCoupon tbGroupOrderCoupon, @Param("pageable") Pageable pageable); + + + /** + * 新增数据 + * + * @param tbGroupOrderCoupon 实例对象 + * @return 影响行数 + */ + int insert(TbGroupOrderCoupon tbGroupOrderCoupon); + + /** + * 批量新增数据(MyBatis原生foreach方法) + * + * @param entities List 实例对象列表 + * @return 影响行数 + */ + int insertBatch(@Param("entities") List entities); + + /** + * 修改数据 + * + * @param tbGroupOrderCoupon 实例对象 + * @return 影响行数 + */ + int update(TbGroupOrderCoupon tbGroupOrderCoupon); + + /** + * 通过主键删除数据 + * + * @param id 主键 + * @return 影响行数 + */ + int deleteById(Integer id); + +} + diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbGroupOrderInfoMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbGroupOrderInfoMapper.java new file mode 100644 index 0000000..0342b96 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbGroupOrderInfoMapper.java @@ -0,0 +1,64 @@ +package com.chaozhanggui.system.cashierservice.dao; + +import com.chaozhanggui.system.cashierservice.entity.TbGroupOrderInfo; +import com.chaozhanggui.system.cashierservice.entity.dto.GroupOrderDto; +import com.chaozhanggui.system.cashierservice.entity.vo.GroupOrderListVo; +import com.github.pagehelper.Page; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * 团购卷订单(TbGroupOrderInfo)表数据库访问层 + * + * @author ww + * @since 2024-04-27 16:15:08 + */ +public interface TbGroupOrderInfoMapper { + + /** + * 通过ID查询单条数据 + * + * @param id 主键 + * @return 实例对象 + */ + TbGroupOrderInfo queryById(Integer id); + + TbGroupOrderInfo selectByPayOrderNo(@Param("payOrderNO")String payOrderNO); + + /** + * 查询数据 + * + * @param param 查询条件 + * @return 对象列表 + */ + List queryAll(GroupOrderDto param); + + + /** + * 新增数据 + * + * @param tbGroupOrderInfo 实例对象 + * @return 影响行数 + */ + int insert(TbGroupOrderInfo tbGroupOrderInfo); + + /** + * 批量新增数据(MyBatis原生foreach方法) + * + * @param entities List 实例对象列表 + * @return 影响行数 + */ + int insertBatch(@Param("entities") List entities); + + /** + * 修改数据 + * + * @param tbGroupOrderInfo 实例对象 + * @return 影响行数 + */ + int update(TbGroupOrderInfo tbGroupOrderInfo); + + +} + diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbIntegralFlowMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbIntegralFlowMapper.java new file mode 100644 index 0000000..cb6f56f --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbIntegralFlowMapper.java @@ -0,0 +1,17 @@ +package com.chaozhanggui.system.cashierservice.dao; + +import com.chaozhanggui.system.cashierservice.entity.TbIntegralFlow; + +public interface TbIntegralFlowMapper { + int deleteByPrimaryKey(Integer id); + + int insert(TbIntegralFlow record); + + int insertSelective(TbIntegralFlow record); + + TbIntegralFlow selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(TbIntegralFlow record); + + int updateByPrimaryKey(TbIntegralFlow record); +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbIntegralMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbIntegralMapper.java new file mode 100644 index 0000000..322cfcd --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbIntegralMapper.java @@ -0,0 +1,23 @@ +package com.chaozhanggui.system.cashierservice.dao; + +import com.chaozhanggui.system.cashierservice.entity.TbIntegral; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +public interface TbIntegralMapper { + int deleteByPrimaryKey(Integer id); + + int insert(TbIntegral record); + + int insertSelective(TbIntegral record); + + TbIntegral selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(TbIntegral record); + + int updateByPrimaryKey(TbIntegral record); + + List selectAllByUserId(String userId); +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbMerchantAccountMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbMerchantAccountMapper.java index e067028..b0d4ee6 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbMerchantAccountMapper.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbMerchantAccountMapper.java @@ -1,7 +1,11 @@ package com.chaozhanggui.system.cashierservice.dao; import com.chaozhanggui.system.cashierservice.entity.TbMerchantAccount; +import org.apache.ibatis.annotations.Mapper; +import org.springframework.stereotype.Component; +@Component +@Mapper public interface TbMerchantAccountMapper { TbMerchantAccount selectByAccount(String account); diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbMerchantCouponMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbMerchantCouponMapper.java index 572b1fa..08bf7d4 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbMerchantCouponMapper.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbMerchantCouponMapper.java @@ -1,9 +1,8 @@ package com.chaozhanggui.system.cashierservice.dao; import com.chaozhanggui.system.cashierservice.entity.TbMerchantCoupon; -import org.apache.ibatis.annotations.Param; -import org.springframework.data.domain.Pageable; -import java.util.List; +import org.apache.ibatis.annotations.Mapper; +import org.springframework.stereotype.Component; /** * 优惠券(TbMerchantCoupon)表数据库访问层 @@ -11,6 +10,8 @@ import java.util.List; * @author lyf * @since 2024-04-02 09:24:16 */ +@Component +@Mapper public interface TbMerchantCouponMapper { /** @@ -21,65 +22,7 @@ public interface TbMerchantCouponMapper { */ TbMerchantCoupon queryById(Integer id); - /** - * 查询指定行数据 - * - * @param tbMerchantCoupon 查询条件 - * @param pageable 分页对象 - * @return 对象列表 - */ - List queryAllByLimit(TbMerchantCoupon tbMerchantCoupon, @Param("pageable") Pageable pageable); - List queryAllByPage(@Param("page")Integer page, @Param("size")Integer size); - /** - * 统计总行数 - * - * @param tbMerchantCoupon 查询条件 - * @return 总行数 - */ - long count(TbMerchantCoupon tbMerchantCoupon); - - /** - * 新增数据 - * - * @param tbMerchantCoupon 实例对象 - * @return 影响行数 - */ - int insert(TbMerchantCoupon tbMerchantCoupon); - - /** - * 批量新增数据(MyBatis原生foreach方法) - * - * @param entities List 实例对象列表 - * @return 影响行数 - */ - int insertBatch(@Param("entities") List entities); - - /** - * 批量新增或按主键更新数据(MyBatis原生foreach方法) - * - * @param entities List 实例对象列表 - * @return 影响行数 - * @throws org.springframework.jdbc.BadSqlGrammarException 入参是空List的时候会抛SQL语句错误的异常,请自行校验入参 - */ - int insertOrUpdateBatch(@Param("entities") List entities); - - /** - * 修改数据 - * - * @param tbMerchantCoupon 实例对象 - * @return 影响行数 - */ - int update(TbMerchantCoupon tbMerchantCoupon); - - /** - * 通过主键删除数据 - * - * @param id 主键 - * @return 影响行数 - */ - int deleteById(Integer id); - } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbOrderInfoMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbOrderInfoMapper.java index bea67e1..20d3776 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbOrderInfoMapper.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbOrderInfoMapper.java @@ -5,6 +5,7 @@ import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Component; +import java.math.BigDecimal; import java.util.List; @Component @@ -28,9 +29,9 @@ public interface TbOrderInfoMapper { List selectAllByStatus(String status); TbOrderInfo selectByPayOrderNo(String payOrderNo); - List selectByUserId(@Param("userId")Integer userId, @Param("page")Integer page, - @Param("size")Integer size, @Param("status") String status); - + List selectByUserId(@Param("userId")Integer userId, @Param("status") String status); + List selectByTradeDay(@Param("day") String day,@Param("minPrice") BigDecimal minPrice,@Param("maxPrice") BigDecimal maxPrice); + List selectWinnerByUserId(@Param("userId")Integer userId); } \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbParamsMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbParamsMapper.java new file mode 100644 index 0000000..f234c90 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbParamsMapper.java @@ -0,0 +1,17 @@ +package com.chaozhanggui.system.cashierservice.dao; + +import com.chaozhanggui.system.cashierservice.entity.TbParams; + +public interface TbParamsMapper { + int deleteByPrimaryKey(Integer id); + + int insert(TbParams record); + + int insertSelective(TbParams record); + + TbParams selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(TbParams record); + + int updateByPrimaryKey(TbParams record); +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbPlatformDictMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbPlatformDictMapper.java index fa1ce5b..e85bc7b 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbPlatformDictMapper.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbPlatformDictMapper.java @@ -3,7 +3,6 @@ package com.chaozhanggui.system.cashierservice.dao; import com.chaozhanggui.system.cashierservice.entity.TbPlatformDict; import org.apache.ibatis.annotations.Param; -import org.springframework.data.domain.Pageable; import java.util.List; /** @@ -22,64 +21,10 @@ public interface TbPlatformDictMapper { */ TbPlatformDict queryById(Integer id); - /** - * 查询指定行数据 - * - * @param tbPlatformDict 查询条件 - * @param pageable 分页对象 - * @return 对象列表 - */ - List queryAllByLimit(TbPlatformDict tbPlatformDict, @Param("pageable") Pageable pageable); + List queryByIdList(@Param("idList")List idList); List queryAllByType(@Param("type") String type,@Param("environment") String environment); - /** - * 统计总行数 - * - * @param tbPlatformDict 查询条件 - * @return 总行数 - */ - long count(TbPlatformDict tbPlatformDict); - - /** - * 新增数据 - * - * @param tbPlatformDict 实例对象 - * @return 影响行数 - */ - int insert(TbPlatformDict tbPlatformDict); - - /** - * 批量新增数据(MyBatis原生foreach方法) - * - * @param entities List 实例对象列表 - * @return 影响行数 - */ - int insertBatch(@Param("entities") List entities); - - /** - * 批量新增或按主键更新数据(MyBatis原生foreach方法) - * - * @param entities List 实例对象列表 - * @return 影响行数 - * @throws org.springframework.jdbc.BadSqlGrammarException 入参是空List的时候会抛SQL语句错误的异常,请自行校验入参 - */ - int insertOrUpdateBatch(@Param("entities") List entities); - - /** - * 修改数据 - * - * @param tbPlatformDict 实例对象 - * @return 影响行数 - */ - int update(TbPlatformDict tbPlatformDict); - - /** - * 通过主键删除数据 - * - * @param id 主键 - * @return 影响行数 - */ - int deleteById(Integer id); + List queryGroupByValue(@Param("value")String value,@Param("environment") String environment); } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbProductGroupMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbProductGroupMapper.java index e5274ee..13d89fd 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbProductGroupMapper.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbProductGroupMapper.java @@ -27,5 +27,6 @@ public interface TbProductGroupMapper { List selectByIdAndShopId(@Param("code") String code); List selectByQrcode(@Param("qrCode") String qrCode,@Param("groupId") Integer groupId); + List selectByShopId(@Param("shopId") String shopId,@Param("groupId") Integer groupId); } \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbProductMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbProductMapper.java index 91c8f2b..9208a08 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbProductMapper.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbProductMapper.java @@ -2,6 +2,7 @@ package com.chaozhanggui.system.cashierservice.dao; import com.chaozhanggui.system.cashierservice.entity.TbProduct; import com.chaozhanggui.system.cashierservice.entity.TbProductWithBLOBs; +import com.chaozhanggui.system.cashierservice.entity.vo.ShopGroupInfoVo; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Component; @@ -11,25 +12,26 @@ import java.util.List; @Component @Mapper public interface TbProductMapper { - int deleteByPrimaryKey(Integer id); - - int insert(TbProductWithBLOBs record); - - int insertSelective(TbProductWithBLOBs record); TbProductWithBLOBs selectByPrimaryKey(Integer id); TbProduct selectById(Integer id); - int updateByPrimaryKeySelective(TbProductWithBLOBs record); - - int updateByPrimaryKeyWithBLOBs(TbProductWithBLOBs record); - - int updateByPrimaryKey(TbProduct record); - List selectByIdIn(@Param("ids") String ids); List selectByIds(@Param("list") List ids); Integer selectByQcode(@Param("code") String code,@Param("productId") Integer productId,@Param("shopId") String shopId); Integer selectByNewQcode(@Param("code") String code,@Param("productId") Integer productId,@Param("shopId") String shopId,@Param("list") List list); + + List selGroups(@Param("proName") String proName,@Param("type") String type, + @Param("rightTopLng") Double rightTopLng, @Param("rightTopLat") Double rightTopLat, + @Param("leftBottomLng") Double leftBottomLng, @Param("leftBottomLat") Double leftBottomLat, + @Param("cities") String cities, @Param("orderBy") String orderBy, @Param("lng") String lng, @Param("lat") String lat); + + List selHotGroups(@Param("proName") String proName,@Param("type") String type, + @Param("startTime") String startTime, @Param("endTime") String endTime, + @Param("cities") String cities, @Param("orderBy") String orderBy, @Param("lng") String lng, @Param("lat") String lat); + + + void upGroupRealSalesNumber(@Param("id") String id,@Param("number") Integer number); } \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbProductSkuMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbProductSkuMapper.java index 018ec3e..7edb951 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbProductSkuMapper.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbProductSkuMapper.java @@ -38,4 +38,5 @@ public interface TbProductSkuMapper { List selectDownSku(@Param("list") List productId); List selectSkus(@Param("list") List productId); + List selectSku(@Param("productId") String productId); } \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbPurchaseNoticeMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbPurchaseNoticeMapper.java new file mode 100644 index 0000000..630fa9c --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbPurchaseNoticeMapper.java @@ -0,0 +1,30 @@ +package com.chaozhanggui.system.cashierservice.dao; + +import com.chaozhanggui.system.cashierservice.entity.TbPurchaseNotice; + +/** + * 购买须知(关联tb_merchant_coupon)(TbPurchaseNotice)表数据库访问层 + * + * @author ww + * @since 2024-04-11 10:00:23 + */ +public interface TbPurchaseNoticeMapper { + + /** + * 通过ID查询单条数据 + * + * CouponId 主键 + * @return 实例对象 + */ + TbPurchaseNotice queryByCouponId(Integer id); + + /** + * 通过ID查询单条数据 + * + * @param id 主键 + * @return 实例对象 + */ + TbPurchaseNotice queryById(Integer id); + +} + diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbReleaseFlowMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbReleaseFlowMapper.java new file mode 100644 index 0000000..0cce4bd --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbReleaseFlowMapper.java @@ -0,0 +1,24 @@ +package com.chaozhanggui.system.cashierservice.dao; + +import com.chaozhanggui.system.cashierservice.entity.TbReleaseFlow; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +public interface TbReleaseFlowMapper { + int deleteByPrimaryKey(Integer id); + + int insert(TbReleaseFlow record); + + int insertSelective(TbReleaseFlow record); + + TbReleaseFlow selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(TbReleaseFlow record); + + int updateByPrimaryKey(TbReleaseFlow record); + + List selectByUserId(@Param("userId") String userId); + + List selectAll(); +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbShopInfoMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbShopInfoMapper.java index 7567a21..ad6904e 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbShopInfoMapper.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbShopInfoMapper.java @@ -2,6 +2,7 @@ package com.chaozhanggui.system.cashierservice.dao; import com.chaozhanggui.system.cashierservice.entity.TbShopInfo; import com.chaozhanggui.system.cashierservice.entity.vo.HomeVO; +import com.chaozhanggui.system.cashierservice.entity.vo.SubShopVo; import com.chaozhanggui.system.cashierservice.entity.vo.UserDutyVo; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; @@ -18,7 +19,15 @@ public interface TbShopInfoMapper { int insertSelective(TbShopInfo record); + List selShopInfoByGps(@Param("rightTopLng") Double rightTopLng, @Param("rightTopLat") Double rightTopLat, + @Param("leftBottomLng") Double leftBottomLng, @Param("leftBottomLat") Double leftBottomLat, + @Param("cities") String cities, @Param("lng") String lng, @Param("lat") String lat, + @Param("shopName")String shopName); + TbShopInfo selectByPrimaryKey(Integer id); + + Integer selNumByChain(@Param("chainName") String chainName); + List selectByIds(@Param("list") List ids); int updateByPrimaryKeySelective(TbShopInfo record); @@ -31,7 +40,7 @@ public interface TbShopInfoMapper { TbShopInfo selectByPhone(String phone); - List selectShopInfo(@Param("page")Integer page, @Param("size")Integer size); + List selectShopInfo(@Param("page") Integer page, @Param("size") Integer size); List searchUserDutyDetail(@Param("list") List productId); } \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbShopPayTypeMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbShopPayTypeMapper.java index e656808..6990b03 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbShopPayTypeMapper.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbShopPayTypeMapper.java @@ -1,7 +1,12 @@ package com.chaozhanggui.system.cashierservice.dao; import com.chaozhanggui.system.cashierservice.entity.TbShopPayType; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.springframework.stereotype.Component; +@Component +@Mapper public interface TbShopPayTypeMapper { int deleteByPrimaryKey(Integer id); @@ -14,4 +19,6 @@ public interface TbShopPayTypeMapper { int updateByPrimaryKeySelective(TbShopPayType record); int updateByPrimaryKey(TbShopPayType record); + + int countSelectByShopIdAndPayType(@Param("shopId") String shopId, @Param("payType") String payType ); } \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbShopTableMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbShopTableMapper.java index 1cf5017..87f5277 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbShopTableMapper.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbShopTableMapper.java @@ -22,6 +22,9 @@ public interface TbShopTableMapper { TbShopTable selectQRcode(String code); + String queryShopIdByTableCode(String code); + + int upDateQrcodeNull(String code); int updateByPrimaryKeySelective(TbShopTable record); int updateByPrimaryKey(TbShopTable record); diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbShopUserFlowMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbShopUserFlowMapper.java index 7cf0c32..8beec03 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbShopUserFlowMapper.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbShopUserFlowMapper.java @@ -1,14 +1,10 @@ package com.chaozhanggui.system.cashierservice.dao; import com.chaozhanggui.system.cashierservice.entity.TbShopUserFlow; -import org.apache.ibatis.annotations.Mapper; -import org.springframework.stereotype.Component; import java.util.List; import java.util.Map; -@Component -@Mapper public interface TbShopUserFlowMapper { int deleteByPrimaryKey(Integer id); @@ -22,5 +18,6 @@ public interface TbShopUserFlowMapper { int updateByPrimaryKey(TbShopUserFlow record); + List> selectByMemberAccountFlow(String memberId); } \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbShopUserMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbShopUserMapper.java index 1f0e8f8..ab3069b 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbShopUserMapper.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbShopUserMapper.java @@ -1,10 +1,15 @@ package com.chaozhanggui.system.cashierservice.dao; +import com.chaozhanggui.system.cashierservice.entity.TbParams; import com.chaozhanggui.system.cashierservice.entity.TbShopUser; +import com.chaozhanggui.system.cashierservice.entity.vo.ShopUserListVo; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Component; +import java.util.List; +import java.util.Map; + @Component @Mapper public interface TbShopUserMapper { @@ -15,14 +20,22 @@ public interface TbShopUserMapper { int insertSelective(TbShopUser record); TbShopUser selectByPrimaryKey(String id); + List selectByPhone(String phone); int updateByPrimaryKeySelective(TbShopUser record); int updateByPrimaryKey(TbShopUser record); + int upUserBYId(TbShopUser record); TbShopUser selectByUserIdAndShopId(@Param("userId") String userId,@Param("shopId") String shopId); + TbShopUser selectByPhoneAndShopId(@Param("phone") String phone,@Param("shopId") String shopId); + List selectAllByUserId(@Param("userId") String userId); - TbShopUser selectByUserId(@Param("userId") String userId); + List selectByUserId(@Param("userId") String userId, @Param("shopId") String shopId); + + TbShopUser selectByOpenId(@Param("openId") String openId); + + TbParams selectParams(); } \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbShopVideoMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbShopVideoMapper.java new file mode 100644 index 0000000..7fa42de --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbShopVideoMapper.java @@ -0,0 +1,32 @@ +package com.chaozhanggui.system.cashierservice.dao; + +import com.chaozhanggui.system.cashierservice.entity.TbShopVideo; + +import java.util.List; + +/** + * (TbShopVideo)表数据库访问层 + * + * @author ww + * @since 2024-04-12 14:50:09 + */ +public interface TbShopVideoMapper { + + /** + * 通过ID查询单条数据 + * + * @param id 主键 + * @return 实例对象 + */ + TbShopVideo queryById(Integer id); + + /** + * 查询数据 + * + * @param tbShopVideo 查询条件 + * @return 对象列表 + */ + List queryAll(TbShopVideo tbShopVideo); + +} + diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbSplitAccountsMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbSplitAccountsMapper.java new file mode 100644 index 0000000..70ee67a --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbSplitAccountsMapper.java @@ -0,0 +1,17 @@ +package com.chaozhanggui.system.cashierservice.dao; + +import com.chaozhanggui.system.cashierservice.entity.TbSplitAccounts; + +public interface TbSplitAccountsMapper { + int deleteByPrimaryKey(Integer id); + + int insert(TbSplitAccounts record); + + int insertSelective(TbSplitAccounts record); + + TbSplitAccounts selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(TbSplitAccounts record); + + int updateByPrimaryKey(TbSplitAccounts record); +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbSystemCouponsMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbSystemCouponsMapper.java new file mode 100644 index 0000000..c66ed50 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbSystemCouponsMapper.java @@ -0,0 +1,25 @@ +package com.chaozhanggui.system.cashierservice.dao; + +import com.chaozhanggui.system.cashierservice.entity.TbSystemCoupons; +import org.apache.ibatis.annotations.Param; + +import java.math.BigDecimal; +import java.util.List; + +public interface TbSystemCouponsMapper { + int deleteByPrimaryKey(Integer id); + + int insert(TbSystemCoupons record); + + int insertSelective(TbSystemCoupons record); + + TbSystemCoupons selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(TbSystemCoupons record); + + int updateByPrimaryKey(TbSystemCoupons record); + + List selectAll(@Param("type") String type); + + int selectByAmount(@Param("orderNum") BigDecimal orderNum); +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbUserCouponsMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbUserCouponsMapper.java new file mode 100644 index 0000000..192a2e3 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbUserCouponsMapper.java @@ -0,0 +1,31 @@ +package com.chaozhanggui.system.cashierservice.dao; + +import com.chaozhanggui.system.cashierservice.entity.TbUserCoupons; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.springframework.stereotype.Component; + +import java.math.BigDecimal; +import java.util.List; + +@Component +@Mapper +public interface TbUserCouponsMapper { + int deleteByPrimaryKey(Integer id); + + int insert(TbUserCoupons record); + + int insertSelective(TbUserCoupons record); + + TbUserCoupons selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(TbUserCoupons record); + + int updateByPrimaryKey(TbUserCoupons record); + + List selectByUserId(@Param("userId") String userId,@Param("status") String status,@Param("amount") BigDecimal amount); + + TbUserCoupons selectByOrderId(@Param("orderId") Integer orderId); + + int selectByUserIdAndAmount(@Param("userId") String userId, @Param("orderNum") BigDecimal orderNum); +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbUserInfoMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbUserInfoMapper.java index 841dfa6..975d431 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbUserInfoMapper.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbUserInfoMapper.java @@ -4,6 +4,8 @@ import com.chaozhanggui.system.cashierservice.entity.TbUserInfo; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Component; +import java.util.List; + @Component @Mapper public interface TbUserInfoMapper { @@ -22,14 +24,6 @@ public interface TbUserInfoMapper { TbUserInfo selectByOpenId(String openId); - /** - * 通过手机号查询 - * @param phone - * @param source 公众号 WECHAT 小程序 WECHAT-APP 手机注册 TELEPHONE 移动端 APP - * @return - */ - TbUserInfo selectUserByPhone(String phone,String source); - /** * 查询来源为APP 未绑定微信用户的 用户数据 * @param phone @@ -38,4 +32,5 @@ public interface TbUserInfoMapper { TbUserInfo selectByPhone(String phone); + List selectAll(); } \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbWiningParamsMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbWiningParamsMapper.java new file mode 100644 index 0000000..803fc9f --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbWiningParamsMapper.java @@ -0,0 +1,21 @@ +package com.chaozhanggui.system.cashierservice.dao; + +import com.chaozhanggui.system.cashierservice.entity.TbWiningParams; + +import java.util.List; + +public interface TbWiningParamsMapper { + int deleteByPrimaryKey(Integer id); + + int insert(TbWiningParams record); + + int insertSelective(TbWiningParams record); + + TbWiningParams selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(TbWiningParams record); + + int updateByPrimaryKey(TbWiningParams record); + + List selectAll(); +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbWiningUserMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbWiningUserMapper.java new file mode 100644 index 0000000..8659d34 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbWiningUserMapper.java @@ -0,0 +1,26 @@ +package com.chaozhanggui.system.cashierservice.dao; + +import com.chaozhanggui.system.cashierservice.entity.TbWiningUser; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +@Mapper +public interface TbWiningUserMapper { + int deleteByPrimaryKey(Integer id); + + int insert(TbWiningUser record); + + int insertSelective(TbWiningUser record); + + TbWiningUser selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(TbWiningUser record); + + int updateByPrimaryKey(TbWiningUser record); + + List selectAllByTrade(@Param("day") String day); +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbYhqParamsMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbYhqParamsMapper.java new file mode 100644 index 0000000..0693c83 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbYhqParamsMapper.java @@ -0,0 +1,21 @@ +package com.chaozhanggui.system.cashierservice.dao; + +import com.chaozhanggui.system.cashierservice.entity.TbYhqParams; + +import java.util.List; + +public interface TbYhqParamsMapper { + int deleteByPrimaryKey(Integer id); + + int insert(TbYhqParams record); + + int insertSelective(TbYhqParams record); + + TbYhqParams selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(TbYhqParams record); + + int updateByPrimaryKey(TbYhqParams record); + + List selectAll(); +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/Enum/LogoEnum.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/Enum/LogoEnum.java new file mode 100644 index 0000000..4c04b56 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/Enum/LogoEnum.java @@ -0,0 +1,87 @@ +package com.chaozhanggui.system.cashierservice.entity.Enum; + +import com.github.pagehelper.util.StringUtil; + +/** + * @author 12847 + */ + +public enum LogoEnum { + url1(1,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/IMG_0299.PNG"), + url2(2,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/ffaab08f6a62103593646bf36dbaa24c.jpeg"), + url3(3,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/fe6c4572004f9aa7716bff89c4c56783.jpeg"), + url4(4,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/fb56ef7c59d46835e6ff4b5c494aed5a.jpeg"), + url5(5,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/f8469a7760c7f584ab55e47b60cd3829.jpeg"), + url6(6,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/f73810e20530a70dd068e0e0a82677d4.jpeg"), + url7(7,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/f66361c48515ba9b2a03d9d72829d675.jpeg"), + url8(8,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/f2be456f85849922ba838e7eb4694272.jpeg"), + url9(9,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/e9fca54f0320644291848338184b6c08.jpeg"), + url10(10,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/e9e574fdedb43831801697a610603044.jpeg"), + url11(11,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/e913ec3afe3520b9a638e16d298b401f.jpeg"), + url12(12,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/e87d19da0cb5af9b53f485117b665cc9.jpeg"), + url13(13,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/e847667f37d86dc4a48ffcf69bb1a964.jpeg"), + url14(14,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/e731f8a883ab1ef2a71487f2eb5b0e38.jpeg"), + url15(15,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/e681a9a281760f275f4b9d11c01a5869.jpeg"), + url16(16,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/e41fa3916c86d43904a66d1174b81080.jpeg"), + url17(17,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/e138425037e7ba3eded9ab828e3f39d2.jpeg"), + url18(18,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/e0d4e933083418e6c4795fb6bf5db628.jpeg"), + url19(19,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/e07b1933b0ad75f428339ffc79ee4fef.jpeg"), + url20(20,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/d4ac63680f417b49210aa54cf6e03e77.jpeg"), + url21(21,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/d44a8bccd46f4fa6c340e825bba5c338.jpeg"), + url22(22,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/cd794c0c5dd3b212e7c46eaa7c3a85cc.jpeg"), + url23(23,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/ccf1f255cd30c2aed0b421213df01863.jpeg"), + url24(24,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/cbe7897bee2d057eaaeaa1604d5bd167.jpeg"), + url25(25,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/cae19ed2c2c1c749e388730ef1cbb596.jpeg"), + url26(26,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/c90a7e5d7a9a95a48dac8aecfab5c8e1.jpeg"), + url27(27,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/c72ec32dbb7c0a42ca6a0a483a0d99ab.jpeg"), + url28(28,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/c72ec32dbb7c0a42ca6a0a483a0d99ab.jpeg"), + url29(29,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/c451f57dde1fcbbe4afe5766184084da.jpeg"), + url30(30,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/a9a9e9eb047009f79bc22290470c2932.jpeg"), + url31(31,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/aef489a444793e37e2f33aeb3fe1fe13.jpeg"), + url32(32,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/b0f4a2d7ab851fb2ea01446b722c5631.jpeg"), + url33(33,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/b2d643c11850042ff2932451c84940c3.jpeg"), + url34(34,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/bdf1ebd620f759f703631b805216ca11.jpeg"), + url35(35,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/be1e70097583d1a08a9951925d66ef33.jpeg"), + url36(36,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/c3f38f6604713f13474a5e2f1145e481.jpeg"), + url37(37,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/c27da8b2c154998ebf7300c49cef649a.jpeg"), + url38(38,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/c26400a670209b60abcd28bfc6d22171.jpeg"), + url39(39,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/a906414986b1bee60cec709dabf2103b.jpeg"), + url40(40,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/a6d8629c155b59814e4d772fb5e6ec6a.jpeg"), + url41(41,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/a6a78d2a64c49cf62e37475eb66e351c.jpeg"), + url42(42,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/a571ccde02b075656f354b593533b00c.jpeg"), + url43(43,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/a0be3632c238d1a8e24e51ff8942efc6.jpeg"), + url44(44,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/9fca88b43ed09ddbeb4803ceab4f356f.jpeg"), + url45(45,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/86ad712e29369b9f56ca93a94f7a5d67.jpeg"), + url46(46,"https://cashier-oss.oss-cn-beijing.aliyuncs.com/status/%E6%BE%B6%E6%9D%91%E5%84%9A/88d4ca4146196992b48a52f62a690bf0.jpeg"), + ; + + private Integer key; + + private String url; + + public Integer getKey() { + return key; + } + + public String getUrl() { + return url; + } + + LogoEnum(Integer key, String url) { + this.key = key; + this.url = url; + } + + public static String getValueByKey(Integer key) { + if(key == null){ + return ""; + } + LogoEnum[] urlEnums = values(); + for (LogoEnum logo : urlEnums) { + if (logo.key.equals(key)) { + return logo.getUrl(); + } + } + return ""; + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/SysDict.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/SysDict.java index bc3797d..cb25ae5 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/SysDict.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/SysDict.java @@ -1,88 +1,30 @@ package com.chaozhanggui.system.cashierservice.entity; -import java.io.Serializable; -import java.util.Date; +import lombok.Data; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +@Data public class SysDict implements Serializable { + private Long dictId; + private String dictName; + private String name; - private String description; + /** + * 是否有子类0否1是 + */ + private Object isChild; - private String createBy; + /** + * 值 + */ + private String value; - private String updateBy; - - private Date createTime; - - private Date updateTime; - - private Integer isChild; - - private static final long serialVersionUID = 1L; - - public Integer getIsChild() { - return isChild; - } - - public void setIsChild(Integer isChild) { - this.isChild = isChild; - } - - public Long getDictId() { - return dictId; - } - - public void setDictId(Long dictId) { - this.dictId = dictId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name == null ? null : name.trim(); - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description == null ? null : description.trim(); - } - - public String getCreateBy() { - return createBy; - } - - public void setCreateBy(String createBy) { - this.createBy = createBy == null ? null : createBy.trim(); - } - - public String getUpdateBy() { - return updateBy; - } - - public void setUpdateBy(String updateBy) { - this.updateBy = updateBy == null ? null : updateBy.trim(); - } - - public Date getCreateTime() { - return createTime; - } - - public void setCreateTime(Date createTime) { - this.createTime = createTime; - } - - public Date getUpdateTime() { - return updateTime; - } - - public void setUpdateTime(Date updateTime) { - this.updateTime = updateTime; - } + private List detail=new ArrayList<>(); } \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/SysDictDetail.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/SysDictDetail.java index 6e74012..7a43ee2 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/SysDictDetail.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/SysDictDetail.java @@ -1,98 +1,15 @@ package com.chaozhanggui.system.cashierservice.entity; +import lombok.Data; + import java.io.Serializable; import java.util.Date; +@Data public class SysDictDetail implements Serializable { - private Long detailId; - - private Long dictId; + private String dictName; private String label; private String value; - - private Integer dictSort; - - private String createBy; - - private String updateBy; - - private Date createTime; - - private Date updateTime; - - private static final long serialVersionUID = 1L; - - public Long getDetailId() { - return detailId; - } - - public void setDetailId(Long detailId) { - this.detailId = detailId; - } - - public Long getDictId() { - return dictId; - } - - public void setDictId(Long dictId) { - this.dictId = dictId; - } - - public String getLabel() { - return label; - } - - public void setLabel(String label) { - this.label = label == null ? null : label.trim(); - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value == null ? null : value.trim(); - } - - public Integer getDictSort() { - return dictSort; - } - - public void setDictSort(Integer dictSort) { - this.dictSort = dictSort; - } - - public String getCreateBy() { - return createBy; - } - - public void setCreateBy(String createBy) { - this.createBy = createBy == null ? null : createBy.trim(); - } - - public String getUpdateBy() { - return updateBy; - } - - public void setUpdateBy(String updateBy) { - this.updateBy = updateBy == null ? null : updateBy.trim(); - } - - public Date getCreateTime() { - return createTime; - } - - public void setCreateTime(Date createTime) { - this.createTime = createTime; - } - - public Date getUpdateTime() { - return updateTime; - } - - public void setUpdateTime(Date updateTime) { - this.updateTime = updateTime; - } } \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbActivate.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbActivate.java new file mode 100644 index 0000000..c223bfc --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbActivate.java @@ -0,0 +1,78 @@ +package com.chaozhanggui.system.cashierservice.entity; + +import java.io.Serializable; +import java.math.BigDecimal; + +public class TbActivate implements Serializable { + private Integer id; + + private Integer shopId; + + private Integer minNum; + + private Integer maxNum; + + private BigDecimal handselNum; + + private String handselType; + + private String isDel; + + private static final long serialVersionUID = 1L; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public Integer getShopId() { + return shopId; + } + + public void setShopId(Integer shopId) { + this.shopId = shopId; + } + + public Integer getMinNum() { + return minNum; + } + + public void setMinNum(Integer minNum) { + this.minNum = minNum; + } + + public Integer getMaxNum() { + return maxNum; + } + + public void setMaxNum(Integer maxNum) { + this.maxNum = maxNum; + } + + public BigDecimal getHandselNum() { + return handselNum; + } + + public void setHandselNum(BigDecimal handselNum) { + this.handselNum = handselNum; + } + + public String getHandselType() { + return handselType; + } + + public void setHandselType(String handselType) { + this.handselType = handselType == null ? null : handselType.trim(); + } + + public String getIsDel() { + return isDel; + } + + public void setIsDel(String isDel) { + this.isDel = isDel == null ? null : isDel.trim(); + } +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbCashierCart.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbCashierCart.java index 4e8ab74..0c99e3a 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbCashierCart.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbCashierCart.java @@ -1,6 +1,7 @@ package com.chaozhanggui.system.cashierservice.entity; import lombok.Data; +import org.apache.commons.lang3.StringUtils; import java.io.Serializable; import java.math.BigDecimal; @@ -60,4 +61,12 @@ public class TbCashierCart implements Serializable { private TbProductSpec tbProductSpec; private static final long serialVersionUID = 1L; + + public String getSkuName() { + if(StringUtils.isNotBlank(skuName)){ + return skuName; + }else { + return ""; + } + } } \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbCouponCategory.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbCouponCategory.java new file mode 100644 index 0000000..3afa452 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbCouponCategory.java @@ -0,0 +1,71 @@ +package com.chaozhanggui.system.cashierservice.entity; + +import java.util.Date; +import java.io.Serializable; + +/** + * 团购卷分类(TbCouponCategory)实体类 + * + * @author ww + * @since 2024-04-24 14:09:16 + */ +public class TbCouponCategory implements Serializable { + private static final long serialVersionUID = -45350278241700844L; + + private Integer id; + /** + * 分类名称 + */ + private String name; + + private Date createTime; + + private Date updateTime; + /** + * 0:不展示;1:展示; + */ + private Integer status; + + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public Date getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + +} + diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbGroupOrderCoupon.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbGroupOrderCoupon.java new file mode 100644 index 0000000..dde37a8 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbGroupOrderCoupon.java @@ -0,0 +1,101 @@ +package com.chaozhanggui.system.cashierservice.entity; + +import java.io.Serializable; +import java.math.BigDecimal; + +/** + * 团购卷 卷码表(TbGroupOrderCoupon)实体类 + * + * @author ww + * @since 2024-05-06 14:39:59 + */ +public class TbGroupOrderCoupon implements Serializable { + private static final long serialVersionUID = -35424376349743542L; + + private Integer id; + /** + * 团购订单id + */ + private Integer orderId; + /** + * 团购卷码 + */ + private String couponNo; + /** + * 是否已退款 + * 0:否 + * 1:是 + */ + private Integer isRefund; + /** + * 退款金额 + */ + private BigDecimal refundAmount; + /** + * 退款原因 + */ + private String refundReason; + /** + * 退款说明 + */ + private String refundDesc; + + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public Integer getOrderId() { + return orderId; + } + + public void setOrderId(Integer orderId) { + this.orderId = orderId; + } + + public String getCouponNo() { + return couponNo; + } + + public void setCouponNo(String couponNo) { + this.couponNo = couponNo; + } + + public Integer getIsRefund() { + return isRefund; + } + + public void setIsRefund(Integer isRefund) { + this.isRefund = isRefund; + } + + public BigDecimal getRefundAmount() { + return refundAmount; + } + + public void setRefundAmount(BigDecimal refundAmount) { + this.refundAmount = refundAmount; + } + + public String getRefundReason() { + return refundReason; + } + + public void setRefundReason(String refundReason) { + this.refundReason = refundReason; + } + + public String getRefundDesc() { + return refundDesc; + } + + public void setRefundDesc(String refundDesc) { + this.refundDesc = refundDesc; + } + +} + diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbGroupOrderInfo.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbGroupOrderInfo.java new file mode 100644 index 0000000..7ed0ada --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbGroupOrderInfo.java @@ -0,0 +1,123 @@ +package com.chaozhanggui.system.cashierservice.entity; + +import lombok.Data; + +import java.math.BigDecimal; +import java.util.Date; +import java.io.Serializable; + +@Data +public class TbGroupOrderInfo implements Serializable { + private static final long serialVersionUID = -11810357048433715L; + /** + * id + */ + private Integer id; + /** + * 订单编号 + */ + private String orderNo; + private Integer merchantId; + /** + * 商户Id + */ + private Integer shopId; + /** + * 用户id + */ + private Integer userId; + /** + * 商品id + */ + private Integer proId; + /** + * 商品图 + */ + private String proImg; + /** + * 商品名称 + */ + private String proName; + /** + * 团购卷到期日期 + */ + private Date expDate; + /** + * 订单类型 预留字段 + */ + private String orderType; + /** + * 支付方式 wechatPay微信支付,aliPay支付宝支付 + */ + private String payType; + /** + * 订单金额 + */ + private BigDecimal orderAmount; + /** + * 优惠金额 + */ + private BigDecimal saveAmount; + /** + * 实付金额 + */ + private BigDecimal payAmount; + /** + * 退单金额 + */ + private BigDecimal refundAmount; + /** + * 数量 + */ + private Integer number; + + private Integer refundNumber; + /** + * 订单状态 + * 状态: unpaid-待付款;unused-待使用;closed-已完成;refunding-退款中;refund-已退款;cancelled-已取消; + */ + private String status; + /** + * 备注 + */ + private String remark; + /** + * 手机号 + */ + private String phone; + /** + * 付款时间 + */ + private Date payTime; + /** + * 是否支持退款 0:不支持 1:支持 + */ + private Integer refundAble; + /** + * 创建时间 + */ + private Date createTime; + /** + * 卷码核销员 + */ + private String verifier; + /** + * 更新时间 + */ + private Date updateTime; + /** + * 支付订单号 + */ + private String payOrderNo; + /** + * 交易日期 + */ + private Date tradeDay; + /** + * 原订单id 退单 + */ + private Integer source; + + +} + diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbIntegral.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbIntegral.java new file mode 100644 index 0000000..ed52c85 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbIntegral.java @@ -0,0 +1,69 @@ +package com.chaozhanggui.system.cashierservice.entity; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.Date; + +public class TbIntegral implements Serializable { + private Integer id; + + private String userId; + + private BigDecimal num; + + private String status; + + private Date createTime; + + private Date updateTime; + + private static final long serialVersionUID = 1L; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId == null ? null : userId.trim(); + } + + public BigDecimal getNum() { + return num; + } + + public void setNum(BigDecimal num) { + this.num = num; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status == null ? null : status.trim(); + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public Date getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbIntegralFlow.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbIntegralFlow.java new file mode 100644 index 0000000..888295e --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbIntegralFlow.java @@ -0,0 +1,59 @@ +package com.chaozhanggui.system.cashierservice.entity; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.Date; + +public class TbIntegralFlow implements Serializable { + private Integer id; + + private String userId; + + private BigDecimal num; + + private Date createTime; + + private Date updateTime; + + private static final long serialVersionUID = 1L; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId == null ? null : userId.trim(); + } + + public BigDecimal getNum() { + return num; + } + + public void setNum(BigDecimal num) { + this.num = num; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public Date getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbMerchantCoupon.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbMerchantCoupon.java index 8e922e5..4f5bee0 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbMerchantCoupon.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbMerchantCoupon.java @@ -41,6 +41,7 @@ public class TbMerchantCoupon implements Serializable { * 限领数量 */ private String limitNumber; + private String useNumber; /** * 发放数量 */ @@ -135,6 +136,14 @@ public class TbMerchantCoupon implements Serializable { private String merchantId; + public String getUseNumber() { + return useNumber; + } + + public void setUseNumber(String useNumber) { + this.useNumber = useNumber; + } + public Integer getId() { return id; } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbMerchantThirdApply.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbMerchantThirdApply.java index b3c7922..8e9901e 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbMerchantThirdApply.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbMerchantThirdApply.java @@ -21,6 +21,13 @@ public class TbMerchantThirdApply implements Serializable { private String appToken; + private String smallAppid; + + private String storeId; + + + + private static final long serialVersionUID = 1L; public Integer getId() { @@ -94,4 +101,20 @@ public class TbMerchantThirdApply implements Serializable { public void setAppToken(String appToken) { this.appToken = appToken == null ? null : appToken.trim(); } + + public String getSmallAppid() { + return smallAppid; + } + + public void setSmallAppid(String smallAppid) { + this.smallAppid = smallAppid; + } + + public String getStoreId() { + return storeId; + } + + public void setStoreId(String storeId) { + this.storeId = storeId; + } } \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbOrderInfo.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbOrderInfo.java index c2e8b82..60a3dcf 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbOrderInfo.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbOrderInfo.java @@ -95,9 +95,36 @@ public class TbOrderInfo implements Serializable { private String remark; private String tableName; private String masterId; + private String isBuyCoupon; + private String isUseCoupon; private Integer totalNumber; private List detailList; + private String winnnerNo; + private String isWinner; + + //根据状态返回 需付款 已付款 未付款 已退 + private String description; + + public void setDescription() { + switch (status) { + case "closed": + this.description = "已付款"; + break; + case "refund": + this.description = "已退款"; + break; + case "paying": + case "unpaid": + this.description = "需付款"; + break; + default: + this.description = ""; + break; + } + } + + private String outNumber; private static final long serialVersionUID = 1L; public TbOrderInfo(){ super(); diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbParams.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbParams.java new file mode 100644 index 0000000..5aa9414 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbParams.java @@ -0,0 +1,19 @@ +package com.chaozhanggui.system.cashierservice.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; + + +@Data +public class TbParams implements Serializable { + private Integer id; + + private BigDecimal integralRatio; + private BigDecimal twoRatio; + + private BigDecimal tradeRatio; + + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbPlatformDict.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbPlatformDict.java index 55e42cf..7c45819 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbPlatformDict.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbPlatformDict.java @@ -12,10 +12,17 @@ public class TbPlatformDict implements Serializable { private static final long serialVersionUID = -34581903392247717L; private Integer id; + /** + * 标签前图标 + */ + private String shareImg; /** * 描述 同类型下 name唯一 */ private String name; + private String value; + private String fontColor; + private String backColor; /** * homeDistrict--金刚区(首页) carousel--轮播图 tag--标签 */ @@ -24,10 +31,6 @@ public class TbPlatformDict implements Serializable { * 封面图 */ private String coverImg; - /** - * 分享图 - */ - private String shareImg; /** * 视频URL地址 */ @@ -36,10 +39,8 @@ public class TbPlatformDict implements Serializable { * 视频封面图 */ private String videoCoverImg; - /** - * 相对跳转地址 - */ - private String relUrl; + + private String jumpType; /** * 绝对跳转地址 */ @@ -78,6 +79,22 @@ public class TbPlatformDict implements Serializable { this.id = id; } + public String getFontColor() { + return fontColor; + } + + public void setFontColor(String fontColor) { + this.fontColor = fontColor; + } + + public String getBackColor() { + return backColor; + } + + public void setBackColor(String backColor) { + this.backColor = backColor; + } + public String getName() { return name; } @@ -86,6 +103,14 @@ public class TbPlatformDict implements Serializable { this.name = name; } + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + public String getType() { return type; } @@ -126,12 +151,12 @@ public class TbPlatformDict implements Serializable { this.videoCoverImg = videoCoverImg; } - public String getRelUrl() { - return relUrl; + public String getJumpType() { + return jumpType; } - public void setRelUrl(String relUrl) { - this.relUrl = relUrl; + public void setJumpType(String jumpType) { + this.jumpType = jumpType; } public String getAbsUrl() { diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbProduct.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbProduct.java index c828f9c..c8ab10c 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbProduct.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbProduct.java @@ -40,6 +40,8 @@ public class TbProduct implements Serializable { private String shareImg; + private String images; + private String videoCoverImg; private Integer sort; @@ -127,6 +129,16 @@ public class TbProduct implements Serializable { private String specTableHeaders; private String cartNumber="0"; + private String groupCategoryId; + + + public String getImages() { + return images; + } + + public void setImages(String images) { + this.images = images; + } public String getCartNumber() { return cartNumber; @@ -626,6 +638,15 @@ public class TbProduct implements Serializable { return specTableHeaders; } + public String getGroupCategoryId() { + return groupCategoryId; + } + + public void setGroupCategoryId(String groupCategoryId) { + this.groupCategoryId = groupCategoryId; + } + + public void setSpecTableHeaders(String specTableHeaders) { this.specTableHeaders = specTableHeaders == null ? null : specTableHeaders.trim(); } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbPurchaseNotice.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbPurchaseNotice.java new file mode 100644 index 0000000..1085810 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbPurchaseNotice.java @@ -0,0 +1,160 @@ +package com.chaozhanggui.system.cashierservice.entity; + +import java.io.Serializable; + +/** + * 购买须知(关联tb_merchant_coupon)(TbPurchaseNotice)实体类 + * + * @author ww + * @since 2024-04-11 10:00:23 + */ +public class TbPurchaseNotice implements Serializable { + private static final long serialVersionUID = 811103518413221387L; + /** + * 自增 + */ + private Integer id; + /** + * 商户卷Id + */ + private Integer couponId; + /** + * 使用日期说明 + */ + private String dateUsed; + /** + * 可用时间说明 + */ + private String availableTime; + /** + * 预约方式 + */ + private String bookingType; + /** + * 退款说明 + */ + private String refundPolicy; + /** + * 使用规则 + */ + private String usageRules; + /** + * 发票说明 + */ + private String invoiceInfo; + /** + * 团购价说明 + */ + private String groupPurInfo; + /** + * 门市价/划线价说明 + */ + private String marketPriceInfo; + /** + * 折扣说明 + */ + private String discountInfo; + /** + * 平台温馨提示 + */ + private String platformTips; + + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public Integer getCouponId() { + return couponId; + } + + public void setCouponId(Integer couponId) { + this.couponId = couponId; + } + + public String getDateUsed() { + return dateUsed; + } + + public void setDateUsed(String dateUsed) { + this.dateUsed = dateUsed; + } + + public String getAvailableTime() { + return availableTime; + } + + public void setAvailableTime(String availableTime) { + this.availableTime = availableTime; + } + + public String getBookingType() { + return bookingType; + } + + public void setBookingType(String bookingType) { + this.bookingType = bookingType; + } + + public String getRefundPolicy() { + return refundPolicy; + } + + public void setRefundPolicy(String refundPolicy) { + this.refundPolicy = refundPolicy; + } + + public String getUsageRules() { + return usageRules; + } + + public void setUsageRules(String usageRules) { + this.usageRules = usageRules; + } + + public String getInvoiceInfo() { + return invoiceInfo; + } + + public void setInvoiceInfo(String invoiceInfo) { + this.invoiceInfo = invoiceInfo; + } + + public String getGroupPurInfo() { + return groupPurInfo; + } + + public void setGroupPurInfo(String groupPurInfo) { + this.groupPurInfo = groupPurInfo; + } + + public String getMarketPriceInfo() { + return marketPriceInfo; + } + + public void setMarketPriceInfo(String marketPriceInfo) { + this.marketPriceInfo = marketPriceInfo; + } + + public String getDiscountInfo() { + return discountInfo; + } + + public void setDiscountInfo(String discountInfo) { + this.discountInfo = discountInfo; + } + + public String getPlatformTips() { + return platformTips; + } + + public void setPlatformTips(String platformTips) { + this.platformTips = platformTips; + } + +} + diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbReleaseFlow.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbReleaseFlow.java new file mode 100644 index 0000000..34414ed --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbReleaseFlow.java @@ -0,0 +1,30 @@ +package com.chaozhanggui.system.cashierservice.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.Date; + +@Data +public class TbReleaseFlow implements Serializable { + private Integer id; + + private String userId; + + private BigDecimal num; + + private String type; + private String operationType; + + private String remark; + private String nickName; + + private String fromSource; + + private Date createTime; + private String createTr; + private String openId; + + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbShopInfo.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbShopInfo.java index 54863e8..2d8b7e9 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbShopInfo.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbShopInfo.java @@ -1,8 +1,12 @@ package com.chaozhanggui.system.cashierservice.entity; +import lombok.Data; + import java.io.Serializable; import java.math.BigDecimal; + +@Data public class TbShopInfo implements Serializable { private Integer id; @@ -58,6 +62,8 @@ public class TbShopInfo implements Serializable { private String industryName; + private String businessStartDay; + private String businessEndDay; private String businessTime; private String postTime; @@ -95,366 +101,16 @@ public class TbShopInfo implements Serializable { * 商家二维码 */ private String shopQrcode; - - public String getShopQrcode() { - return shopQrcode; - } - - public void setShopQrcode(String shopQrcode) { - this.shopQrcode = shopQrcode; - } + private String isOpenYhq; + private Byte isUseVip; + /** + * 商户标签 + */ + private String tag; + private String provinces; + private String cities; + private String districts; private static final long serialVersionUID = 1L; - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getAccount() { - return account; - } - - public void setAccount(String account) { - this.account = account == null ? null : account.trim(); - } - - public String getShopCode() { - return shopCode; - } - - public void setShopCode(String shopCode) { - this.shopCode = shopCode == null ? null : shopCode.trim(); - } - - public String getSubTitle() { - return subTitle; - } - - public void setSubTitle(String subTitle) { - this.subTitle = subTitle == null ? null : subTitle.trim(); - } - - public String getMerchantId() { - return merchantId; - } - - public void setMerchantId(String merchantId) { - this.merchantId = merchantId == null ? null : merchantId.trim(); - } - - public String getShopName() { - return shopName; - } - - public void setShopName(String shopName) { - this.shopName = shopName == null ? null : shopName.trim(); - } - - public String getChainName() { - return chainName; - } - - public void setChainName(String chainName) { - this.chainName = chainName == null ? null : chainName.trim(); - } - - public String getBackImg() { - return backImg; - } - - public void setBackImg(String backImg) { - this.backImg = backImg == null ? null : backImg.trim(); - } - - public String getFrontImg() { - return frontImg; - } - - public void setFrontImg(String frontImg) { - this.frontImg = frontImg == null ? null : frontImg.trim(); - } - - public String getContactName() { - return contactName; - } - - public void setContactName(String contactName) { - this.contactName = contactName == null ? null : contactName.trim(); - } - - public String getPhone() { - return phone; - } - - public void setPhone(String phone) { - this.phone = phone == null ? null : phone.trim(); - } - - public String getLogo() { - return logo; - } - - public void setLogo(String logo) { - this.logo = logo == null ? null : logo.trim(); - } - - public Byte getIsDeposit() { - return isDeposit; - } - - public void setIsDeposit(Byte isDeposit) { - this.isDeposit = isDeposit; - } - - public Byte getIsSupply() { - return isSupply; - } - - public void setIsSupply(Byte isSupply) { - this.isSupply = isSupply; - } - - public String getCoverImg() { - return coverImg; - } - - public void setCoverImg(String coverImg) { - this.coverImg = coverImg == null ? null : coverImg.trim(); - } - - public String getShareImg() { - return shareImg; - } - - public void setShareImg(String shareImg) { - this.shareImg = shareImg == null ? null : shareImg.trim(); - } - - public String getDetail() { - return detail; - } - - public void setDetail(String detail) { - this.detail = detail == null ? null : detail.trim(); - } - - public String getLat() { - return lat; - } - - public void setLat(String lat) { - this.lat = lat == null ? null : lat.trim(); - } - - public String getLng() { - return lng; - } - - public void setLng(String lng) { - this.lng = lng == null ? null : lng.trim(); - } - - public String getMchId() { - return mchId; - } - - public void setMchId(String mchId) { - this.mchId = mchId == null ? null : mchId.trim(); - } - - public String getRegisterType() { - return registerType; - } - - public void setRegisterType(String registerType) { - this.registerType = registerType == null ? null : registerType.trim(); - } - - public Byte getIsWxMaIndependent() { - return isWxMaIndependent; - } - - public void setIsWxMaIndependent(Byte isWxMaIndependent) { - this.isWxMaIndependent = isWxMaIndependent; - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address == null ? null : address.trim(); - } - - public String getCity() { - return city; - } - - public void setCity(String city) { - this.city = city == null ? null : city.trim(); - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type == null ? null : type.trim(); - } - - public String getIndustry() { - return industry; - } - - public void setIndustry(String industry) { - this.industry = industry == null ? null : industry.trim(); - } - - public String getIndustryName() { - return industryName; - } - - public void setIndustryName(String industryName) { - this.industryName = industryName == null ? null : industryName.trim(); - } - - public String getBusinessTime() { - return businessTime; - } - - public void setBusinessTime(String businessTime) { - this.businessTime = businessTime == null ? null : businessTime.trim(); - } - - public String getPostTime() { - return postTime; - } - - public void setPostTime(String postTime) { - this.postTime = postTime == null ? null : postTime.trim(); - } - - public BigDecimal getPostAmountLine() { - return postAmountLine; - } - - public void setPostAmountLine(BigDecimal postAmountLine) { - this.postAmountLine = postAmountLine; - } - - public Byte getOnSale() { - return onSale; - } - - public void setOnSale(Byte onSale) { - this.onSale = onSale; - } - - public Byte getSettleType() { - return settleType; - } - - public void setSettleType(Byte settleType) { - this.settleType = settleType; - } - - public String getSettleTime() { - return settleTime; - } - - public void setSettleTime(String settleTime) { - this.settleTime = settleTime == null ? null : settleTime.trim(); - } - - public Integer getEnterAt() { - return enterAt; - } - - public void setEnterAt(Integer enterAt) { - this.enterAt = enterAt; - } - - public Long getExpireAt() { - return expireAt; - } - - public void setExpireAt(Long expireAt) { - this.expireAt = expireAt; - } - - public Byte getStatus() { - return status; - } - - public void setStatus(Byte status) { - this.status = status; - } - - public Float getAverage() { - return average; - } - - public void setAverage(Float average) { - this.average = average; - } - - public Integer getOrderWaitPayMinute() { - return orderWaitPayMinute; - } - - public void setOrderWaitPayMinute(Integer orderWaitPayMinute) { - this.orderWaitPayMinute = orderWaitPayMinute; - } - - public Integer getSupportDeviceNumber() { - return supportDeviceNumber; - } - - public void setSupportDeviceNumber(Integer supportDeviceNumber) { - this.supportDeviceNumber = supportDeviceNumber; - } - - public Byte getDistributeLevel() { - return distributeLevel; - } - - public void setDistributeLevel(Byte distributeLevel) { - this.distributeLevel = distributeLevel; - } - - public Long getCreatedAt() { - return createdAt; - } - - public void setCreatedAt(Long createdAt) { - this.createdAt = createdAt; - } - - public Long getUpdatedAt() { - return updatedAt; - } - - public void setUpdatedAt(Long updatedAt) { - this.updatedAt = updatedAt; - } - - public String getProxyId() { - return proxyId; - } - - public void setProxyId(String proxyId) { - this.proxyId = proxyId == null ? null : proxyId.trim(); - } - - public String getView() { - return view; - } - - public void setView(String view) { - this.view = view == null ? null : view.trim(); - } } \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbShopUser.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbShopUser.java index c1a688d..1c58321 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbShopUser.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbShopUser.java @@ -42,6 +42,10 @@ public class TbShopUser implements Serializable { private String code; + + private String dynamicCode; + + private Byte isAttention; private Integer attentionAt; @@ -214,6 +218,15 @@ public class TbShopUser implements Serializable { this.code = code == null ? null : code.trim(); } + public String getDynamicCode() { + return dynamicCode; + } + + public void setDynamicCode(String dynamicCode) { + this.dynamicCode = dynamicCode; + } + + public Byte getIsAttention() { return isAttention; } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbShopUserFlow.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbShopUserFlow.java index d70e58c..730cd8f 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbShopUserFlow.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbShopUserFlow.java @@ -19,6 +19,8 @@ public class TbShopUserFlow implements Serializable { private Date createTime; + private String type; + private static final long serialVersionUID = 1L; public Integer getId() { @@ -76,4 +78,12 @@ public class TbShopUserFlow implements Serializable { public void setCreateTime(Date createTime) { this.createTime = createTime; } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type == null ? null : type.trim(); + } } \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbShopVideo.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbShopVideo.java new file mode 100644 index 0000000..6123ff4 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbShopVideo.java @@ -0,0 +1,159 @@ +package com.chaozhanggui.system.cashierservice.entity; + +import java.util.Date; +import java.io.Serializable; + +/** + * 商户视频号(TbShopVideo)实体类 + * + * @author ww + * @since 2024-04-12 14:50:09 + */ +public class TbShopVideo implements Serializable { + private static final long serialVersionUID = 521986900418854409L; + + private Integer id; + /** + * 店铺id + */ + private Integer shopId; + /** + * 1-公众号;2-小程序;3-视频号 + */ + private Integer type; + /** + * 描述信息 + */ + private String name; + /** + * 渠道id(视频号id) + */ + private Integer channelId; + /** + * 创建时间 + */ + private Date createdTime; + /** + * 更新时间 + */ + private Date updateTime; + /** + * 资源Id(视频号id)(公众号id) + */ + private Integer sourceId; + /** + * 资源地址 + */ + private String sourceUrl; + /** + * 0:关闭;1:开启; + */ + private Integer status; + /** + * 视频id + */ + private Integer videoId; + /** + * 视频地址 + */ + private String videoUrl; + + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public Integer getShopId() { + return shopId; + } + + public void setShopId(Integer shopId) { + this.shopId = shopId; + } + + public Integer getType() { + return type; + } + + public void setType(Integer type) { + this.type = type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getChannelId() { + return channelId; + } + + public void setChannelId(Integer channelId) { + this.channelId = channelId; + } + + public Date getCreatedTime() { + return createdTime; + } + + public void setCreatedTime(Date createdTime) { + this.createdTime = createdTime; + } + + public Date getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + public Integer getSourceId() { + return sourceId; + } + + public void setSourceId(Integer sourceId) { + this.sourceId = sourceId; + } + + public String getSourceUrl() { + return sourceUrl; + } + + public void setSourceUrl(String sourceUrl) { + this.sourceUrl = sourceUrl; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public Integer getVideoId() { + return videoId; + } + + public void setVideoId(Integer videoId) { + this.videoId = videoId; + } + + public String getVideoUrl() { + return videoUrl; + } + + public void setVideoUrl(String videoUrl) { + this.videoUrl = videoUrl; + } + +} + diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbSplitAccounts.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbSplitAccounts.java new file mode 100644 index 0000000..89408a0 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbSplitAccounts.java @@ -0,0 +1,34 @@ +package com.chaozhanggui.system.cashierservice.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.Date; + +@Data +//分配金额 +public class TbSplitAccounts implements Serializable { + private Integer id; + + private Integer merchantId;//商户ID + + private Integer shopId;//店铺ID + + private BigDecimal couponsPrice;//优惠券价值 + + private BigDecimal conponsAmount;//优惠券面额 + private BigDecimal originAmount;// + + private String isSplit; + + private BigDecimal orderAmount; + + private Date createTime; + + private Date splitTime; + + private String tradeDay; + + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbSystemCoupons.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbSystemCoupons.java new file mode 100644 index 0000000..6f03d88 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbSystemCoupons.java @@ -0,0 +1,30 @@ +package com.chaozhanggui.system.cashierservice.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.Date; + +@Data +public class TbSystemCoupons implements Serializable { + private Integer id; + + private String name; + + private BigDecimal couponsPrice; + + private BigDecimal couponsAmount; + + private String status; + private String typeName; + + private Date createTime; + + private Date updateTime; + private Integer dayNum; + + private Date endTime; + + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbUserCoupons.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbUserCoupons.java new file mode 100644 index 0000000..6f59527 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbUserCoupons.java @@ -0,0 +1,31 @@ +package com.chaozhanggui.system.cashierservice.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.Date; + +@Data +public class TbUserCoupons implements Serializable { + private Integer id; + + private String userId; + private Integer orderId; + + private BigDecimal couponsPrice; + + private BigDecimal couponsAmount; + private TbOrderInfo orderInfo; + + private String status; + private String isDouble; + + private Date createTime; + + private Date updateTime; + + private Date endTime; + + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbUserInfo.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbUserInfo.java index fab566b..e449864 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbUserInfo.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbUserInfo.java @@ -5,7 +5,6 @@ import java.math.BigDecimal; public class TbUserInfo implements Serializable { private Integer id; - private Integer userId; private BigDecimal amount; @@ -98,15 +97,12 @@ public class TbUserInfo implements Serializable { private String avatar = ""; - private String phone=""; + private String isPwd; - public String getPhone() { - return phone; - } + private String pwd; + + private String custPhone="400-6666-389"; - public void setPhone(String phone) { - this.phone = phone; - } public String getAvatar() { return avatar; @@ -116,6 +112,14 @@ public class TbUserInfo implements Serializable { this.avatar = avatar; } + public String getCustPhone() { + return custPhone; + } + + public void setCustPhone(String custPhone) { + this.custPhone = custPhone; + } + private static final long serialVersionUID = 1L; public Integer getId() { @@ -478,14 +482,6 @@ public class TbUserInfo implements Serializable { this.grandParentId = grandParentId == null ? null : grandParentId.trim(); } - public Integer getUserId() { - return userId; - } - - public void setUserId(Integer userId) { - this.userId = userId; - } - public String getPassword() { return password; } @@ -493,4 +489,20 @@ public class TbUserInfo implements Serializable { public void setPassword(String password) { this.password = password; } + + public String getIsPwd() { + return isPwd; + } + + public void setIsPwd(String isPwd) { + this.isPwd = isPwd; + } + + public String getPwd() { + return pwd; + } + + public void setPwd(String pwd) { + this.pwd = pwd; + } } \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbWiningParams.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbWiningParams.java new file mode 100644 index 0000000..6c513c1 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbWiningParams.java @@ -0,0 +1,22 @@ +package com.chaozhanggui.system.cashierservice.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; + +@Data +public class TbWiningParams implements Serializable { + private Integer id; + + private BigDecimal minPrice; + + private BigDecimal maxPrice; + + private Integer winingNum; + + private Integer winingUserNum; + private String status; + + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbWiningUser.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbWiningUser.java new file mode 100644 index 0000000..3855259 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbWiningUser.java @@ -0,0 +1,54 @@ +package com.chaozhanggui.system.cashierservice.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.Date; + +@Data +public class TbWiningUser implements Serializable { + private Integer id; + + private String userName; + + private String orderNo; + + private BigDecimal orderAmount; + + private String isUser; + + private Date createTime; + + private String isRefund; + + private BigDecimal refundAmount; + + private String refundNo; + + private String refundPayType; + + private String tradeDay; + + private Date refundTime; + + + private static final long serialVersionUID = 1L; + public TbWiningUser(){ + super(); + } + public TbWiningUser(String userName,String orderNo,BigDecimal orderAmount, + String isUser,String tradeDay){ + this.createTime = new Date(); + this.userName = userName; + this.orderNo = orderNo; + this.orderAmount = orderAmount; + this.isUser = isUser; + this.tradeDay = tradeDay; + this.isRefund = "true"; + this.refundAmount = BigDecimal.ZERO; + this.refundPayType = "WX"; + + + } +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbYhqParams.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbYhqParams.java new file mode 100644 index 0000000..41e19af --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/TbYhqParams.java @@ -0,0 +1,20 @@ +package com.chaozhanggui.system.cashierservice.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; + +@Data +public class TbYhqParams implements Serializable { + private Integer id; + + private String name; + + private BigDecimal minPrice; + + private BigDecimal maxPrice; + + private String status; + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/AuthUserDto.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/AuthUserDto.java index c27ef49..e01c109 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/AuthUserDto.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/AuthUserDto.java @@ -13,6 +13,7 @@ public class AuthUserDto { private String password; private String code; + private String opencode; private String uuid = ""; @@ -47,4 +48,12 @@ public class AuthUserDto { public void setUuid(String uuid) { this.uuid = uuid; } + + public String getOpencode() { + return opencode; + } + + public void setOpencode(String opencode) { + this.opencode = opencode; + } } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/BasePageDto.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/BasePageDto.java new file mode 100644 index 0000000..c36c432 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/BasePageDto.java @@ -0,0 +1,13 @@ +package com.chaozhanggui.system.cashierservice.entity.dto; + +import lombok.Data; + +/** + * 分页数据 + */ +@Data +public class BasePageDto { + private Integer page = 1; + + private Integer size = 10; +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/ComShopDto.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/ComShopDto.java new file mode 100644 index 0000000..332cb8d --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/ComShopDto.java @@ -0,0 +1,15 @@ +package com.chaozhanggui.system.cashierservice.entity.dto; + +import lombok.Data; + + +/** + * 通用门店查询类 + */ +@Data +public class ComShopDto extends HomeBaseDto{ + /** + * 连锁店名 + */ + private String shopName; +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/CreateGroupOrderDto.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/CreateGroupOrderDto.java new file mode 100644 index 0000000..58429d5 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/CreateGroupOrderDto.java @@ -0,0 +1,18 @@ +package com.chaozhanggui.system.cashierservice.entity.dto; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class CreateGroupOrderDto { + private Integer proId; + private Integer shopId; + private Integer num; + private Integer userId; + private String phone; + private BigDecimal orderAmount; + private BigDecimal payAmount; + private String remark; + +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/GroupOrderDto.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/GroupOrderDto.java new file mode 100644 index 0000000..41e54d1 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/GroupOrderDto.java @@ -0,0 +1,13 @@ +package com.chaozhanggui.system.cashierservice.entity.dto; + +import lombok.Data; + +@Data +public class GroupOrderDto extends BasePageDto { + //用户Id 必填 + private String userId; + //状态: unpaid-待付款;unused-待使用;closed-已完成;refunding-退款中;refund-已退款;cancelled-已取消; + private String status; + //商品名称 模糊查询 + private String proName; +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/HomeBaseDto.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/HomeBaseDto.java new file mode 100644 index 0000000..143c537 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/HomeBaseDto.java @@ -0,0 +1,54 @@ +package com.chaozhanggui.system.cashierservice.entity.dto; + +import lombok.Data; +import org.apache.commons.lang3.StringUtils; + + +/** + * 查询通用核心类 + * 经纬度 + * 城市信息 + */ +@Data +public class HomeBaseDto extends BasePageDto{ + /** + * 经度 + */ + private String lat; + /** + * 纬度 + */ + private String lng; + /** + * 地址 + */ + private String address; + + private String distanceInKm; + + private Integer isPage = 1; + + public void setLat(String lat) { + if (StringUtils.isBlank(lat) || lat.equals("undefined")) { + this.lat = "34.343207"; + }else { + this.lat = lat; + } + } + + public void setLng(String lng) { + if (StringUtils.isBlank(lng) || lng.equals("undefined")) { + this.lng = "108.939645"; + }else { + this.lng = lng; + } + } + + public void setAddress(String address) { + if (StringUtils.isBlank(address) || address.equals("undefined")) { + this.address = "西安市"; + }else { + this.address = address; + } + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/HomeDto.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/HomeDto.java index abbcbbb..ebd27a8 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/HomeDto.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/HomeDto.java @@ -1,76 +1,37 @@ package com.chaozhanggui.system.cashierservice.entity.dto; +import lombok.Data; + /** * @author 12847 */ -public class HomeDto { - /** - * 地址 - */ - private String address; +@Data +public class HomeDto extends HomeBaseDto { + private String proName; /** * 品类 */ private String type; /** - * 1.理我最近 2.销量优先 3.价格优先 + * 0.今日上新 + * 1.离我最近 + * 2.销量优先 + * 3.价格优先 + * 4.热榜推荐 + * 5.精选推荐 */ - private Integer orderBy; + private Integer orderBy = 0; + /** - * 附近1KM 1选中 0未选中 + * 0:今天 + * 1:两小时内 */ - private Integer distance; - - private Integer page; - - private Integer size; - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public Integer getOrderBy() { - return orderBy; - } + private Integer dateType = 1; public void setOrderBy(Integer orderBy) { - this.orderBy = orderBy; - } - - public Integer getDistance() { - return distance; - } - - public void setDistance(Integer distance) { - this.distance = distance; - } - - public Integer getPage() { - return page; - } - - public void setPage(Integer page) { - this.page = page; - } - - public Integer getSize() { - return size; - } - - public void setSize(Integer size) { - this.size = size; + if(orderBy!=null){ + this.orderBy = orderBy; + } } } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/ReturnGroupOrderDto.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/ReturnGroupOrderDto.java new file mode 100644 index 0000000..403c22b --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/ReturnGroupOrderDto.java @@ -0,0 +1,29 @@ +package com.chaozhanggui.system.cashierservice.entity.dto; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class ReturnGroupOrderDto { + /** + * 退单数 + */ + private Integer num; + /** + * 团购订单id + */ + private Integer orderId; + /** + * 退款金额 + */ + private BigDecimal refundAmount; + /** + * 退款原因 + */ + private String refundReason; + /** + * 退款说明 + */ + private String refundDesc; +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/UserPassDto.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/UserPassDto.java new file mode 100644 index 0000000..5a19a64 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/UserPassDto.java @@ -0,0 +1,17 @@ +package com.chaozhanggui.system.cashierservice.entity.dto; + +import lombok.Data; + +/** + * 修改密码的 Vo 类 + */ +@Data +public class UserPassDto { + private String phone; + + private String code; + + private String oldPass; + + private String newPass; +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/BannerInfoVo.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/BannerInfoVo.java new file mode 100644 index 0000000..f34831f --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/BannerInfoVo.java @@ -0,0 +1,43 @@ +package com.chaozhanggui.system.cashierservice.entity.vo; + +import lombok.Data; + +import java.math.BigDecimal; + +/** + * @author lyf + */ +@Data +public class BannerInfoVo { + /** + * 昵称 + */ + private String name; + /** + * 昵称 + */ + private String logo; + + /** + * 免单了多少钱 + */ + private BigDecimal money; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getLogo() { + return logo; + } + + public void setLogo(String logo) { + this.logo = logo; + } + + +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/BannerVO.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/BannerVO.java new file mode 100644 index 0000000..c9e82da --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/BannerVO.java @@ -0,0 +1,31 @@ +package com.chaozhanggui.system.cashierservice.entity.vo; + +import java.util.List; + +/** + * @author 12847 + */ +public class BannerVO { + /** + * 有多少人参与了免单 + */ + private String coupons; + + private List counponsInfo; + + public String getCoupons() { + return coupons; + } + + public void setCoupons(String coupons) { + this.coupons = coupons; + } + + public List getCounponsInfo() { + return counponsInfo; + } + + public void setCounponsInfo(List counponsInfo) { + this.counponsInfo = counponsInfo; + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/CommonVo.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/CommonVo.java new file mode 100644 index 0000000..ee243de --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/CommonVo.java @@ -0,0 +1,25 @@ +package com.chaozhanggui.system.cashierservice.entity.vo; + +import com.chaozhanggui.system.cashierservice.entity.SysDict; +import lombok.Data; + +import java.util.List; + +/** + * 顶部图 + * 预约到店 + * 每日上新 + * 热榜推荐 + * 咖啡饮品 + */ +@Data +public class CommonVo { + + private String title; + + private List carousel; + /** + * 菜单列表 不一定有 + */ + private List menu; +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/DicDetailVO.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/DicDetailVO.java deleted file mode 100644 index 9de0cfa..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/DicDetailVO.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.chaozhanggui.system.cashierservice.entity.vo; - -import com.chaozhanggui.system.cashierservice.entity.SysDictDetail; - -import java.util.List; - -/** - * @author lyf - */ -public class DicDetailVO { - private String name; - - private String description; - - private List detail; - - private Integer isChild; - - public Integer getIsChild() { - return isChild; - } - - public void setIsChild(Integer isChild) { - this.isChild = isChild; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public List getDetail() { - return detail; - } - - public void setDetail(List detail) { - this.detail = detail; - } -} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/DistrictVO.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/DistrictVO.java deleted file mode 100644 index aff7937..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/DistrictVO.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.chaozhanggui.system.cashierservice.entity.vo; - -/** - * @author lyf - */ -public class DistrictVO { - /** - * 图片 - */ - private String icon; - /** - * 菜单名 - */ - private String name; - /** - * 跳转地址 - */ - private String relUrl; -} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/DistrictVo.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/DistrictVo.java new file mode 100644 index 0000000..88fcded --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/DistrictVo.java @@ -0,0 +1,42 @@ +package com.chaozhanggui.system.cashierservice.entity.vo; + +import lombok.Data; +import net.sourceforge.pinyin4j.PinyinHelper; +import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; +import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; +import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; +import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; + +import java.util.List; + +/** + * 行政区域返回vo + */ +@Data +public class DistrictVo{ + private Object citycode; + private String adcode; + private String name; + private String center; + private String level; + private List districts; + + public String getNameAsPY() { + return getPinYin(name); + } + + public String getPinYin(String name){ + HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat(); + // 设置声调类型为WITH_TONE_MARK + format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); + // 设置拼音输出的大小写格式为小写 + format.setCaseType(HanyuPinyinCaseType.LOWERCASE); + String pinyin = ""; + try { + pinyin = PinyinHelper.toHanYuPinyinString(name,format , "", false); + } catch (BadHanyuPinyinOutputFormatCombination e) { + return pinyin; + } + return pinyin; + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/GroupOrderDetailsVo.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/GroupOrderDetailsVo.java new file mode 100644 index 0000000..cee294b --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/GroupOrderDetailsVo.java @@ -0,0 +1,100 @@ +package com.chaozhanggui.system.cashierservice.entity.vo; + +import com.chaozhanggui.system.cashierservice.entity.TbGroupOrderCoupon; +import com.chaozhanggui.system.cashierservice.entity.TbPurchaseNotice; +import lombok.Data; + +import java.math.BigDecimal; +import java.util.List; + +@Data +public class GroupOrderDetailsVo { + private Integer id; + /** + * 商品id + */ + private Integer proId; + /** + * 商品名称 + */ + private String proName; + /** + * 商品卷图片 + */ + private String proImg; + /** + * 可用时间说明 + * 周一至周日 + */ + private String avaTime=""; + /** + * 商品描述 + * 随时退·过期自动退·到店 + */ + private String proDetail="随时退·过期自动退·到店"; + /** + * 订单金额 + */ + private BigDecimal orderAmount; + /** + * number 张可用 | 2024-04-11 23:59:59 到期 + */ + private String expDate; + /** + * 订单状态 + */ + private String status; + /** + * 是否支持退款 + */ + private Integer refundAble; + + List coupons; + + /** + * 商家名称 + */ + private String shopName; + private Byte isUseVip; + /** + * 商家电话 + */ + private String shopPhone; + /** + * 距离 单位km + */ + private String distances; + /** + * 地址 + */ + private String address; + /** + * 商品细节 + */ + List tagVos; + /** + * 购买须知 + */ + private TbPurchaseNotice notice=new TbPurchaseNotice(); + /** + * 订单编号 + */ + private String orderNo; + /** + * 手机号 + */ + private String phone; + /** + * 付款时间 + */ + private String payTime; + /** + * 数量 + */ + private Integer number; + /** + * 实付金额 + */ + private BigDecimal payAmount; + private BigDecimal saveAmount; +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/GroupOrderListVo.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/GroupOrderListVo.java new file mode 100644 index 0000000..2e43e79 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/GroupOrderListVo.java @@ -0,0 +1,39 @@ +package com.chaozhanggui.system.cashierservice.entity.vo; + +import lombok.Data; + +@Data +public class GroupOrderListVo { + /** + * id + */ + private Integer id; + /** + * 订单编号 + */ + private String orderNo; + /** + * 商品名称 + */ + private String proName; + /** + * 商品图 + */ + private String proImg; + /** + * 订单金额 + */ + private Double orderAmount; + /** + * 实付金额 + */ + private Double payAmount; + /** + * 数量 + */ + private Integer number; + /** + * 订单状态 + */ + private String status; +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/HomeCarouselVo.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/HomeCarouselVo.java new file mode 100644 index 0000000..8e71a04 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/HomeCarouselVo.java @@ -0,0 +1,31 @@ +package com.chaozhanggui.system.cashierservice.entity.vo; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Data; + +/** + * 轮播图VO + */ +@Data +@JsonIgnoreProperties(ignoreUnknown = true) +public class HomeCarouselVo { + + /** + * 描述 同类型下 name唯一 + */ + private String name; + /** + * 轮播图url + */ + private String coverImg; + /** + * 跳转类型 如 拉起相机 跳转小程序 跳转第三方url + */ + private String jumpType; + /** + * 绝对跳转地址 + */ + private String absUrl; + +} + diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/HomeDistrictVo.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/HomeDistrictVo.java new file mode 100644 index 0000000..4f8e8b5 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/HomeDistrictVo.java @@ -0,0 +1,37 @@ +package com.chaozhanggui.system.cashierservice.entity.vo; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Data; + +/** + * 首页金刚区Vo + */ +@Data +@JsonIgnoreProperties(ignoreUnknown = true) +public class HomeDistrictVo{ + /** + * 展示图url + */ + private String coverImg; + /** + * 描述 同类型下 name唯一 + */ + private String name; + + private String value; + /** + * 字体颜色 + */ + private String fontColor; + /** + * 类型: scan:拉起相机;relative:内部页面;absolute:外链url + */ + private String jumpType; + /** + * 绝对跳转地址 + */ + private String absUrl; + + +} + diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/HomeUpVO.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/HomeUpVO.java index b3104e2..ef2272d 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/HomeUpVO.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/HomeUpVO.java @@ -1,8 +1,6 @@ package com.chaozhanggui.system.cashierservice.entity.vo; import com.chaozhanggui.system.cashierservice.entity.SysDict; -import com.chaozhanggui.system.cashierservice.entity.TbPlatformDict; -import lombok.Data; import java.util.List; @@ -14,15 +12,15 @@ public class HomeUpVO { /** * 轮播图 */ - List carousel; + List carousel; /** * 金刚区 */ - List district; + List district; /** * 条件查询 */ - List menu; + List menu; /** * 今日上新 */ @@ -31,6 +29,18 @@ public class HomeUpVO { * 销量飙升 */ HotRankingVO salesList; + /** + * 小横幅 + */ + BannerVO bannerVO; + + public BannerVO getBannerVO() { + return bannerVO; + } + + public void setBannerVO(BannerVO bannerVO) { + this.bannerVO = bannerVO; + } public TodayRankingVO getTodayList() { return todayList; @@ -48,27 +58,27 @@ public class HomeUpVO { this.salesList = salesList; } - public List getCarousel() { + public List getCarousel() { return carousel; } - public void setCarousel(List carousel) { + public void setCarousel(List carousel) { this.carousel = carousel; } - public List getDistrict() { + public List getDistrict() { return district; } - public void setDistrict(List district) { + public void setDistrict(List district) { this.district = district; } - public List getMenu() { + public List getMenu() { return menu; } - public void setMenu(List menu) { + public void setMenu(List menu) { this.menu = menu; } } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/HomeVO.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/HomeVO.java index 8e39f17..d770df2 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/HomeVO.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/HomeVO.java @@ -1,6 +1,8 @@ package com.chaozhanggui.system.cashierservice.entity.vo; import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; /** * @author lyf @@ -10,6 +12,11 @@ public class HomeVO { * 店铺名称 */ private String shopName; + + /** + * 店铺名称 + */ + private String shopImage; /** * 商品名称 */ @@ -29,7 +36,7 @@ public class HomeVO { /** * 折扣 */ - private Float discount; + private BigDecimal discount; /** * 共省金额 */ @@ -40,21 +47,41 @@ public class HomeVO { */ private BigDecimal realSalesNumber; - private Integer productId; /** * 店铺标签 */ - private String shopTag; + private List shopTag; /** * 商品标签 */ - private String proTag; + private List proTag=new ArrayList<>(); /** * 距离 */ private String distances ="100"; + private String districts; private Integer id; + /** + * 结束时间 + */ + private Long endTime; + + public String getShopImage() { + return shopImage; + } + + public void setShopImage(String shopImage) { + this.shopImage = shopImage; + } + + public Long getEndTime() { + return endTime; + } + + public void setEndTime(Long endTime) { + this.endTime = endTime; + } public Integer getId() { return id; @@ -72,30 +99,22 @@ public class HomeVO { this.distances = distances; } - public String getShopTag() { + public List getShopTag() { return shopTag; } - public void setShopTag(String shopTag) { + public void setShopTag(List shopTag) { this.shopTag = shopTag; } - public String getProTag() { + public List getProTag() { return proTag; } - public void setProTag(String proTag) { + public void setProTag(List proTag) { this.proTag = proTag; } - public Integer getProductId() { - return productId; - } - - public void setProductId(Integer productId) { - this.productId = productId; - } - public String getShopName() { return shopName; } @@ -104,6 +123,13 @@ public class HomeVO { this.shopName = shopName; } + public String getDistricts() { + return districts; + } + + public void setDistricts(String districts) { + this.districts = districts; + } public String getProductName() { return productName; @@ -137,11 +163,11 @@ public class HomeVO { this.salePrice = salePrice; } - public Float getDiscount() { + public BigDecimal getDiscount() { return discount; } - public void setDiscount(Float discount) { + public void setDiscount(BigDecimal discount) { this.discount = discount; } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/IntegralFlowVo.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/IntegralFlowVo.java new file mode 100644 index 0000000..12cfe06 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/IntegralFlowVo.java @@ -0,0 +1,17 @@ +package com.chaozhanggui.system.cashierservice.entity.vo; + +import lombok.Data; + +import java.math.BigDecimal; + +/** + * @author lyf + */ +@Data +public class IntegralFlowVo { + private String openId; + private Integer page; + private Integer pageSize; + private String sign; + +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/IntegralVo.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/IntegralVo.java new file mode 100644 index 0000000..c26ab36 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/IntegralVo.java @@ -0,0 +1,21 @@ +package com.chaozhanggui.system.cashierservice.entity.vo; + +import lombok.Data; + +import java.math.BigDecimal; + +/** + * @author lyf + */ +@Data +public class IntegralVo { + //openId + private String openId; + //数量 + private BigDecimal num; + //类型 + private String type; + //签名 + private String sign; + +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/OrderConfirmVo.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/OrderConfirmVo.java new file mode 100644 index 0000000..1e774e4 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/OrderConfirmVo.java @@ -0,0 +1,51 @@ +package com.chaozhanggui.system.cashierservice.entity.vo; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class OrderConfirmVo { + private String proId; + private String shopId; + private Byte isUseVip; + /** + * 商品图片 + */ + private String proImg; + /** + * 商品名称 + */ + private String proName; + /** + * 可用时间说明 + * 周一至周日 + */ + private String avaTime = "周一至周日"; + /** + * 商品描述 + * 随时退·过期自动退·到店 + */ + private String proDetail = "随时退·过期自动退·到店"; + /** + * 商品原价/划线价 + */ + private BigDecimal originPrice; + /** + * 商品现价 + */ + private BigDecimal salePrice; + /** + * 优惠金额 + */ + private BigDecimal save; + /** + * 优惠劵 + * 暂无可用/有多少张可选择 + * 字体颜色 + * 背景色 + */ + private TagVo couponDetail; + + +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/OrderVo.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/OrderVo.java index b179b01..03ee617 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/OrderVo.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/OrderVo.java @@ -1,6 +1,5 @@ package com.chaozhanggui.system.cashierservice.entity.vo; -import com.chaozhanggui.system.cashierservice.entity.TbCashierCart; import com.chaozhanggui.system.cashierservice.entity.TbOrderDetail; import lombok.Data; @@ -25,6 +24,8 @@ public class OrderVo { private String orderNo; private Long time; + private Long expiredMinutes = 0l; + private Long expiredSeconds = 0l; private BigDecimal payAmount; private String orderType; @@ -34,4 +35,6 @@ public class OrderVo { private BigDecimal totalNumber; + private String outNumber; + } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/ProductInfoVo.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/ProductInfoVo.java new file mode 100644 index 0000000..b1ef659 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/ProductInfoVo.java @@ -0,0 +1,90 @@ +package com.chaozhanggui.system.cashierservice.entity.vo; + +import com.alibaba.fastjson.JSONArray; +import com.chaozhanggui.system.cashierservice.entity.TbPurchaseNotice; +import lombok.Data; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * @author lyf + */ +@Data +public class ProductInfoVo { + /** + * 商品图片 + */ + private JSONArray images; + + /** + * 现价 + */ + private BigDecimal salePrice; + /** + * 折扣 + */ + private BigDecimal discount; + /** + * 原价 + */ + private BigDecimal originPrice; + + /** + * 销量 + */ + private BigDecimal realSalesNumber; + + /** + * 商品名称 + */ + private String productName; + + /** + * 购买须知标签 + */ + private List noticeTag; + + /** + * 店铺名称 + */ + private String shopName; + /** + * 多少家店可用 + */ + private Integer shopNum; + /** + * 连锁店扩展店名 + */ + private String chainName; + /** + * 联系方式 + */ + private String phone; + /** + * 营业时间 + */ + private String businessTime = "全天营业"; + /** + * 距离 + */ + private String distances = "100"; + private String lat; + private String lng; + private String districts; + /** + * 地址 + */ + private String address; + + /** + * 套餐详情 + */ + List productList = new ArrayList<>(); + + /** + * 购买须知/价格说明 + */ + private TbPurchaseNotice purchaseNotice = new TbPurchaseNotice(); +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/ProductVo.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/ProductVo.java new file mode 100644 index 0000000..0d6ee0b --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/ProductVo.java @@ -0,0 +1,35 @@ +package com.chaozhanggui.system.cashierservice.entity.vo; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Data; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +@Data +@JsonIgnoreProperties(ignoreUnknown = true) +public class ProductVo { + //选几个 + private Integer number; + + //类别 + private String title; + + //食物 + private List goods=new ArrayList<>(); // 食品列表 + + @Data + @JsonIgnoreProperties(ignoreUnknown = true) + public static class Food { + private Integer id; + private String name; // 商品名称 + private BigDecimal lowPrice; // 售价 + private String groupNum; // 数量 + private String unitName; // 单位 + /** + * 商品标签 + */ + private List proTag=new ArrayList<>(); + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/ShopGroupInfoVo.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/ShopGroupInfoVo.java new file mode 100644 index 0000000..3adef0a --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/ShopGroupInfoVo.java @@ -0,0 +1,35 @@ +package com.chaozhanggui.system.cashierservice.entity.vo; + +import lombok.Data; + +/** + * @author ww + * 店铺团购卷vo + */ +@Data +public class ShopGroupInfoVo { + private Integer shopId; + + private String shopName; + + private String shopImg; + + private String shopTag; + private String lat; + private String lng; + + + + private Integer proId; + + private String proName; + + private String proImg; + //销量 + private Integer number; + + private String address; + private String districts; + + +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/ShopUserListVo.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/ShopUserListVo.java new file mode 100644 index 0000000..39b4aaf --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/ShopUserListVo.java @@ -0,0 +1,20 @@ +package com.chaozhanggui.system.cashierservice.entity.vo; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class ShopUserListVo { + + private Long memberId; + private Long shopId; + private String shopName; + private String chainName; + private String logo; + private String detail; + private BigDecimal levelConsume; + private BigDecimal amount; + private String code; + private Integer isVip; +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/SubShopVo.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/SubShopVo.java new file mode 100644 index 0000000..8f33275 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/SubShopVo.java @@ -0,0 +1,49 @@ +package com.chaozhanggui.system.cashierservice.entity.vo; + +import lombok.Data; + +/** + * 预约到店列表页Vo + */ +@Data +public class SubShopVo{ + private Integer id; + /** + * 店铺名称 + */ + private String shopName; + /** + * 连锁店扩展名 + */ + private String chainName; + /** + * 手机号 + */ + private String phone; + /** + * 营业时间 + */ + private String businessStartDay; + private String businessEndDay; + private String businessTime; + /** + * Logo图 + */ + private String logo; + /** + * 封面图 + */ + private String coverImg; + /** + * 地址 + */ + private String address; + /** + * 距离 + */ + private String distances ="100"; + + private String lat; + + private String lng; +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/TagProductVO.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/TagProductVO.java new file mode 100644 index 0000000..1fbda4d --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/TagProductVO.java @@ -0,0 +1,22 @@ +package com.chaozhanggui.system.cashierservice.entity.vo; + +import lombok.Data; + +/** + * 商品 标签 + * @author lyf + */ +@Data +public class TagProductVO { + //商品id + private Integer productId; + //标签前 小图标 + private String shareImg; + //标签 名称 + private String name; + //字体颜色 + private String fontColor; + //背景色 + private String backColor; + +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/TagVo.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/TagVo.java new file mode 100644 index 0000000..24885d6 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/TagVo.java @@ -0,0 +1,25 @@ +package com.chaozhanggui.system.cashierservice.entity.vo; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Data; + +@Data +@JsonIgnoreProperties(ignoreUnknown = true) +public class TagVo { + /** + * 标签前 小图标 + */ + private String shareImg; + /** + * 描述 同类型下 name唯一 + */ + private String name; + /** + * 字体颜色 + */ + private String fontColor; + /** + * 背景色 + */ + private String backColor; +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/carouselVO.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/carouselVO.java deleted file mode 100644 index d7cffc7..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/vo/carouselVO.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.chaozhanggui.system.cashierservice.entity.vo; - -/** - * 轮播图 - * @author lyf - */ -public class carouselVO { - /** - * 封面图 - */ - private String coverImg; - /** - * 跳转地址 - */ - private String relUrl; -} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/exception/DefaultError.java b/src/main/java/com/chaozhanggui/system/cashierservice/exception/DefaultError.java new file mode 100644 index 0000000..da542b9 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/exception/DefaultError.java @@ -0,0 +1,108 @@ +package com.chaozhanggui.system.cashierservice.exception; + + +public enum DefaultError implements IError { + /** + * 系统内部错误 + */ + SYSTEM_INTERNAL_ERROR("0000", "系统错误"), + /** + * 无效参数 + */ + INVALID_PARAMETER("0001", "参数验证失败"), + /** + * 服务不存在 + */ + SERVICE_NOT_FOUND("0002", "服务不存在"), + /** + * 参数不全 + */ + PARAMETER_REQUIRED("0003", "参数不全"), + /** + * 参数过长 + */ + PARAMETER_MAX_LENGTH("0004", "参数过长"), + /** + * 参数过短 + */ + PARAMETER_MIN_LENGTH("0005", "参数过短"), + /** + * 认证失败 + */ + AUTHENTICATION_ERROR("0006", "认证失败"), + /** + * 认证动作失败 + */ + AUTHENTICATION_OPTION_ERROR("0007", "认证失败"), + /** + * 请求方法出错 + */ + METHOD_NOT_SUPPORTED("0008", "请求方法出错"), + /** + * 不支持的content类型 + */ + CONTENT_TYPE_NOT_SUPPORT("0009", "不支持的content类型"), + /** + * json格式化出错 + */ + JSON_FORMAT_ERROR("0010", "json格式化出错"), + /** + * 远程调用出错 + */ + CALL_REMOTE_ERROR("0011", "远程调用出错"), + /** + * 服务运行SQLException异常 + */ + SQL_EXCEPTION("0012", "服务运行SQL异常"), + /** + * 客户端异常 给调用者 app,移动端调用 + */ + CLIENT_EXCEPTION("0013", "客户端异常"), + /** + * 服务端异常, 微服务服务端产生的异常 + */ + SERVER_EXCEPTION("0014", "服务端异常"), + /** + * 授权失败 禁止访问 + */ + ACCESS_DENIED("0015", "没有访问权限"), + /** + * 演示环境 没有权限访问 + */ + SHOW_AUTH_CONTROL("0016", "演示环境,没有权限访问"), + /** + * 业务异常 + */ + BUSINESS_ERROR("0017", "业务异常"), + + NO_USER("0018","用户不存在"); + + String errorCode; + String errorMessage; + private static final String NS = "SYS"; + + DefaultError(String errorCode, String errorMessage) { + this.errorCode = errorCode; + this.errorMessage = errorMessage; + } + + @Override + public String getNameSpace() { + return NS; + } + + @Override + public String getErrorCode() { + return NS + "." + this.errorCode; + } + + @Override + public String getErrorMessage() { + return this.errorMessage; + } + + @Override + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/exception/DefaultExceptionAdvice.java b/src/main/java/com/chaozhanggui/system/cashierservice/exception/DefaultExceptionAdvice.java new file mode 100644 index 0000000..b68db15 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/exception/DefaultExceptionAdvice.java @@ -0,0 +1,168 @@ +package com.chaozhanggui.system.cashierservice.exception; + +import com.chaozhanggui.system.cashierservice.sign.Result; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.validation.BindException; +import org.springframework.validation.BindingResult; +import org.springframework.validation.FieldError; +import org.springframework.validation.ObjectError; +import org.springframework.web.HttpMediaTypeNotSupportedException; +import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.MissingServletRequestParameterException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.servlet.NoHandlerFoundException; + +import javax.validation.ConstraintViolation; +import javax.validation.ConstraintViolationException; +import javax.validation.UnexpectedTypeException; +import java.sql.SQLException; +import java.util.List; +import java.util.Set; + +@ControllerAdvice +@ResponseBody +public class DefaultExceptionAdvice { + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultExceptionAdvice.class); + + @ResponseStatus(HttpStatus.BAD_REQUEST) + @ExceptionHandler({HttpMessageNotReadableException.class, }) + public ResponseEntity handleHttpMessageNotReadableException(HttpMessageNotReadableException e) { + LOGGER.error("参数解析失败", e); + Result response = Result.failure(DefaultError.INVALID_PARAMETER); + response.setMsg(e.getMessage()); + return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); + } + + @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) + @ExceptionHandler({HttpRequestMethodNotSupportedException.class}) + public ResponseEntity handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) { + LOGGER.error("不支持当前请求方法", e); + Result response = Result.failure(DefaultError.METHOD_NOT_SUPPORTED); + response.setMsg(e.getMessage()); + return new ResponseEntity<>(response, HttpStatus.METHOD_NOT_ALLOWED); + } + + @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE) + @ExceptionHandler({HttpMediaTypeNotSupportedException.class}) + public ResponseEntity handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) { + LOGGER.error("不支持当前媒体类型", e); + Result response = Result.failure(DefaultError.CONTENT_TYPE_NOT_SUPPORT); + response.setMsg(e.getMessage()); + return new ResponseEntity<>(response, HttpStatus.UNSUPPORTED_MEDIA_TYPE); + } + + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + @ExceptionHandler({SQLException.class}) + public ResponseEntity handleSQLException(SQLException e) { + LOGGER.error("服务运行SQLException异常", e); + Result response = Result.failure(DefaultError.SQL_EXCEPTION); + response.setMsg(e.getMessage()); + return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); + } + + /** + * 所有异常统一处理 + * + * @return ResponseEntity + */ + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + @ExceptionHandler(Exception.class) + public ResponseEntity handleException(Exception ex) { + LOGGER.error("未知异常", ex); + IError error; + String extMessage = null; + if (ex instanceof BindException) { + error = DefaultError.INVALID_PARAMETER; + List errors = ((BindException) ex).getAllErrors(); + if (errors.size() != 0) { + StringBuilder msg = new StringBuilder(); + for (ObjectError objectError : errors) { + msg.append("Field error in object '").append(objectError.getObjectName()).append(" "); + if (objectError instanceof FieldError) { + msg.append("on field ").append(((FieldError) objectError).getField()).append(" "); + } + msg.append(objectError.getDefaultMessage()).append(" "); + } + extMessage = msg.toString(); + } + } else if (ex instanceof MissingServletRequestParameterException) { + error = DefaultError.INVALID_PARAMETER; + extMessage = ex.getMessage(); + } else if (ex instanceof ConstraintViolationException) { + error = DefaultError.INVALID_PARAMETER; + Set> violations = ((ConstraintViolationException) ex).getConstraintViolations(); + final StringBuilder msg = new StringBuilder(); + for (ConstraintViolation constraintViolation : violations) { + msg.append(constraintViolation.getPropertyPath()).append(":").append(constraintViolation.getMessage()).append("\n"); + } + extMessage = msg.toString(); + } else if (ex instanceof HttpMediaTypeNotSupportedException) { + error = DefaultError.CONTENT_TYPE_NOT_SUPPORT; + extMessage = ex.getMessage(); + } else if (ex instanceof HttpMessageNotReadableException) { + error = DefaultError.INVALID_PARAMETER; + extMessage = ex.getMessage(); + } else if (ex instanceof MethodArgumentNotValidException) { + error = DefaultError.INVALID_PARAMETER; + final BindingResult result = ((MethodArgumentNotValidException) ex).getBindingResult(); + if (result.hasErrors()) { + extMessage = result.getAllErrors().get(0).getDefaultMessage(); + } else { + extMessage = ex.getMessage(); + } + } else if (ex instanceof HttpRequestMethodNotSupportedException) { + error = DefaultError.METHOD_NOT_SUPPORTED; + extMessage = ex.getMessage(); + } else if (ex instanceof UnexpectedTypeException) { + error = DefaultError.INVALID_PARAMETER; + extMessage = ex.getMessage(); + } else if (ex instanceof NoHandlerFoundException) { + error = DefaultError.SERVICE_NOT_FOUND; + extMessage = ex.getMessage(); + } else { + error = DefaultError.SYSTEM_INTERNAL_ERROR; + extMessage = ex.getMessage(); + } + + + Result response = Result.failure(error); + response.setMsg(extMessage); + return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); + } + + /** + * BusinessException 业务异常处理 + * + * @return ResponseEntity + */ + @ResponseStatus(HttpStatus.OK) + @ExceptionHandler(MsgException.class) + public ResponseEntity handleException(MsgException e) { + LOGGER.error("业务异常", e); + Result response = Result.fail(e.getMessage()); + response.setMsg(e.getMessage()); + return new ResponseEntity<>(response, HttpStatus.OK); + } + +// /** +// * 使用ExceptionHandler注解声明处理TestException异常 +// * +// */ +// @ResponseBody +// @ExceptionHandler(MsgException.class) +// public Result exception(MsgException e) { +// // 控制台打印异常 +// e.printStackTrace(); +// // 返回错误格式信息 +// return Result.fail(e.getMessage()); +// } + +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/exception/IError.java b/src/main/java/com/chaozhanggui/system/cashierservice/exception/IError.java new file mode 100644 index 0000000..56d1d1b --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/exception/IError.java @@ -0,0 +1,32 @@ +package com.chaozhanggui.system.cashierservice.exception; + +public interface IError { + + /** + * 获取nameSpace + * + * @return nameSpace + */ + String getNameSpace(); + + /** + * 获取错误码 + + * @return 错误码 + */ + String getErrorCode(); + + /** + * 获取错误信息 + + * @return 错误信息 + */ + String getErrorMessage(); + + /** + * 设置错误信息 + * + * @param errorMessage 错误信息 + */ + void setErrorMessage(String errorMessage); +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/interceptor/CustomFilter.java b/src/main/java/com/chaozhanggui/system/cashierservice/interceptor/CustomFilter.java index b89fc6f..b79a877 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/interceptor/CustomFilter.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/interceptor/CustomFilter.java @@ -1,9 +1,7 @@ package com.chaozhanggui.system.cashierservice.interceptor; -import ch.qos.logback.classic.turbo.TurboFilter; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; - import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/interceptor/LimitSubmitAspect.java b/src/main/java/com/chaozhanggui/system/cashierservice/interceptor/LimitSubmitAspect.java new file mode 100644 index 0000000..406ca17 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/interceptor/LimitSubmitAspect.java @@ -0,0 +1,186 @@ +package com.chaozhanggui.system.cashierservice.interceptor; + +import cn.hutool.core.util.ObjectUtil; +import com.chaozhanggui.system.cashierservice.annotation.LimitSubmit; +import com.chaozhanggui.system.cashierservice.exception.MsgException; +import com.chaozhanggui.system.cashierservice.util.RedisUtils; +import lombok.extern.slf4j.Slf4j; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.*; +import org.aspectj.lang.reflect.MethodSignature; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.LocalVariableTableParameterNameDiscoverer; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; +import java.lang.reflect.Method; + +@Component +@Aspect +@Slf4j +public class LimitSubmitAspect { + //封装了redis操作各种方法 + @Autowired + private RedisUtils redisUtil; + + @Pointcut("@annotation(com.chaozhanggui.system.cashierservice.annotation.LimitSubmit)") + private void pay() { + } + + @Pointcut("@annotation(com.chaozhanggui.system.cashierservice.annotation.LimitSubmit)") + private void pay1() { + } + + @Around("pay()") + public Object handleSubmit(ProceedingJoinPoint joinPoint) throws Throwable { + + Method method = ((MethodSignature) joinPoint.getSignature()).getMethod(); + + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + HttpServletRequest request = attributes.getRequest(); + + String orderId= request.getParameter("orderId"); + if(ObjectUtil.isEmpty(orderId)||ObjectUtil.isNull(orderId)){ + orderId=request.getParameter("authCode"); + } + + + if(ObjectUtil.isEmpty(orderId)||ObjectUtil.isNull(orderId)){ + orderId=request.getParameter("id"); + } + + + //获取注解信息 + LimitSubmit limitSubmit = method.getAnnotation(LimitSubmit.class); + boolean needAllWait = limitSubmit.needAllWait(); + String redisKey = limitSubmit.key(); + + + int submitTimeLimiter = limitSubmit.limit(); + String key = getRedisKey(joinPoint, redisKey, orderId); + Object result = redisUtil.get(key); + log.info("开始锁定资源信息" + key); + + if (result != null) { + log.info("锁定的值是" + result.toString()); + throw new MsgException("正在处理中, 请勿重复操作"); + } + boolean setResult = redisUtil.setIfAbsent(key, String.valueOf(System.currentTimeMillis()), submitTimeLimiter); + if (!setResult) { + throw new MsgException("1正在处理中, 请勿重复操作"); + } + + + try { + Object proceed = joinPoint.proceed(); + return proceed; + } catch (Throwable e) { + log.error("Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'", joinPoint.getSignature().getDeclaringTypeName(), + joinPoint.getSignature().getName(), e.getCause() != null ? e.getCause() : "NULL", e.getMessage(), e); + throw e; + } finally { + if (!needAllWait) { + redisUtil.del(redisKey); + log.info("删除后的结果: " + redisUtil.get(redisKey)); + } + } + } + + + @AfterReturning("pay1()") + public void AfterReturning(JoinPoint joinPoint) { + Method method = ((MethodSignature) joinPoint.getSignature()).getMethod(); + LimitSubmit limitSubmit = method.getAnnotation(LimitSubmit.class); + String redisKey = limitSubmit.key(); + + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + HttpServletRequest request = attributes.getRequest(); + + String orderId= request.getParameter("orderId"); + + String key = getRedisKey1(joinPoint, redisKey, orderId); + log.info("正常释放了锁资源" + key); + // 延时 1s 释放 + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } finally { +// redisUtil.del(key); + log.info("删除后的结果: " + redisUtil.get(redisKey)); + } + } + + @AfterThrowing(pointcut = "pay1()", throwing = "ex") + public void AfterThrowing(JoinPoint joinPoint, Throwable ex) { + + if (!(ex instanceof MsgException)) { + // 抛出的如果不是重复性提交的异常, 则释放锁资源 + + Method method = ((MethodSignature) joinPoint.getSignature()).getMethod(); + LimitSubmit limitSubmit = method.getAnnotation(LimitSubmit.class); + String redisKey = limitSubmit.key(); + + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + HttpServletRequest request = attributes.getRequest(); + + String orderId= request.getParameter("orderId"); + + String key = getRedisKey1(joinPoint, redisKey, orderId); + log.info("发生异常释放了锁资源" + key); + // 延时 1s 释放 + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } finally { + redisUtil.del(key); + log.info("删除后的结果: " + redisUtil.get(redisKey)); + } + } + } + + /** + * 支持多参数,从请求参数进行处理 + */ + private String getRedisKey(ProceedingJoinPoint joinPoint, String key, String orderId) { + if (key.contains("%s") && orderId != null) { + key = String.format(key, orderId); + } + Method method = ((MethodSignature) joinPoint.getSignature()).getMethod(); + + LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer(); + String[] parameterNames = discoverer.getParameterNames(method); + if (parameterNames != null) { + for (int i = 0; i < parameterNames.length; i++) { + String item = parameterNames[i]; + if (key.contains("#" + item)) { + key = key.replace("#" + item, joinPoint.getArgs()[i].toString()); + } + } + } + return key.toString(); + } + + private String getRedisKey1(JoinPoint joinPoint, String key, String orderId) { + if (key.contains("%s") && orderId != null) { + key = String.format(key, orderId); + } + Method method = ((MethodSignature) joinPoint.getSignature()).getMethod(); + + LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer(); + String[] parameterNames = discoverer.getParameterNames(method); + if (parameterNames != null) { + for (int i = 0; i < parameterNames.length; i++) { + String item = parameterNames[i]; + if (key.contains("#" + item)) { + key = key.replace("#" + item, joinPoint.getArgs()[i].toString()); + } + } + } + return key.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/model/OrderDetailPO.java b/src/main/java/com/chaozhanggui/system/cashierservice/model/OrderDetailPO.java index 1a2b8cb..b3b22d6 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/model/OrderDetailPO.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/model/OrderDetailPO.java @@ -32,6 +32,8 @@ public class OrderDetailPO implements Serializable { private String remark; + private String outNumber; + @Data public static class Detail implements Serializable{ diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/model/ReturnOrderReq.java b/src/main/java/com/chaozhanggui/system/cashierservice/model/ReturnOrderReq.java new file mode 100644 index 0000000..e9cbc1b --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/model/ReturnOrderReq.java @@ -0,0 +1,17 @@ +package com.chaozhanggui.system.cashierservice.model; + +import lombok.Data; + +@Data +public class ReturnOrderReq extends BaseRequest { + + private String orderNumber; + + private String amount; + + private String mercRefundNo; + + private String refundReason; + + private String payPassword; +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/netty/ConnectionDebouncerHandler.java b/src/main/java/com/chaozhanggui/system/cashierservice/netty/ConnectionDebouncerHandler.java new file mode 100644 index 0000000..1a620da --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/netty/ConnectionDebouncerHandler.java @@ -0,0 +1,35 @@ +package com.chaozhanggui.system.cashierservice.netty; + +import io.netty.channel.Channel; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandlerContext; +import lombok.extern.slf4j.Slf4j; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +@Slf4j +public class ConnectionDebouncerHandler extends ChannelDuplexHandler { + private static final Map lastConnectionTimes = new ConcurrentHashMap<>(); + private static final long debounceIntervalMillis = 5*1000; // 防抖时间间隔,单位:毫秒 + + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + Channel channel = ctx.channel(); + long currentTimeMillis = System.currentTimeMillis(); + Long lastConnectionTime = lastConnectionTimes.get(channel); + if (lastConnectionTime == null || (currentTimeMillis - lastConnectionTime) > debounceIntervalMillis) { + // 允许新连接 + lastConnectionTimes.put(channel, currentTimeMillis); + super.channelActive(ctx); // 将事件传递给下一个处理器 + } else { + + channel.close(); + } + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + ctx.close(); + } +} 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..3d2f1ba --- /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("{\"type\":\"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..e3ccf17 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/netty/PushToAppChannelHandlerAdapter.java @@ -0,0 +1,242 @@ +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 { + log.info("netty连接 长连接激活"); + 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) { + 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{ + log.info("netty连接 接收到接口数据:meg:{}",msg); + 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 (String user : webSockets.keySet()) { + ChannelHandlerContext ctx = webSockets.get(user); + if (ctx != null) { + log.info("netty连接 发送消息 桌码群发 userId:{}",user); + sendMesToApp(message,ctx); + }else { + log.info("netty连接 发送消息 桌码群发 userId:{} 失败",user); + } + } + }else { + log.info("netty连接 发送消息 桌码群发 tableId:{} 失败",tableId); + } + } + } + + } +} \ 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..74d0c25 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/netty/PushToAppChannelInitializer.java @@ -0,0 +1,53 @@ +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.stereotype.Component; + +import javax.net.ssl.SSLException; +import java.io.*; +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()); + + // 添加连接防抖处理器(没用) +// pipeline.addLast(new ConnectionDebouncerHandler()); + //本地试调时使用 +// 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/PushToClientChannelHandlerAdapter.java b/src/main/java/com/chaozhanggui/system/cashierservice/netty/PushToClientChannelHandlerAdapter.java new file mode 100644 index 0000000..ff709fc --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/netty/PushToClientChannelHandlerAdapter.java @@ -0,0 +1,191 @@ +package com.chaozhanggui.system.cashierservice.netty; + +import com.alibaba.fastjson.JSONObject; +import com.chaozhanggui.system.cashierservice.netty.config.NettyChannelHandlerAdapter; +import com.chaozhanggui.system.cashierservice.util.JSONUtil; +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.ChannelHandlerContext; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + + +/** + * 客户端 + */ +@Slf4j +@Sharable +@Component +public class PushToClientChannelHandlerAdapter extends NettyChannelHandlerAdapter { + + /** + * [shopId, [clientId, ctx]] + */ + private static Map> webSocketMap = new HashMap<>(); + + /** + * [ctx, shopId:clientId] + */ + private static Map clientIdMap = new ConcurrentHashMap<>(); + + + private String clientId = ""; + private String shopId = ""; + + public PushToClientChannelHandlerAdapter() { + } + + public static PushToClientChannelHandlerAdapter getInstance() { + return new PushToClientChannelHandlerAdapter(); + } + + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + log.info("netty连接client 长连接激活"); + super.channelActive(ctx); + } + + @Override + public void channelInactive(ChannelHandlerContext ctx) { + log.info("netty连接client 长连接关闭:{}, {}",clientId,shopId); + ctx.close(); + removeCtx(ctx); + } + + /** + * 移除ctx + */ + private void removeCtx(ChannelHandlerContext ctx) { + // shopId:clientId + String key = clientIdMap.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]); + } + } + } + clientIdMap.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) { + JSONObject jsonObject = new JSONObject(); + if (StringUtils.isNotEmpty(msg)) { + jsonObject = JSONObject.parseObject(msg); + }else { + log.info("netty连接client 接收到空数据:{}",msg); + } + String type = jsonObject.getString("type"); + if(type.equals("heartbeat")){//心跳 + log.info("netty连接client 接收到心跳数据:shop:{} clientId:{} meg:{}",shopId,clientId,msg); + }else { + if (type.equals("connect")) { + String clientId = jsonObject.getString("clientId"); + String shopId = jsonObject.getString("shopId"); + if (StringUtils.isBlank(type) || StringUtils.isBlank(shopId) || StringUtils.isBlank(clientId)) { + log.info("netty连接client 建立连接请求失败:{}",jsonObject); + channelInactive(ctx); + return; + } + + log.info("netty连接client 接收到数据 建立连接参数 param:{}",jsonObject); + this.clientId=clientId; + this.shopId=shopId; + if (webSocketMap.containsKey(shopId)) { + ConcurrentHashMap clientSocketMap = webSocketMap.get(shopId); + ChannelHandlerContext channelHandlerContext = clientSocketMap.get(clientId); + if (channelHandlerContext != null) { + channelHandlerContext.close(); + } + clientSocketMap.put(clientId, ctx); + } else { + ConcurrentHashMap clientSocketMap = new ConcurrentHashMap<>(); + clientSocketMap.put(clientId, ctx); + webSocketMap.put(shopId,clientSocketMap); + } + clientIdMap.put(ctx, shopId + ":" + clientId); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("status", "success"); + jsonObject1.put("msg", "连接成功"); + jsonObject1.put("type", "connect"); + sendMesToApp(jsonObject1.toString(), ctx); + } + } + //业务逻辑代码处理框架。。。 + ctx.flush(); + } + + public void sendMesToApp(String str, ChannelHandlerContext ctx) { + sendMessage(ctx, str); + } + + /** + * @param message 发送的消息内容 + * @param shopId 店铺Id + * @param clientId 客户端Id + * @param userFlag + * 为true 单发给clientId + * 为false 群发 shopId为空 发给所有人 + */ + @Async + public void AppSendInfo(String message, String shopId,String clientId, boolean userFlag) { + log.info("netty连接client 发送消息 shopId:{} clientId:{} userFlag:{} message:{}",shopId,clientId,userFlag, JSONUtil.toJSONString(message)); + if (userFlag) { + if (webSocketMap.containsKey(shopId)) { + ConcurrentHashMap webSockets = webSocketMap.get(shopId); + if(!webSockets.isEmpty()){ + if (StringUtils.isNotBlank(clientId)) { + ChannelHandlerContext ctx = webSockets.get(clientId); + if (ctx != null) { + sendMesToApp(message,ctx); + } + } + } + } + } else { + if (StringUtils.isEmpty(shopId)) { + // 向所有用户发送信息 + for (ConcurrentHashMap value : webSocketMap.values()) { + for (ChannelHandlerContext ctx : value.values()) { + sendMesToApp(message,ctx); + } + } + } else if (webSocketMap.containsKey(shopId)) { + ConcurrentHashMap webSockets = webSocketMap.get(shopId); + if(!webSockets.isEmpty()) { + for (String user : webSockets.keySet()) { + ChannelHandlerContext ctx = webSockets.get(user); + if (ctx != null) { + log.info("netty连接client 发送消息 桌码群发 clientId:{}",user); + sendMesToApp(message,ctx); + }else { + log.info("netty连接client 发送消息 桌码群发 clientId:{} 失败",user); + } + } + }else { + log.info("netty连接client 发送消息 桌码群发 clientId:{} 失败",clientId); + } + } + } + } +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/netty/PushToClientChannelInitializer.java b/src/main/java/com/chaozhanggui/system/cashierservice/netty/PushToClientChannelInitializer.java new file mode 100644 index 0000000..fd2b305 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/netty/PushToClientChannelInitializer.java @@ -0,0 +1,52 @@ +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.stereotype.Component; + +import javax.net.ssl.SSLException; +import java.io.InputStream; +import java.util.concurrent.TimeUnit; + +@Component +@Slf4j +public class PushToClientChannelInitializer 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()); + // 添加连接防抖处理器(没用) +// pipeline.addLast(new ConnectionDebouncerHandler()); + //本地试调时使用 wss +// 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("/client")); + ch.pipeline().addLast(new PushToClientChannelHandlerAdapter()); + } + + + public static InputStream loadResourceAsByteArrayInputStream(String path) { + InputStream inputStream = PushToClientChannelInitializer.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..94008fd --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/netty/config/NettyChannelHandlerAdapter.java @@ -0,0 +1,148 @@ +package com.chaozhanggui.system.cashierservice.netty.config; + +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.handler.codec.http.QueryStringDecoder; +import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; +import lombok.extern.slf4j.Slf4j; + +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 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()); + } + } + + /** + * 服务器接受客户端的数据信息时触发 + * + * @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..8ded4f7 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/netty/config/NettyConfig.java @@ -0,0 +1,45 @@ +package com.chaozhanggui.system.cashierservice.netty.config; + +import com.chaozhanggui.system.cashierservice.netty.PushToAppChannelInitializer; +import com.chaozhanggui.system.cashierservice.netty.PushToClientChannelInitializer; +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.client-port}") + private int clientPort; + + /** + * 接收者的线程数 + */ + @Value("${netty.server.parent-group-threads}") + private int parentGroupThreads; + /** + * 客户端的线程数 + */ + @Value("${netty.server.child-group-threads}") + private int childGroupThreads; + + @Resource + private PushToAppChannelInitializer pushToAppChannelInitializer; + @Resource + private PushToClientChannelInitializer pushToClientChannelInitializer; + @PostConstruct + public void startCameraNetty() { + NettyUtils.getInstance().initNetty(port, parentGroupThreads, childGroupThreads, pushToAppChannelInitializer); + NettyUtils.getInstance().initNetty(clientPort, parentGroupThreads, childGroupThreads, pushToClientChannelInitializer); + } +} 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 a1edf56..fc41fcd 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/CartConsumer.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/CartConsumer.java @@ -3,18 +3,10 @@ package com.chaozhanggui.system.cashierservice.rabbit; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; -import com.chaozhanggui.system.cashierservice.dao.*; -import com.chaozhanggui.system.cashierservice.entity.*; -import com.chaozhanggui.system.cashierservice.entity.vo.CashierCarVo; 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.sign.Result; -import com.chaozhanggui.system.cashierservice.socket.AppWebSocketServer; -import com.chaozhanggui.system.cashierservice.util.JSONUtil; -import com.chaozhanggui.system.cashierservice.util.RedisUtils; -import com.chaozhanggui.system.cashierservice.util.SnowFlakeUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.amqp.rabbit.annotation.RabbitHandler; @@ -23,13 +15,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; -import java.math.BigDecimal; -import java.time.Instant; -import java.util.*; - @Slf4j @Component -@RabbitListener(queues = {RabbitConstants.CART_QUEUE_PUT}) +//@RabbitListener(queues = {RabbitConstants.CART_QUEUE_PUT}) @Service public class CartConsumer { @@ -39,30 +27,39 @@ public class CartConsumer { @Autowired private CartService cartService; @RabbitHandler + @RabbitListener(queues = {"${queue}"}) public void listener(String message) { try { + log.info("监听数据进入 "+message); JSONObject jsonObject = JSON.parseObject(message); String tableId = jsonObject.getString("tableId"); String shopId = jsonObject.getString("shopId"); - 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("商品数量错误"); } cartService.createCart(jsonObject); - }else if(jsonObject.getString("type").equals("createOrder")){ + }else if (jsonObject.getString("type").equals("queryCart") ) { + cartService.queryCart(jsonObject); + } else if(jsonObject.getString("type").equals("createOrder")){ String cartDetail = redisUtil.getMessage(RedisCst.TABLE_CART.concat(tableId).concat("-").concat(shopId)); if (StringUtils.isEmpty(cartDetail)){ + log.info("createOrder购物车为空"); throw new MsgException("购物车为空无法下单"); } JSONArray array = JSON.parseArray(cartDetail); if (array.size() > 0){ cartService.createOrder(jsonObject); } - }else if(jsonObject.getString("type").equals("clearCart")){ + } + else if(jsonObject.getString("type").equals("clearCart")){ cartService.clearCart(jsonObject); } } catch (Exception e) { - e.getMessage(); + log.info("数据处理失败:{}",e.getMessage()); + e.printStackTrace(); } } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/IntegralConsumer.java b/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/IntegralConsumer.java new file mode 100644 index 0000000..a4155f3 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/IntegralConsumer.java @@ -0,0 +1,36 @@ +package com.chaozhanggui.system.cashierservice.rabbit; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.chaozhanggui.system.cashierservice.redis.RedisUtil; +import com.chaozhanggui.system.cashierservice.service.IntegralService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.amqp.rabbit.annotation.RabbitHandler; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.stereotype.Service; + +@Slf4j +@Component +@RabbitListener(queues = {RabbitConstants.INTEGRAL_QUEUE_PUT}) +@Service +public class IntegralConsumer { + + + @Autowired + private RedisUtil redisUtil; + @Autowired + private IntegralService integralService; + @RabbitHandler + public void listener(String message) { + try { + JSONObject jsonObject = JSON.parseObject(message); + integralService.integralAdd(jsonObject); + } catch (Exception e) { + e.getMessage(); + } + } + + +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/PrintMechineConsumer.java b/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/PrintMechineConsumer.java index 26b1f66..1657918 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/PrintMechineConsumer.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/PrintMechineConsumer.java @@ -172,6 +172,7 @@ public class PrintMechineConsumer { if(ObjectUtil.isNotEmpty(detailList)&&detailList.size()>0){ OrderDetailPO detailPO = new OrderDetailPO(shopInfo.getShopName(), "普通打印", orderInfo.getTableName(), orderInfo.getOrderNo(), DateUtils.getTime(new Date(orderInfo.getCreatedAt())), "【POS-1】001", orderInfo.getOrderAmount().toPlainString(), balance, orderInfo.getPayType(), "0", detailList,orderInfo.getRemark()); + detailPO.setOutNumber(orderInfo.getOutNumber()); String data= PrinterUtils.getCashPrintData(detailPO,"结算单"); PrinterUtils.printTickets(1, Integer.valueOf(printerNum), tbPrintMachineWithBLOBs.getAddress(), data); } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/RabbitConfig.java b/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/RabbitConfig.java index d3380a9..2e1f20c 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/RabbitConfig.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/RabbitConfig.java @@ -27,7 +27,8 @@ public class RabbitConfig { @Value("${spring.rabbitmq.password}") private String password; - + @Value("${prod}") + private String prod; @Bean @@ -49,19 +50,32 @@ public class RabbitConfig { } @Bean public DirectExchange defaultExchange_Register() { - return new DirectExchange(RabbitConstants.CART_PUT); + return new DirectExchange(RabbitConstants.CART_PUT+prod); } @Bean public Queue queuePut_Register() { - return new Queue(RabbitConstants.CART_QUEUE_PUT, true); //队列持久 + return new Queue(RabbitConstants.CART_QUEUE_PUT+prod, true); //队列持久 } @Bean public Binding bindingPut_Register() { - return BindingBuilder.bind(queuePut_Register()).to(defaultExchange_Register()).with(RabbitConstants.CART_ROUTINGKEY_PUT); + return BindingBuilder.bind(queuePut_Register()).to(defaultExchange_Register()).with(RabbitConstants.CART_ROUTINGKEY_PUT+prod); + } + @Bean + public DirectExchange defaultIntegral() { + return new DirectExchange(RabbitConstants.INTEGRAL_PUT); } + @Bean + public Queue queueIntegral() { + return new Queue(RabbitConstants.INTEGRAL_QUEUE_PUT, true); //队列持久 + } + + @Bean + public Binding bindingIntegral() { + return BindingBuilder.bind(queueIntegral()).to(defaultIntegral()).with(RabbitConstants.INTEGRAL_ROUTINGKEY_PUT); + } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/RabbitConstants.java b/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/RabbitConstants.java index e9adf1b..1e44c86 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/RabbitConstants.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/RabbitConstants.java @@ -29,4 +29,13 @@ public interface RabbitConstants { public static final String PRINT_MECHINE_COLLECT_ROUTINGKEY_PUT = "print_mechine_collect_routingkey_put_wx"; + + + + public static final String INTEGRAL_PUT="integral_put1"; + + public static final String INTEGRAL_QUEUE_PUT = "integral_queue_put1"; + + + public static final String INTEGRAL_ROUTINGKEY_PUT = "integral_routingkey_put1"; } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/RabbitProducer.java b/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/RabbitProducer.java index 2627adf..5498148 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/RabbitProducer.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/RabbitProducer.java @@ -7,6 +7,7 @@ import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.connection.CorrelationData; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @@ -16,7 +17,8 @@ public class RabbitProducer implements RabbitTemplate.ConfirmCallback { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private RabbitTemplate rabbitTemplate; - + @Value("${prod}") + private String prod; @Autowired public RabbitProducer(RabbitTemplate rabbitTemplate) { this.rabbitTemplate = rabbitTemplate; @@ -25,7 +27,7 @@ public class RabbitProducer implements RabbitTemplate.ConfirmCallback { public void putCart(String content) { CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString()); - rabbitTemplate.convertAndSend(RabbitConstants.CART_PUT, RabbitConstants.CART_ROUTINGKEY_PUT, content, correlationId); + rabbitTemplate.convertAndSend(RabbitConstants.CART_PUT+prod, RabbitConstants.CART_ROUTINGKEY_PUT+prod, content, correlationId); } public void putOrderCollect(String content) { CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString()); @@ -36,7 +38,10 @@ public class RabbitProducer implements RabbitTemplate.ConfirmCallback { CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString()); rabbitTemplate.convertAndSend(RabbitConstants.PRINT_MECHINE_COLLECT_PUT, RabbitConstants.PRINT_MECHINE_COLLECT_ROUTINGKEY_PUT, content, correlationId); } - + public void printCoupons(String content){ + CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString()); + rabbitTemplate.convertAndSend(RabbitConstants.INTEGRAL_PUT, RabbitConstants.INTEGRAL_ROUTINGKEY_PUT, content, correlationId); + } @Override public void confirm(CorrelationData correlationData, boolean ack, String cause) { logger.info(" 回调id:" + correlationData); diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/redis/RedisConfig.java b/src/main/java/com/chaozhanggui/system/cashierservice/redis/RedisConfig.java index 33e8140..35934b2 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/redis/RedisConfig.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/redis/RedisConfig.java @@ -4,12 +4,16 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.listener.RedisMessageListenerContainer; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; +import java.nio.charset.Charset; + /** * @ClassName RedisConfig * @Author Administrator @@ -80,4 +84,16 @@ public class RedisConfig { container.setConnectionFactory(connectionFactory); return container; } + + @Bean + public RedisTemplate redisTemplate(RedisConnectionFactory factory) { + RedisTemplate template = new RedisTemplate<>(); + // 设置Redis连接工厂 + template.setConnectionFactory(factory); + // 设置默认的Key序列化器为StringRedisSerializer + template.setDefaultSerializer(new StringRedisSerializer()); + // 设置Value序列化器为StringRedisSerializer,并指定字符集编码为UTF-8 + template.setValueSerializer(new StringRedisSerializer(Charset.forName("UTF-8"))); + return template; + } } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/redis/RedisCst.java b/src/main/java/com/chaozhanggui/system/cashierservice/redis/RedisCst.java index fd7d198..8bf5631 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/redis/RedisCst.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/redis/RedisCst.java @@ -10,10 +10,16 @@ public class RedisCst { //在线用户 public static final String ONLINE_USER = "ONLINE_USER:"; + public static final String PHONE_LIMIT = "PHONE_LIMIT:"; public static final String ONLINE_APP_USER = "ONLINE_APP_USER:"; public static final String LDBL_APP_VERSION = "LDBL_APP_VERSION:"; public static final String TABLE_CART = "TABLE:CART:"; + public static final String ORDER_EXPIRED = "ORDER:EXPIRED:"; + public static final String TABLE_ORDER = "TABLE:ORDER:"; public static final String PRODUCT = "PRODUCT:"; - public static final String INTEGRAL_COIN_KEY = ""; + public static final String INTEGRAL_COIN_KEY = "INTEGRAL:COIN:KEY"; + public static final String COUPONS_COIN_KEY = "COUPONS:COIN:KEY"; + + public static final String OUT_NUMBER="ORDER:NUMBER:"; } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/redis/RedisUtil.java b/src/main/java/com/chaozhanggui/system/cashierservice/redis/RedisUtil.java index 6c87667..784732c 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/redis/RedisUtil.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/redis/RedisUtil.java @@ -7,6 +7,7 @@ import org.springframework.stereotype.Component; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; +import java.io.*; import java.util.*; /** @@ -17,7 +18,7 @@ import java.util.*; * @Description redis工具类 */ @Component -public class RedisUtil { +public class RedisUtil{ // 成功标识 private static final int REDIS_SUCCESS = 1; // 失败标识 @@ -109,7 +110,7 @@ public class RedisUtil { * @author wgc * @date 2018-12-19 19:49 */ - public Integer saveMessage(String key, String message, int expire) { + public Integer saveMessage(String key, String message, Long expire) { Jedis jedis = null; try { if (StringUtils.isEmpty(key)) { @@ -159,6 +160,53 @@ public class RedisUtil { } return flag; } + + /** + * 通过key 获取数据的剩余存活时间 + */ + public long getRemainingTime(String key) { + Jedis jedis = null; + long remainingTime = -1; + try { + // 从jedis池中获取一个jedis实例 + jedis = pool.getResource(); + if (database != 0) { + jedis.select(database); + } + + // 获取键的剩余生存时间 + remainingTime = jedis.ttl(key); + } catch (Exception e) { + e.printStackTrace(); + } finally { + // 释放对象池,即获取jedis实例使用后要将对象还回去 + if (jedis != null) { + jedis.close(); + } + } + return remainingTime; + } + + public void setKeyExpirationTime(String key, long seconds) { + Jedis jedis = null; + try { + // 从jedis池中获取一个jedis实例 + jedis = pool.getResource(); + if (database != 0) { + jedis.select(database); + } + // 设置键的存活时间 + jedis.expire(key, seconds); + } catch (Exception e) { + e.printStackTrace(); + } finally { + // 释放对象池,即获取jedis实例使用后要将对象还回去 + if (jedis != null) { + jedis.close(); + } + } + } + /** * @param key * @param message @@ -480,4 +528,128 @@ public class RedisUtil { } return REDIS_FAILED+""; } + + public 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; + } + } + + public 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; + } + } + +// public String serialize(Object list) { +// try { +// ObjectMapper mapper = new ObjectMapper(); +// return mapper.writeValueAsString(list); +// } catch (Exception e) { +// e.printStackTrace(); +// return null; +// } +// } +// public List deserializeJson(String json, Class clazz) { +// try { +// ObjectMapper mapper = new ObjectMapper(); +// return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, clazz)); +// } catch (Exception e) { +// e.printStackTrace(); +// return null; +// } +// } + public byte[] getHashAll(String key) { + Jedis jedis = null; + try { + // 从jedis池中获取一个jedis实例 + jedis = pool.getResource(); + if (database!=0) { + jedis.select(database); + } + byte[] serializedList = jedis.get(key.getBytes()); + return serializedList; + + } catch (Exception e) { + e.printStackTrace(); + } finally { + // 释放对象池,即获取jedis实例使用后要将对象还回去 + if (jedis != null) { + jedis.close(); + } + } + + return null; + } + public int saveHashAll(byte[] key,byte[] value) { + Jedis jedis = null; + try { + // 从jedis池中获取一个jedis实例 + jedis = pool.getResource(); + if (database!=0) { + jedis.select(database); + } + jedis.rpush(key,value); + return REDIS_SUCCESS; + + } catch (Exception e) { + e.printStackTrace(); + } finally { + // 释放对象池,即获取jedis实例使用后要将对象还回去 + if (jedis != null) { + jedis.close(); + } + } + + return REDIS_FAILED; + } + + public Set getSet(String key ){ + Jedis jedis = null ; + Set set = null ; + try { + jedis = pool.getResource(); + set = jedis.smembers(key); + }catch (Exception e) { + e.printStackTrace(); + } finally { + // 释放对象池,即获取jedis实例使用后要将对象还回去 + if (jedis != null) { + jedis.close(); + } + } + return set ; + } + /** + * 往set中添加数据 + * @param key + * @param values + * @return + */ + public Long addSet(String key , String... values ){ + Jedis jedis = null ; + try { + jedis = pool.getResource(); + return jedis.sadd(key,values); + }catch (Exception e) { + e.printStackTrace(); + } finally { + // 释放对象池,即获取jedis实例使用后要将对象还回去 + if (jedis != null) { + jedis.close(); + } + } + return 0L ; + } } 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 38ff434..a0d1540 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/service/CartService.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/CartService.java @@ -5,26 +5,20 @@ 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.entity.dto.ProductCartDto; -import com.chaozhanggui.system.cashierservice.entity.vo.CashierCarVo; 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.sign.CodeEnum; -import com.chaozhanggui.system.cashierservice.sign.Result; -import com.chaozhanggui.system.cashierservice.socket.AppWebSocketServer; -import com.chaozhanggui.system.cashierservice.socket.WebSocketServer; import com.chaozhanggui.system.cashierservice.util.DateUtils; import com.chaozhanggui.system.cashierservice.util.JSONUtil; -import com.chaozhanggui.system.cashierservice.util.SnowFlakeUtil; +import com.chaozhanggui.system.cashierservice.util.N; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; -import javax.annotation.Resource; import java.io.IOException; import java.math.BigDecimal; import java.time.Instant; @@ -36,6 +30,7 @@ import java.util.*; @Service @Slf4j public class CartService { + @Autowired private RedisUtil redisUtil; @Autowired @@ -54,38 +49,72 @@ public class CartService { 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) throws Exception { + public void createCart(JSONObject jsonObject) { try { - - String tableId = jsonObject.getString("tableId"); String shopId = jsonObject.getString("shopId"); + String productId = jsonObject.getString("productId"); + String key = tableId + "-" + shopId; JSONArray jsonArray = new JSONArray(); BigDecimal amount = BigDecimal.ZERO; boolean exist = redisUtil.exists(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId")); if (!exist) { - JSONObject jsonObject1 = new JSONObject(); - jsonObject1.put("status", "fail"); - jsonObject1.put("msg", "该商品库存已售罄"); - jsonObject1.put("data", new ArrayList<>()); - AppWebSocketServer.AppSendInfo(jsonObject1, jsonObject.getString("userId"), true); - throw new MsgException("该商品库存已售罄"); + TbProductSkuWithBLOBs tbProductSkuWithBLOBs = productSkuMapper.selectByPrimaryKey(Integer.valueOf(jsonObject.getString("skuId"))); + Double stock = tbProductSkuWithBLOBs.getStockNumber(); + redisUtil.saveMessage(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), Math.round(stock) + ""); } - if (jsonObject.getInteger("num") > 0) { - String result = redisUtil.seckill(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), jsonObject.getInteger("num").toString()); - if (result.equals("0")) { + String skuNum = redisUtil.getMessage(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId")); + TbProduct tbProduct = productMapper.selectById(Integer.valueOf(productId)); + if (tbProduct.getIsStock() == 1) { + if (Integer.valueOf(skuNum) < 1 && jsonObject.getInteger("num") > 0) { JSONObject jsonObject1 = new JSONObject(); jsonObject1.put("status", "fail"); jsonObject1.put("msg", "该商品库存已售罄"); jsonObject1.put("data", new ArrayList<>()); - AppWebSocketServer.AppSendInfo(jsonObject1, jsonObject.getString("userId"), true); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), key, jsonObject.getString("userId"), true); + log.error("该商品库存已售罄 skuId:{}", jsonObject.getString("skuId")); 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)))) { @@ -96,38 +125,51 @@ public class CartService { jsonObject.getInteger("userId"), jsonObject.getInteger("num"), tableId, jsonObject.getString("shopId")); jsonArray.add(cashierCart); amount = amount.add(new BigDecimal(cashierCart.getNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee()))); + if (jsonObject.getInteger("num") > 0) { + redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "1"); + } else { + redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "2"); + } + productSkuMapper.updateStockById(jsonObject.getString("skuId"), jsonObject.getInteger("num")); } } else { boolean flag = true; for (int i = 0; i < array.size(); i++) { JSONObject object = array.getJSONObject(i); - 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()))); - if (StringUtils.isNotEmpty(cashierCart.getStatus())) { - cashierCart.setStatus("create"); + if (cashierCart.getSkuId().equals(jsonObject.getString("skuId"))) { + cashierCart.setTotalNumber(cashierCart.getTotalNumber() + jsonObject.getInteger("num")); + cashierCart.setNumber(cashierCart.getNumber() + jsonObject.getInteger("num")); + if (jsonObject.getInteger("num") > 0) { + redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "1"); + } else { + redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "2"); } - cashierCartMapper.updateByPrimaryKeySelective(cashierCart); + productSkuMapper.updateStockById(jsonObject.getString("skuId"), jsonObject.getInteger("num")); if (cashierCart.getNumber() > 0) { - jsonArray.add(cashierCart); - amount = amount.add(new BigDecimal(cashierCart.getTotalNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee()))); + cashierCart.setTotalAmount(new BigDecimal(cashierCart.getTotalNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee()))); + cashierCart.setUpdatedAt(Instant.now().toEpochMilli()); + cashierCartMapper.updateByPrimaryKeySelective(cashierCart); } else { cashierCartMapper.deleteByPrimaryKey(cashierCart.getId()); + continue; } - } else { - cashierCartMapper.deleteByPrimaryKey(cashierCart.getId()); + flag = false; } + jsonArray.add(cashierCart); + amount = amount.add(new BigDecimal(cashierCart.getTotalNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee()))); } if (flag && jsonObject.getInteger("num") > 0) { TbCashierCart cashierCart = addCart(jsonObject.getString("productId"), jsonObject.getString("skuId"), jsonObject.getInteger("userId"), jsonObject.getInteger("num"), tableId, jsonObject.getString("shopId")); jsonArray.add(cashierCart); amount = amount.add(new BigDecimal(cashierCart.getTotalNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee()))); + if (jsonObject.getInteger("num") > 0) { + redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "1"); + } else { + redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "2"); + } + productSkuMapper.updateStockById(jsonObject.getString("skuId"), jsonObject.getInteger("num")); } } } else { @@ -136,10 +178,10 @@ public class CartService { jsonObject.getInteger("userId"), jsonObject.getInteger("num"), tableId, jsonObject.getString("shopId")); jsonArray.add(cashierCart); amount = amount.add(new BigDecimal(cashierCart.getTotalNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee()))); + redisUtil.getIncrNum(RedisCst.PRODUCT + shopId + ":" + jsonObject.getString("skuId"), "1"); + productSkuMapper.updateStockById(jsonObject.getString("skuId"), jsonObject.getInteger("num")); } } - 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"); @@ -147,78 +189,406 @@ public class CartService { jsonObject1.put("type", jsonObject.getString("type")); jsonObject1.put("data", jsonArray); jsonObject1.put("amount", amount); - AppWebSocketServer.AppSendInfo(jsonObject1, jsonObject.getString("tableId").concat("-").concat(shopId), false); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), jsonObject.getString("tableId").concat("-").concat(shopId), "", false); } catch (Exception e) { - e.getMessage(); + log.error("长链接错误 createCart{}", e.getMessage()); } } private TbCashierCart addCart(String productId, String skuId, Integer userId, Integer num, String tableId, String shopId) throws Exception { - TbProduct product = productMapper.selectById(Integer.valueOf(productId)); - if (Objects.isNull(product)) { - JSONObject jsonObject1 = new JSONObject(); - jsonObject1.put("status", "fail"); - jsonObject1.put("msg", "该商品不存在"); - jsonObject1.put("data", new ArrayList<>()); - AppWebSocketServer.AppSendInfo(jsonObject1, userId.toString(), true); - throw new MsgException("该商品不存在"); + 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; } - 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, 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.setUserId(userId); - 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; } @Transactional(rollbackFor = Exception.class) - public void createOrder(JSONObject jsonObject) throws IOException { + 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; - Map skuMap = new HashMap<>(); + String couponId = ""; + BigDecimal couponAmount = BigDecimal.ZERO; List orderDetails = new ArrayList<>(); Integer orderId = 0; + TbMerchantAccount tbMerchantAccount = merchantAccountMapper.selectByShopId(jsonObject.getString("shopId")); + if (tbMerchantAccount == null) { + MsgException.throwException("生成订单错误"); + } + + String userId = jsonObject.getString("userId"); + TbUserInfo tbUserInfo = userInfoMapper.selectByPrimaryKey(Integer.valueOf(userId)); + if (tbUserInfo == null) { + MsgException.throwException("生成订单失败"); + } for (int i = 0; i < array.size(); i++) { JSONObject object = array.getJSONObject(i); TbCashierCart cashierCart = JSONUtil.parseJSONStr2T(object.toJSONString(), TbCashierCart.class); TbProductSkuWithBLOBs tbProduct = productSkuMapper.selectByPrimaryKey(Integer.valueOf(cashierCart.getSkuId())); totalAmount = totalAmount.add(cashierCart.getTotalAmount()); packAMount = packAMount.add(cashierCart.getPackFee()); + originAmount = originAmount.add(cashierCart.getTotalAmount()); + if (Objects.nonNull(tbProduct)) { + saleAmount = saleAmount.add(tbProduct.getSalePrice()); + } + TbOrderDetail orderDetail = new TbOrderDetail(); + orderDetail.setCreateTime(new Date()); + orderDetail.setNum(cashierCart.getNumber()); + orderDetail.setPrice(cashierCart.getSalePrice()); + if (cashierCart.getIsPack().equals("true")) { + orderDetail.setPriceAmount(cashierCart.getTotalAmount().add(cashierCart.getPackFee())); + } else { + orderDetail.setPriceAmount(cashierCart.getTotalAmount()); + } + orderDetail.setProductId(Integer.valueOf(cashierCart.getProductId())); + orderDetail.setProductSkuId(Integer.valueOf(cashierCart.getSkuId())); + orderDetail.setProductSkuName(tbProduct.getSpecSnap()); + orderDetail.setProductName(cashierCart.getName()); + orderDetail.setShopId(jsonObject.getInteger("shopId")); + orderDetail.setPackAmount(cashierCart.getPackFee()); + orderDetail.setProductImg(cashierCart.getCoverImg()); + orderDetail.setStatus("unpaid"); + if (StringUtils.isNotEmpty(cashierCart.getOrderId())) { + orderId = Integer.valueOf(cashierCart.getOrderId()); + } + orderDetails.add(orderDetail); + if (StringUtils.isNotEmpty(cashierCart.getOrderId())) { + orderId = Integer.valueOf(cashierCart.getOrderId()); + } + cashierCartMapper.updateStatusById(cashierCart.getId(), "final"); + } + //总金额 + TbShopTable shopTable = shopTableMapper.selectQRcode(jsonObject.getString("tableId")); + //生成订单 + TbOrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId); + String isBuyYhq = "false"; + String isuseYhq = "false"; + if (jsonObject.containsKey("isYhq") && jsonObject.getString("isYhq").equals("1")) { + couponId = jsonObject.getString("couponsId"); + //1:购买优惠券,0:自己持有优惠券 + Integer couponsId = jsonObject.getInteger("couponsId"); + if (jsonObject.getString("isBuyYhq").equals("1")) { + TbSystemCoupons systemCoupons = systemCouponsMapper.selectByPrimaryKey(couponsId); + if (Objects.isNull(systemCoupons) || !systemCoupons.getStatus().equals("0")) { + log.info("开始处理订单"); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("status", "fail"); + jsonObject1.put("msg", "优惠券已售空"); + jsonObject1.put("type", jsonObject.getString("type")); + jsonObject1.put("data", ""); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), key, jsonObject.getString("userId"), true); + log.info("消息推送"); + return; + } + if (N.gt(systemCoupons.getCouponsAmount(), totalAmount)) { + log.info("开始处理订单"); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("status", "fail"); + jsonObject1.put("msg", "订单金额小于优惠价金额"); + jsonObject1.put("type", jsonObject.getString("type")); + jsonObject1.put("data", ""); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), key, jsonObject.getString("userId"), true); + log.info("消息推送"); + return; + } + totalAmount = totalAmount.add(systemCoupons.getCouponsPrice()).subtract(systemCoupons.getCouponsAmount()); + originAmount = originAmount.add(systemCoupons.getCouponsPrice()); + couponAmount = systemCoupons.getCouponsAmount(); + systemCoupons.setStatus("1"); + systemCouponsMapper.updateByPrimaryKeySelective(systemCoupons); + TbUserCoupons userCoupons = new TbUserCoupons(); + userCoupons.setEndTime(DateUtils.getNewDate(new Date(), 3, systemCoupons.getDayNum())); + userCoupons.setCouponsAmount(systemCoupons.getCouponsAmount()); + userCoupons.setCouponsPrice(systemCoupons.getCouponsPrice()); + userCoupons.setStatus("1"); + userCoupons.setUserId(userId); + userCoupons.setCreateTime(new Date()); + userCouponsMapper.insert(userCoupons); + couponId = userCoupons.getId() + ""; + couponAmount = userCoupons.getCouponsAmount(); + } else { + TbUserCoupons userCoupons = userCouponsMapper.selectByPrimaryKey(couponsId); + if (Objects.isNull(userCoupons) || !userCoupons.getStatus().equals("0")) { + log.info("开始处理订单"); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("status", "fail"); + jsonObject1.put("msg", "优惠券已使用"); + jsonObject1.put("type", jsonObject.getString("type")); + jsonObject1.put("data", ""); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), key, jsonObject.getString("userId"), true); + log.info("消息推送"); + return; + } + if (N.gt(userCoupons.getCouponsAmount(), totalAmount)) { + log.info("开始处理订单"); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("status", "fail"); + jsonObject1.put("msg", "订单金额小于优惠价金额"); + jsonObject1.put("type", jsonObject.getString("type")); + jsonObject1.put("data", ""); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), key, jsonObject.getString("userId"), true); + log.info("消息推送"); + return; + } + totalAmount = totalAmount.subtract(userCoupons.getCouponsAmount()); + userCoupons.setStatus("1"); + userCoupons.setEndTime(DateUtils.getNewDate(new Date(), 5, 30)); + userCouponsMapper.updateByPrimaryKeySelective(userCoupons); + couponAmount = userCoupons.getCouponsAmount(); + } + isuseYhq = "true"; + + } + if (Objects.nonNull(orderInfo)) { + log.info("订单状态:" + orderInfo.getStatus()); + if (!"unpaid".equals(orderInfo.getStatus())) { + log.info("开始处理订单"); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("status", "fail"); + jsonObject1.put("msg", "订单正在支付中,请稍后再试"); + jsonObject1.put("type", jsonObject.getString("type")); + jsonObject1.put("data", ""); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), key, jsonObject.getString("userId"), true); + log.info("消息推送"); + return; + } + + orderDetailMapper.deleteByOUrderId(orderId); + orderInfo.setUpdatedAt(System.currentTimeMillis()); + orderInfo.setSettlementAmount(totalAmount); + orderInfo.setUserCouponId(couponId); + orderInfo.setUserCouponAmount(couponAmount); + orderInfo.setAmount(totalAmount); + orderInfo.setOriginAmount(originAmount); + orderInfo.setOrderAmount(totalAmount.add(packAMount)); + orderInfo.setFreightAmount(BigDecimal.ZERO); + orderInfo.setProductAmount(saleAmount); + orderInfo.setIsBuyCoupon(isBuyYhq); + orderInfo.setIsUseCoupon(isuseYhq); +// orderInfo.setRemark(StringUtils.isBlank(jsonObject.getString("remark"))?"":jsonObject.getString("remark")); + orderInfoMapper.updateByPrimaryKeySelective(orderInfo); + } else { + orderInfo = getOrder(totalAmount, packAMount, shopTable, tbMerchantAccount.getId().toString(), jsonObject, originAmount); + orderInfo.setMerchantId(String.valueOf(tbMerchantAccount.getId())); + orderInfo.setUserCouponId(couponId); + orderInfo.setOriginAmount(originAmount); + orderInfo.setIsBuyCoupon(isBuyYhq); + orderInfo.setIsUseCoupon(isuseYhq); + orderInfo.setUserCouponAmount(couponAmount); + + JSONObject object=new JSONObject(); + String outNumber= redisUtil.getMessage(RedisCst.OUT_NUMBER.concat(jsonObject.getString("shopId"))); + Integer number=1; + if(Objects.isNull(outNumber)){ + object.put("outNumber",number); + object.put("times",DateUtils.getDay()); + }else { + object=JSONObject.parseObject(outNumber); + if(object.getString("times").equals(DateUtils.getDay())){ + number=object.getInteger("outNumber")+1; + object.put("outNumber",number); + }else { + object.put("outNumber",number); + object.put("times",DateUtils.getDay()); + } + } + orderInfo.setOutNumber(number+""); + redisUtil.saveMessage(RedisCst.OUT_NUMBER.concat(jsonObject.getString("shopId")),object.toString()); + orderInfoMapper.insert(orderInfo); + orderId = orderInfo.getId(); + } + for (TbOrderDetail orderDetail : orderDetails) { + orderDetail.setOrderId(orderId); + orderDetailMapper.insert(orderDetail); + } + for (int i = 0; i < array.size(); i++) { + JSONObject object = array.getJSONObject(i); + TbCashierCart cashierCart = JSONUtil.parseJSONStr2T(object.toJSONString(), TbCashierCart.class); + cashierCart.setUpdatedAt(System.currentTimeMillis()); + cashierCart.setOrderId(orderId + ""); + cashierCart.setStatus("closed"); + cashierCartMapper.updateByPrimaryKeySelective(cashierCart); + object.put("updatedAt", System.currentTimeMillis()); + object.put("orderId", orderId + ""); + } + redisUtil.saveMessage(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId")).concat("-").concat(shopId), array.toJSONString()); + orderInfo.setDetailList(orderDetails); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("status", "success"); + jsonObject1.put("msg", "成功"); + jsonObject1.put("type", jsonObject.getString("type")); + jsonObject1.put("data", orderInfo); + redisUtil.deleteByKey(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId")).concat("-").concat(shopId)); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), key, jsonObject.getString("userId"), true); + JSONObject jsonObject12 = new JSONObject(); + jsonObject12.put("status", "success"); + jsonObject12.put("msg", "成功"); + jsonObject12.put("type", "order"); + jsonObject12.put("amount", BigDecimal.ZERO); + + jsonObject12.put("data", new JSONArray()); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject12.toString(), jsonObject.getString("tableId").concat("-").concat(shopId), "", false); + redisUtil.saveMessage(RedisCst.ORDER_EXPIRED.concat(orderId.toString()), orderId.toString(), 60 * 16L); + } catch (Exception e) { + log.info("长链接错误 addCart{}", e.getMessage()); + e.printStackTrace(); + } + } + + private TbOrderInfo getOrder(BigDecimal totalAmount, BigDecimal packAMount, + TbShopTable shopTable, String merchantId, JSONObject jsonObject, BigDecimal originAmount) { + TbOrderInfo orderInfo = new TbOrderInfo(); + String orderNo = generateOrderNumber(); + orderInfo.setOrderNo(orderNo); + orderInfo.setSettlementAmount(totalAmount); + orderInfo.setPackFee(packAMount); + orderInfo.setOriginAmount(originAmount); + orderInfo.setProductAmount(originAmount); + orderInfo.setAmount(totalAmount); + orderInfo.setOrderAmount(totalAmount.add(packAMount)); + orderInfo.setPayAmount(BigDecimal.ZERO); + orderInfo.setRefundAmount(new BigDecimal("0.00")); + orderInfo.setTableId(jsonObject.getString("tableId")); + orderInfo.setSendType("table"); + orderInfo.setOrderType("miniapp"); + orderInfo.setTradeDay(DateUtils.getDay()); + orderInfo.setStatus("unpaid"); + orderInfo.setShopId(jsonObject.getString("shopId")); + orderInfo.setUserId(jsonObject.getString("userId")); + orderInfo.setCreatedAt(Instant.now().toEpochMilli()); + orderInfo.setSystemTime(Instant.now().toEpochMilli()); + orderInfo.setUpdatedAt(Instant.now().toEpochMilli()); + orderInfo.setIsAccepted((byte) 1); + if (Objects.nonNull(shopTable)) { + orderInfo.setTableName(shopTable.getName()); + } + orderInfo.setMerchantId(merchantId); + return orderInfo; + } + + public String generateOrderNumber() { + String date = DateUtils.getSdfTimes(); + Random random = new Random(); + int randomNum = random.nextInt(900) + 100; + return "WX" + date + randomNum; + } + + public void clearCart(JSONObject jsonObject) { + try { + String shopId = jsonObject.getString("shopId"); + if (redisUtil.exists(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId)))) { + JSONArray array = JSON.parseArray(redisUtil.getMessage(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId)))); + if (Objects.isNull(array) || array.isEmpty() || array.size() < 1) { + for (int i = 0; i < array.size(); i++) { + TbCashierCart cashierCart = JSONUtil.parseJSONStr2T(array.get(i).toString(), TbCashierCart.class); + redisUtil.secAdd(RedisCst.PRODUCT+shopId+":"+jsonObject.getString("skuId"),cashierCart.getNumber().toString()); + productSkuMapper.updateAddStockById(jsonObject.getString("skuId"), cashierCart.getNumber()); + + } + } + } + cashierCartMapper.updateStatusByTableId(jsonObject.getString("tableId"), "closed"); + redisUtil.saveMessage(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId)), new JSONArray().toJSONString()); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("status", "success"); + jsonObject1.put("msg", "成功"); + jsonObject1.put("type", "clearCart"); + jsonObject1.put("amount", BigDecimal.ZERO); + jsonObject1.put("data", new ArrayList<>()); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), jsonObject.getString("tableId").concat("-").concat(shopId), "", false); + } catch (Exception e) { + log.info("长链接错误 clearCart{}", e.getMessage()); + e.printStackTrace(); + } + } + + @Transactional(rollbackFor = Exception.class) + public void pendingOrder(JSONObject jsonObject) throws IOException { + try { + String shopId = jsonObject.getString("shopId"); + String tableId = jsonObject.getString("tableId"); + String key = tableId + "-" + shopId; + JSONArray array = JSON.parseArray(redisUtil.getMessage(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId)))); + List ids = new ArrayList<>(); + BigDecimal totalAmount = BigDecimal.ZERO; + BigDecimal packAMount = BigDecimal.ZERO; + BigDecimal originAmount = BigDecimal.ZERO; + BigDecimal saleAmount = BigDecimal.ZERO; + String couponId = ""; + BigDecimal couponAmount = BigDecimal.ZERO; + Map skuMap = new HashMap<>(); + List orderDetails = new ArrayList<>(); + Integer orderId = 0; + TbMerchantAccount tbMerchantAccount = merchantAccountMapper.selectByShopId(jsonObject.getString("shopId")); + if (tbMerchantAccount == null) { + throw new MsgException("生成订单错误"); + } + + String userId = jsonObject.getString("userId"); + TbUserInfo tbUserInfo = userInfoMapper.selectByPrimaryKey(Integer.valueOf(userId)); + if (tbUserInfo == null) { + throw new MsgException("生成订单失败"); + } + for (int i = 0; i < array.size(); i++) { + JSONObject object = array.getJSONObject(i); + TbCashierCart cashierCart = JSONUtil.parseJSONStr2T(object.toJSONString(), TbCashierCart.class); + TbProductSkuWithBLOBs tbProduct = productSkuMapper.selectByPrimaryKey(Integer.valueOf(cashierCart.getSkuId())); + totalAmount = totalAmount.add(cashierCart.getTotalAmount()); + packAMount = packAMount.add(cashierCart.getPackFee()); + originAmount = originAmount.add(cashierCart.getTotalAmount()); if (Objects.nonNull(tbProduct)) { saleAmount = saleAmount.add(tbProduct.getSalePrice()); } @@ -249,19 +619,88 @@ public class CartService { orderId = Integer.valueOf(cashierCart.getOrderId()); } } - - TbMerchantAccount tbMerchantAccount = merchantAccountMapper.selectByShopId(jsonObject.getString("shopId")); - if (tbMerchantAccount == null) { - throw new MsgException("生成订单错误"); - } - - TbUserInfo tbUserInfo = userInfoMapper.selectByPrimaryKey(jsonObject.getInteger("userId")); - if (tbUserInfo == null) { - throw new MsgException("生成订单失败"); - } + //总金额 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())) { @@ -271,7 +710,7 @@ public class CartService { jsonObject1.put("msg", "订单正在支付中,请稍后再试"); jsonObject1.put("type", jsonObject.getString("type")); jsonObject1.put("data", ""); - AppWebSocketServer.AppSendInfo(jsonObject1, jsonObject.getString("userId"), true); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject1.toString(), key, jsonObject.getString("userId"), true); log.info("消息推送"); return; } @@ -279,40 +718,45 @@ public class CartService { orderDetailMapper.deleteByOUrderId(orderId); orderInfo.setUpdatedAt(System.currentTimeMillis()); orderInfo.setSettlementAmount(totalAmount); + orderInfo.setUserCouponId(couponId); + orderInfo.setUserCouponAmount(couponAmount); orderInfo.setAmount(totalAmount); - orderInfo.setOriginAmount(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 = new TbOrderInfo(); - String orderNo = generateOrderNumber(); - orderInfo.setOrderNo(orderNo); - orderInfo.setSettlementAmount(totalAmount); - orderInfo.setPackFee(packAMount); - orderInfo.setOriginAmount(totalAmount); - orderInfo.setProductAmount(totalAmount); - 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 = 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); + + JSONObject object=new JSONObject(); + String outNumber= redisUtil.getMessage(RedisCst.OUT_NUMBER.concat(jsonObject.getString("shopId"))); + Integer number=1; + if(Objects.isNull(outNumber)){ + object.put("outNumber",number); + object.put("times",DateUtils.getDay()); + }else { + object=JSONObject.parseObject(outNumber); + if(object.getString("times").equals(DateUtils.getDay())){ + number=object.getInteger("outNumber")+1; + object.put("outNumber",number); + }else { + object.put("outNumber",number); + object.put("times",DateUtils.getDay()); + } + } + orderInfo.setOutNumber(number+""); + redisUtil.saveMessage(RedisCst.OUT_NUMBER.concat(jsonObject.getString("shopId")),object.toString()); + + orderInfoMapper.insert(orderInfo); orderId = orderInfo.getId(); } @@ -338,7 +782,8 @@ public class CartService { 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, jsonObject.getString("userId"), true); + 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", "成功"); @@ -346,38 +791,34 @@ public class CartService { jsonObject12.put("amount", BigDecimal.ZERO); jsonObject12.put("data", new JSONArray()); - AppWebSocketServer.AppSendInfo(jsonObject12, jsonObject.getString("tableId").concat("-").concat(shopId), false); + PushToAppChannelHandlerAdapter.getInstance().AppSendInfo(jsonObject12.toString(), jsonObject.getString("tableId").concat("-").concat(shopId), "", false); } catch (Exception e) { - e.getMessage(); + log.info("长链接错误 pendingOrder{}", e.getMessage()); + e.printStackTrace(); } } - 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) throws IOException { - 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()); - } + 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(); } - 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); } + } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/FileService.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/FileService.java new file mode 100644 index 0000000..0d079ae --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/FileService.java @@ -0,0 +1,66 @@ +package com.chaozhanggui.system.cashierservice.service; + +import com.aliyun.oss.OSS; +import com.aliyun.oss.OSSClientBuilder; +import com.aliyun.oss.common.auth.CredentialsProvider; +import com.aliyun.oss.common.auth.DefaultCredentialProvider; +import com.chaozhanggui.system.cashierservice.util.DateUtils; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import javax.annotation.PostConstruct; +import java.util.UUID; + +@Service +@Slf4j +public class FileService { + + @Value("${aliyun.keyid}") + private String accessKeyId; + @Value("${aliyun.keysecret}") + private String accessKeySecret; + @Value("${aliyun.oss.endpoint}") + private String endpoint; + @Value("${aliyun.oss.bucketname}") + private String bucketName; + + // 创建阿里云登录凭证 + public CredentialsProvider credentialsProvider; + + @PostConstruct + public void init() { + credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret); + } + + + public String uploadFile(MultipartFile file) throws Exception { + String suffix = FilenameUtils.getExtension(file.getResource().getFilename()); + String path = getPath("upload", suffix); + OSS client = new OSSClientBuilder().build(endpoint, credentialsProvider); + try { + client.putObject(bucketName, path, file.getInputStream()); + client.shutdown(); + } catch (Exception e) { + throw new Exception("上传异常"); + } + + return "https://" + bucketName + "." + endpoint + "/" + path; + } + + public String getPath(String prefix, String suffix) { + //生成uuid + String uuid = UUID.randomUUID().toString().replaceAll("-", ""); + //文件路径 + String path = DateUtils.getDays() + "/" + uuid; + + if (StringUtils.isNotBlank(prefix)) { + path = prefix + "/" + path; + } + + return path + "." + suffix; + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/GroupOrderCouponService.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/GroupOrderCouponService.java new file mode 100644 index 0000000..5bc0db8 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/GroupOrderCouponService.java @@ -0,0 +1,48 @@ +package com.chaozhanggui.system.cashierservice.service; + +import com.chaozhanggui.system.cashierservice.entity.TbGroupOrderCoupon; +import com.chaozhanggui.system.cashierservice.dao.TbGroupOrderCouponMapper; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; + +/** + * 团购卷 卷码表(TbGroupOrderCoupon)表服务实现类 + * + * @author ww + * @since 2024-05-06 14:39:59 + */ +@Service +public class GroupOrderCouponService { + @Resource + private TbGroupOrderCouponMapper tbGroupOrderCouponMapper; + + /** + * 通过ID查询单条数据 + * + * @param id 主键 + * @return 实例对象 + */ + public TbGroupOrderCoupon queryById(Integer id) { + return this.tbGroupOrderCouponMapper.queryById(id); + } + + public List queryByOrderId(Integer orderId) { + return tbGroupOrderCouponMapper.queryByOrderId(orderId); + } + + public List queryNoRefundByOrderId(Integer orderId) { + return tbGroupOrderCouponMapper.queryNoRefundByOrderId(orderId); + } + + public TbGroupOrderCoupon insert(TbGroupOrderCoupon tbGroupOrderCoupon) { + this.tbGroupOrderCouponMapper.insert(tbGroupOrderCoupon); + return tbGroupOrderCoupon; + } + + public TbGroupOrderCoupon update(TbGroupOrderCoupon tbGroupOrderCoupon) { + this.tbGroupOrderCouponMapper.update(tbGroupOrderCoupon); + return this.queryById(tbGroupOrderCoupon.getId()); + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/GroupOrderInfoService.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/GroupOrderInfoService.java new file mode 100644 index 0000000..99dd1da --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/GroupOrderInfoService.java @@ -0,0 +1,178 @@ +package com.chaozhanggui.system.cashierservice.service; + +import com.chaozhanggui.system.cashierservice.dao.*; +import com.chaozhanggui.system.cashierservice.entity.*; +import com.chaozhanggui.system.cashierservice.entity.dto.CreateGroupOrderDto; +import com.chaozhanggui.system.cashierservice.entity.dto.GroupOrderDto; +import com.chaozhanggui.system.cashierservice.entity.vo.GroupOrderDetailsVo; +import com.chaozhanggui.system.cashierservice.entity.vo.GroupOrderListVo; +import com.chaozhanggui.system.cashierservice.entity.vo.ProductVo; +import com.chaozhanggui.system.cashierservice.exception.MsgException; +import com.chaozhanggui.system.cashierservice.sign.CodeEnum; +import com.chaozhanggui.system.cashierservice.sign.Result; +import com.chaozhanggui.system.cashierservice.util.DateUtils; +import com.chaozhanggui.system.cashierservice.util.JSONUtil; +import com.chaozhanggui.system.cashierservice.util.LocationUtils; +import com.github.pagehelper.Page; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.math.BigDecimal; +import java.util.Date; +import java.util.List; +import java.util.Random; + +@Service +@Slf4j +public class GroupOrderInfoService { + @Autowired + private TbShopInfoMapper shopInfoMapper; + @Autowired + private TbProductMapper tbProductMapper; + @Resource + private TbGroupOrderInfoMapper tbGroupOrderInfoMapper; + @Autowired + private GroupOrderCouponService groupOrderCouponService; + @Autowired + private TbMerchantAccountMapper merchantAccountMapper; + @Resource + private TbPurchaseNoticeMapper noticeMapper; + + /** + * 通过ID查询单条数据 + * + * @param id 主键 + * @return 实例对象 + */ + + public Result queryById(Integer id, String lng, String lat) { + TbGroupOrderInfo groupOrder = tbGroupOrderInfoMapper.queryById(id); + GroupOrderDetailsVo result = new GroupOrderDetailsVo(); + result.setId(id); + result.setProId(groupOrder.getProId()); + result.setProName(groupOrder.getProName()); + result.setProImg(groupOrder.getProImg()); + TbPurchaseNotice tbPurchaseNotice = noticeMapper.queryByCouponId(groupOrder.getProId()); + if(tbPurchaseNotice!=null){ + result.setAvaTime(tbPurchaseNotice.getAvailableTime()+" | 到店吃"); + result.setNotice(tbPurchaseNotice); + } +// result.setProDetail(); //随时退·过期自动退·到店 + result.setOrderAmount(groupOrder.getOrderAmount()); + + if(!groupOrder.getStatus().equals("unpaid")){ + if(!groupOrder.getStatus().equals("closed")){ + result.setExpDate(groupOrder.getNumber()- + groupOrder.getRefundNumber() + "张可用 | " + + DateUtils.getTimeM( + groupOrder.getExpDate())+" 到期"); + } + } + result.setRefundAble(groupOrder.getRefundAble()); + List tbGroupOrderCoupons = groupOrderCouponService.queryByOrderId(id); + result.setCoupons(tbGroupOrderCoupons); + + TbShopInfo shopInfo = shopInfoMapper.selectByPrimaryKey(groupOrder.getShopId()); + result.setShopName(shopInfo.getShopName()); + result.setIsUseVip(shopInfo.getIsUseVip()); + String distance = LocationUtils.getDistanceString( + Double.parseDouble(lng), Double.parseDouble(lat), + Double.parseDouble(shopInfo.getLng()), Double.parseDouble(shopInfo.getLat())); + result.setDistances(distance); + result.setAddress(shopInfo.getAddress()); + result.setShopPhone(shopInfo.getPhone()); + + TbProductWithBLOBs product = tbProductMapper.selectByPrimaryKey(groupOrder.getProId()); + result.setTagVos(JSONUtil.parseListTNewList(product.getGroupSnap(), ProductVo.class)); + + + result.setOrderNo(groupOrder.getOrderNo()); + result.setPhone(groupOrder.getPhone()); + if (groupOrder.getPayTime() != null) { + result.setPayTime(DateUtils.getTime(groupOrder.getPayTime())); + } + result.setNumber(groupOrder.getNumber()); + result.setPayAmount(groupOrder.getPayAmount()); + result.setSaveAmount(groupOrder.getSaveAmount()); + result.setStatus(groupOrder.getStatus()); + return Result.success(CodeEnum.SUCCESS, result); + } + + + /** + * 分页查询 + * + * @return 查询结果 + */ + public Result queryByPage(GroupOrderDto param) { + PageHelper.startPage(param.getPage(), param.getSize()); + return new Result(CodeEnum.SUCCESS,new PageInfo<>(tbGroupOrderInfoMapper.queryAll(param))); + } + + /** + * 新增数据 + * + * @return 实例对象 + */ + public Result insert(CreateGroupOrderDto param) { + TbMerchantAccount tbMerchantAccount = merchantAccountMapper.selectByShopId(param.getShopId().toString()); + if (tbMerchantAccount == null) { + throw new MsgException("生成订单错误"); + } + + TbGroupOrderInfo tbGroupOrderInfo = new TbGroupOrderInfo(); + tbGroupOrderInfo.setOrderNo(generateOrderNumber()); + tbGroupOrderInfo.setMerchantId(tbMerchantAccount.getId()); + tbGroupOrderInfo.setShopId(param.getShopId()); + tbGroupOrderInfo.setProId(param.getProId()); + tbGroupOrderInfo.setUserId(param.getUserId()); + tbGroupOrderInfo.setPhone(param.getPhone()); + TbProduct tbProduct = tbProductMapper.selectById(param.getProId()); + tbGroupOrderInfo.setProImg(tbProduct.getCoverImg()); + tbGroupOrderInfo.setProName(tbProduct.getName()); + tbGroupOrderInfo.setNumber(param.getNum()); + tbGroupOrderInfo.setRefundNumber(0); + tbGroupOrderInfo.setOrderAmount(param.getOrderAmount()); + tbGroupOrderInfo.setRefundAmount(BigDecimal.ZERO); + tbGroupOrderInfo.setSaveAmount(param.getOrderAmount().subtract(param.getPayAmount())); + tbGroupOrderInfo.setPayAmount(param.getPayAmount()); + tbGroupOrderInfo.setStatus("unpaid"); + tbGroupOrderInfo.setRemark(param.getRemark()); + tbGroupOrderInfo.setCreateTime(new Date()); + tbGroupOrderInfo.setTradeDay(new Date()); + tbGroupOrderInfo.setRefundAble(1); + int insert = tbGroupOrderInfoMapper.insert(tbGroupOrderInfo); + if (insert > 0) { + return new Result(CodeEnum.SUCCESS,tbGroupOrderInfo); + } else { + return new Result(CodeEnum.FAIL); + } + } + + public String generateOrderNumber() { + String date = DateUtils.getSdfTimes(); + Random random = new Random(); + int randomNum = random.nextInt(900) + 100; + return "GP" + date + randomNum; + } + + /** + * 修改数据 + * + * @param tbGroupOrderInfo 实例对象 + * @return 实例对象 + */ + + public Result update(TbGroupOrderInfo tbGroupOrderInfo) { + int update = tbGroupOrderInfoMapper.update(tbGroupOrderInfo); + if (update > 0) { + return new Result(CodeEnum.SUCCESS); + } else { + return new Result(CodeEnum.FAIL); + } + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/HomeDistrictService.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/HomeDistrictService.java new file mode 100644 index 0000000..cadd4b4 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/HomeDistrictService.java @@ -0,0 +1,154 @@ +package com.chaozhanggui.system.cashierservice.service; + +import com.chaozhanggui.system.cashierservice.dao.SysDictMapper; +import com.chaozhanggui.system.cashierservice.dao.TbCouponCategoryMapper; +import com.chaozhanggui.system.cashierservice.dao.TbPlatformDictMapper; +import com.chaozhanggui.system.cashierservice.dao.TbShopInfoMapper; +import com.chaozhanggui.system.cashierservice.entity.SysDict; +import com.chaozhanggui.system.cashierservice.entity.TbCouponCategory; +import com.chaozhanggui.system.cashierservice.entity.TbPlatformDict; +import com.chaozhanggui.system.cashierservice.entity.dto.ComShopDto; +import com.chaozhanggui.system.cashierservice.entity.dto.HomeBaseDto; +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.util.JSONUtil; +import com.chaozhanggui.system.cashierservice.util.LocationUtils; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; + +import javax.annotation.Resource; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +@Service +@Slf4j +public class HomeDistrictService { + @Resource + private ProductService productService; + + @Resource + private TbShopInfoMapper shopInfoMapper; + @Resource + private TbPlatformDictMapper platformDictMapper; + @Resource + private TbCouponCategoryMapper couponCategoryMapper; + @Resource +// private SysDictDetailMapper sysDictDetailMapper; + private SysDictMapper sysDictMapper; + + public Result topCommon(HomeDto param, String environment){ + CommonVo result = new CommonVo(); + String type = param.getType(); + //预约到店 + if (StringUtils.isNotBlank(param.getType())) { + if(type.equals("subShop")){ + List carouselList = platformDictMapper.queryAllByType(type,environment); + result.setCarousel(JSONUtil.parseListTNewList(carouselList, HomeCarouselVo.class)); + result.setTitle(carouselList.get(0).getName()); + }else {//商品分类页 + TbCouponCategory tbCouponCategory = couponCategoryMapper.queryById(Integer.valueOf(param.getType())); + result.setTitle(tbCouponCategory.getName()); + List carouselList = platformDictMapper.queryGroupByValue(param.getType(), environment); + if (!CollectionUtils.isEmpty(carouselList)) { + result.setCarousel(JSONUtil.parseListTNewList(carouselList, HomeCarouselVo.class)); + } + List sysDicts = sysDictMapper.selectByType(null); + for (SysDict sysDict : sysDicts) { + if (sysDict.getIsChild().equals("1")) { + sysDict.setDetail(sysDictMapper.selectByDictId(sysDict.getDictId())); + } + sysDict.setIsChild((sysDict.getIsChild() == null || sysDict.getIsChild().equals("0")) ? false : true); + } + result.setMenu(sysDicts); + } + } else { + if (param.getOrderBy() != null) { + if (param.getOrderBy() == 0) { + List carouselList = platformDictMapper.queryAllByType("newCoupon", environment); + if (!CollectionUtils.isEmpty(carouselList)) { + result.setCarousel(JSONUtil.parseListTNewList(carouselList, HomeCarouselVo.class)); + } + result.setTitle("今日上新"); + } else if (param.getOrderBy() == 4) { + List carouselList = platformDictMapper.queryAllByType("hotCoupon", environment); + if (!CollectionUtils.isEmpty(carouselList)) { + result.setCarousel(JSONUtil.parseListTNewList(carouselList, HomeCarouselVo.class)); + } + result.setTitle("热榜推荐"); + List sysDicts = sysDictMapper.selectHot(); + for (SysDict sysDict : sysDicts) { + if (sysDict.getIsChild().equals("1")) { + sysDict.setDetail(sysDictMapper.selectByDictId(sysDict.getDictId())); + } + sysDict.setIsChild((sysDict.getIsChild() == null || sysDict.getIsChild().equals("0")) ? false : true); + } + result.setMenu(sysDicts); + } + } + } + return Result.success(CodeEnum.SUCCESS, result); + } + + public Result queryShopListByPage(HomeBaseDto param) { + PageHelper.startPage(param.getPage(), param.getSize()); + Map topAndBottomMap = LocationUtils.returnLLSquarePoint( + Double.parseDouble(param.getLng()), + Double.parseDouble(param.getLat()), + param.getDistanceInKm()); + List subShopVos = shopInfoMapper.selShopInfoByGps( + topAndBottomMap.get("rightTopPoint")[1],//109.06198684730003 + topAndBottomMap.get("rightTopPoint")[0],//34.39724773780949 + topAndBottomMap.get("leftBottomPoint")[1], + topAndBottomMap.get("leftBottomPoint")[0], + param.getAddress(), param.getLng(), param.getLat(),null);//西安市 + for (SubShopVo subShopVo : subShopVos) {//距离计算 + if (StringUtils.isNotBlank(subShopVo.getLat()) && StringUtils.isNotBlank(subShopVo.getLng())) { + String distance = LocationUtils.getDistanceString( + Double.parseDouble(param.getLng()), Double.parseDouble(param.getLat()), + Double.parseDouble(subShopVo.getLng()), Double.parseDouble(subShopVo.getLat())); + subShopVo.setDistances(distance); + } + } + return Result.success(CodeEnum.SUCCESS, new PageInfo(subShopVos)); + + } + + public Result queryComShopList(ComShopDto param) { + Map topAndBottomMap = LocationUtils.returnLLSquarePoint( + Double.parseDouble(param.getLng()), + Double.parseDouble(param.getLat()), + param.getDistanceInKm()); + List subShopVos = shopInfoMapper.selShopInfoByGps( + topAndBottomMap.get("rightTopPoint")[1],//109.06198684730003 + topAndBottomMap.get("rightTopPoint")[0],//34.39724773780949 + topAndBottomMap.get("leftBottomPoint")[1], + topAndBottomMap.get("leftBottomPoint")[0], + param.getAddress(), param.getLng(), param.getLat(),param.getShopName());//西安市 + for (SubShopVo subShopVo : subShopVos) {//距离计算 + subShopVo.setBusinessTime(subShopVo.getBusinessStartDay()+"至"+subShopVo.getBusinessEndDay()+" "+subShopVo.getBusinessTime()); + if (StringUtils.isNotBlank(subShopVo.getLat()) && StringUtils.isNotBlank(subShopVo.getLng())) { + String distance = LocationUtils.getDistanceString( + Double.parseDouble(param.getLng()), Double.parseDouble(param.getLat()), + Double.parseDouble(subShopVo.getLng()), Double.parseDouble(subShopVo.getLat())); + subShopVo.setDistances(distance); + } + } + return Result.success(CodeEnum.SUCCESS, subShopVos); + + } + + /** + * 通用商品页 + */ + public Result proList(HomeDto param) { + return Result.success(CodeEnum.SUCCESS, productService.products(param)); + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/HomePageService.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/HomePageService.java index 046a935..35b2e8c 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/service/HomePageService.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/HomePageService.java @@ -1,22 +1,29 @@ package com.chaozhanggui.system.cashierservice.service; -import com.chaozhanggui.system.cashierservice.dao.*; -import com.chaozhanggui.system.cashierservice.entity.*; +import com.chaozhanggui.system.cashierservice.dao.SysDictMapper; +import com.chaozhanggui.system.cashierservice.dao.TbPlatformDictMapper; +import com.chaozhanggui.system.cashierservice.dao.TbProductSkuMapper; +import com.chaozhanggui.system.cashierservice.entity.Enum.LogoEnum; +import com.chaozhanggui.system.cashierservice.entity.SysDict; +import com.chaozhanggui.system.cashierservice.entity.TbPlatformDict; import com.chaozhanggui.system.cashierservice.entity.dto.HomeDto; import com.chaozhanggui.system.cashierservice.entity.vo.*; +import com.chaozhanggui.system.cashierservice.redis.RedisUtil; import com.chaozhanggui.system.cashierservice.sign.CodeEnum; import com.chaozhanggui.system.cashierservice.sign.Result; -import com.chaozhanggui.system.cashierservice.util.Threads; +import com.chaozhanggui.system.cashierservice.util.BigDecimalUtils; +import com.chaozhanggui.system.cashierservice.util.JSONUtil; +import com.chaozhanggui.system.cashierservice.util.RandomUtil; +import com.chaozhanggui.system.cashierservice.util.StringUtil; +import com.github.pagehelper.PageInfo; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.math.BigDecimal; -import java.math.RoundingMode; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; /** * @author lyf @@ -24,121 +31,39 @@ import java.util.concurrent.ExecutionException; @Service @Slf4j public class HomePageService { - @Resource - private TbShopInfoMapper shopInfoMapper; @Resource private TbProductSkuMapper productSkuMapper; @Resource private TbPlatformDictMapper platformDictMapper; @Resource - private TbMerchantCouponMapper merchantCouponMapper; + private SysDictMapper sysDictMapper; @Resource - private TbProductMapper productMapper; - @Resource - private SysDictDetailMapper sysDictDetailMapper; + private ProductService productService; + @Autowired + private RedisUtil redisUtil; - - public Result homePage(HomeDto homeDto,String environmen) throws ExecutionException, InterruptedException { - int beginNo; - if(homeDto.getPage() <=0){ - beginNo = 0; - }else{ - beginNo = (homeDto.getPage() - 1) * homeDto.getSize(); - } - //优惠卷 - List tbMerchantCoupons = merchantCouponMapper.queryAllByPage(beginNo, homeDto.getSize()); - //统计shopId,以及productId - List shopIds = new ArrayList<>(); - List productIds = new ArrayList<>(); - for (TbMerchantCoupon coupon : tbMerchantCoupons) { - shopIds.add(coupon.getShopId()); - productIds.add(coupon.getRelationIds()); - } - CompletableFuture> shopInfo = CompletableFuture.supplyAsync(() -> - shopInfoMapper.selectByIds(shopIds)); - CompletableFuture> product = CompletableFuture.supplyAsync(() -> - productMapper.selectByIds((productIds))); - CompletableFuture> productSku = CompletableFuture.supplyAsync(() -> - productSkuMapper.selectSkus((productIds))); - CompletableFuture> dictPro = CompletableFuture.supplyAsync(() -> - platformDictMapper.queryAllByType("proTag",environmen)); - CompletableFuture> dictShop = CompletableFuture.supplyAsync(() -> - platformDictMapper.queryAllByType("shopTag",environmen)); - Threads.call(shopInfo,product,productSku,dictPro,dictShop); - boolean isFirstAdded = true; - //组装 - List homeVOList = new ArrayList<>(); - for (TbMerchantCoupon o :tbMerchantCoupons) { - HomeVO homeVO = new HomeVO(); - homeVO.setDiscount(o.getRatio()); - if (isFirstAdded){ - homeVO.setShopTag(dictShop.get().get(0).getName()); - homeVO.setProTag(dictPro.get().get(0).getName()); - isFirstAdded = false; - } - for (TbShopInfo tbShopInfo : shopInfo.get()) { - if (o.getShopId().equals(tbShopInfo.getId().toString())) { - homeVO.setShopName(tbShopInfo.getShopName()); - homeVO.setImage(tbShopInfo.getLogo()); - } - } - for (TbProduct tbProduct :product.get()) { - if (o.getRelationIds().equals(tbProduct.getId().toString())) { - homeVO.setProductName(tbProduct.getName()); - homeVO.setImage(tbProduct.getCoverImg()); - homeVO.setId(tbProduct.getId()); - } - } - for (TbProductSku tbProductSku :productSku.get()) { - if (o.getRelationIds().equals(tbProductSku.getProductId())) { - homeVO.setOriginPrice(tbProductSku.getSalePrice()); - homeVO.setRealSalesNumber(tbProductSku.getRealSalesNumber() == null?BigDecimal.ZERO: new BigDecimal(tbProductSku.getRealSalesNumber())); - Float discount = homeVO.getDiscount(); - BigDecimal discountDecimal = new BigDecimal(discount); - homeVO.setSalePrice(tbProductSku.getSalePrice().multiply((discountDecimal.multiply(new BigDecimal("0.1"))))); - homeVO.setSave(homeVO.getOriginPrice().subtract(homeVO.getSalePrice())); - } - } - homeVOList.add(homeVO); - } - - return Result.success(CodeEnum.SUCCESS,homeVOList); - } - - public Result homePageUp(String environment){ + public Result homePageUp(String environment) { HomeUpVO homeUpVO = new HomeUpVO(); //轮播图 - List carouselList = platformDictMapper.queryAllByType("carousel",environment); - homeUpVO.setCarousel(carouselList); + List carouselList = platformDictMapper.queryAllByType("carousel", environment); + homeUpVO.setCarousel(JSONUtil.parseListTNewList(carouselList, HomeCarouselVo.class)); //金刚区 - List districtList = platformDictMapper.queryAllByType("homeDistrict",environment); - homeUpVO.setDistrict(districtList); + List districtList = platformDictMapper.queryAllByType("homeDistrict", environment); + homeUpVO.setDistrict(JSONUtil.parseListTNewList(districtList, HomeDistrictVo.class)); + //菜单 - List sysDicts = sysDictDetailMapper.selectByAll(); - List dicDetailVO = new ArrayList<>(); - for (SysDict sysDictsList : sysDicts) { - DicDetailVO dicDetailVOList = new DicDetailVO(); - dicDetailVOList.setName(sysDictsList.getName()); - dicDetailVOList.setDescription(sysDictsList.getDescription()); - dicDetailVOList.setDetail(sysDictDetailMapper.selectByDictId(sysDictsList.getDictId())); - dicDetailVOList.setIsChild(sysDictsList.getIsChild()); - dicDetailVO.add(dicDetailVOList); + List sysDicts = sysDictMapper.selectByType("home"); + for (SysDict sysDict : sysDicts) { + if (sysDict.getIsChild().equals(1)) { + sysDict.setDetail(sysDictMapper.selectByDictId(sysDict.getDictId())); + } + sysDict.setIsChild((sysDict.getIsChild() == null || sysDict.getIsChild().equals(0)) ? false : true); } - homeUpVO.setMenu(dicDetailVO); + homeUpVO.setMenu(sysDicts); /** * 销量榜 */ List homeVOs = productSkuMapper.selectSale(); - for (HomeVO o : homeVOs) { - BigDecimal originPrice = o.getOriginPrice(); - if (originPrice.compareTo(BigDecimal.ZERO)!= 0){ - BigDecimal multiply = o.getSalePrice().divide(o.getOriginPrice(),2,RoundingMode.DOWN).multiply(BigDecimal.TEN); - o.setDiscount(multiply.floatValue()); - }else { - o.setDiscount(null); - } - } - HotRankingVO hotRankingVO = new HotRankingVO(); hotRankingVO.setHotList(homeVOs); homeUpVO.setSalesList(hotRankingVO); @@ -146,11 +71,52 @@ public class HomePageService { *每日榜 */ List homeVODay = productSkuMapper.selectDay(); + for (HomeVO o : homeVODay) { + BigDecimal originPrice = o.getOriginPrice(); + if (originPrice.compareTo(BigDecimal.ZERO) != 0) { + o.setDiscount(BigDecimalUtils.getDiscount(o.getOriginPrice(),o.getSalePrice())); + } else { + o.setDiscount(null); + } + } TodayRankingVO todayRankingVO = new TodayRankingVO(); todayRankingVO.setTodayList(homeVODay); homeUpVO.setTodayList(todayRankingVO); - return Result.success(CodeEnum.SUCCESS,homeUpVO); + /** + * 小条幅 + */ + homeUpVO.setBannerVO(bannerVoRandom()); + + return Result.success(CodeEnum.SUCCESS, homeUpVO); + } + + /** + * 商品列表 + */ + public Result proList(HomeDto homeDto) { + PageInfo products = productService.products(homeDto); + return Result.success(CodeEnum.SUCCESS, products); + } + + /** + * 小条幅随机数据 + * @return + */ + private BannerVO bannerVoRandom(){ + BannerVO bannerVO = new BannerVO(); + List bannerInfoList = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + BannerInfoVo bannerInfoVo = new BannerInfoVo(); + bannerInfoVo.setName(StringUtil.generateRandomNickname(5)); + bannerInfoVo.setLogo(LogoEnum.getValueByKey(RandomUtil.randomInt())); + bannerInfoVo.setMoney(RandomUtil.randomDecimalGenerator()); + bannerInfoList.add(bannerInfoVo); + } + bannerVO.setCounponsInfo(bannerInfoList); + bannerVO.setCoupons(redisUtil.getMessage("num")); + return bannerVO; } + } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/IntegralService.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/IntegralService.java new file mode 100644 index 0000000..3d948da --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/IntegralService.java @@ -0,0 +1,117 @@ +package com.chaozhanggui.system.cashierservice.service; + +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.RedisUtil; +import com.chaozhanggui.system.cashierservice.util.DateUtils; +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 javax.annotation.Resource; +import java.math.BigDecimal; +import java.text.ParseException; +import java.util.*; + +/** + * @author lyf + */ +@Service +@Slf4j +public class IntegralService { + @Autowired + private RedisUtil redisUtil; + @Autowired + private TbOrderInfoMapper orderInfoMapper; + @Autowired + private TbUserInfoMapper userInfoMapper; + @Autowired + private TbProductMapper productMapper; + @Autowired + private TbProductSkuMapper productSkuMapper; + @Autowired + private TbShopInfoMapper shopInfoMapper; + @Autowired + private TbShopUserMapper tbShopUserMapper; + @Resource + private TbReleaseFlowMapper integralFlowMapper; + @Autowired + private TbUserCouponsMapper userCouponsMapper; + @Autowired + private TbSplitAccountsMapper splitAccountsMapper; + + @Transactional(rollbackFor = Exception.class) + public void integralAdd(JSONObject jsonObject) throws ParseException { + String type = jsonObject.getString("type"); + if (type.equals("trade")){ + //优惠券兑换积分 + Integer integralId = jsonObject.getInteger("integralId"); + TbUserCoupons userCoupons = userCouponsMapper.selectByPrimaryKey(integralId); + if (Objects.isNull(userCoupons) || !"0".equals(userCoupons.getStatus())){ + throw new MsgException("优惠券已被使用"); + } + userCoupons.setStatus("trade"); + userCoupons.setUpdateTime(new Date()); + userCouponsMapper.updateByPrimaryKeySelective(userCoupons); + TbParams params = tbShopUserMapper.selectParams(); + TbReleaseFlow integralFlow = new TbReleaseFlow(); + integralFlow.setNum(userCoupons.getCouponsAmount().multiply(params.getTradeRatio())); + integralFlow.setCreateTime(new Date()); + integralFlow.setFromSource(userCoupons.getId()+""); + integralFlow.setType("TRADEADD"); + integralFlow.setUserId(userCoupons.getUserId()); + integralFlowMapper.insert(integralFlow); + TbUserInfo userInfo = userInfoMapper.selectByPrimaryKey(Integer.valueOf(userCoupons.getUserId())); + if (Objects.nonNull(userInfo)){ + userInfo.setTotalScore(userInfo.getTotalScore() + integralFlow.getNum().intValue()); + userInfoMapper.updateByPrimaryKeySelective(userInfo); + } + }else { + Integer orderId = jsonObject.getInteger("orderId"); + TbOrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId); + if (StringUtils.isNotBlank(orderInfo.getUserCouponId())){ + TbUserCoupons userCoupons = userCouponsMapper.selectByPrimaryKey(Integer.valueOf(orderInfo.getUserCouponId())); + if (Objects.nonNull(userCoupons)){ + TbShopInfo shopInfo = shopInfoMapper.selectByPrimaryKey(Integer.valueOf(orderInfo.getShopId())); + TbSplitAccounts splitAccounts = new TbSplitAccounts(); + splitAccounts.setConponsAmount(userCoupons.getCouponsAmount()); + splitAccounts.setCreateTime(new Date()); + splitAccounts.setIsSplit("false"); + splitAccounts.setMerchantId(Integer.valueOf(shopInfo.getMerchantId())); + splitAccounts.setShopId(shopInfo.getId()); + splitAccounts.setOrderAmount(orderInfo.getPayAmount()); + splitAccounts.setTradeDay(DateUtils.getDay()); + splitAccounts.setOriginAmount(orderInfo.getOriginAmount()); + splitAccountsMapper.insert(splitAccounts); + } + } + if (Objects.isNull(orderInfo)) { + log.error("该订单不存在"); + return; + } + TbShopInfo shopInfo = shopInfoMapper.selectByPrimaryKey(Integer.valueOf(orderInfo.getShopId())); + if (Objects.isNull(shopInfo) || !"true".equals(shopInfo.getIsOpenYhq())){ + log.error("该店铺未开启优惠券功能"); + return; + } + + TbParams params = tbShopUserMapper.selectParams(); + TbUserCoupons userCoupons = new TbUserCoupons(); + userCoupons.setUserId(orderInfo.getUserId()); + userCoupons.setCouponsAmount(orderInfo.getOrderAmount().subtract(orderInfo.getUserCouponAmount()).multiply(params.getIntegralRatio())); + userCoupons.setStatus("0"); + userCoupons.setOrderId(orderId); + userCoupons.setCouponsPrice(userCoupons.getCouponsAmount().multiply(new BigDecimal("0.5"))); + userCoupons.setCreateTime(new Date()); + userCoupons.setEndTime(DateUtils.getNewDate(new Date(),3,30)); + //执行插入方法 + userCouponsMapper.insert(userCoupons); + } + + } + +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/LoginService.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/LoginService.java index 0e9532c..3773928 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/service/LoginService.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/LoginService.java @@ -9,18 +9,22 @@ 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.util.JSONUtil; import com.chaozhanggui.system.cashierservice.util.MD5Utils; import com.chaozhanggui.system.cashierservice.util.TokenUtil; +import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; import java.math.BigDecimal; import java.util.*; @Service +@Slf4j public class LoginService { @@ -50,105 +54,114 @@ public class LoginService { @Transactional(rollbackFor = Exception.class) - public Result wxCustomLogin(String openId, String headImage, String nickName, String telephone, String qrCode, String ip) throws Exception { - - TbUserInfo userInfo = tbUserInfoMapper.selectByOpenId(openId); - if (ObjectUtil.isNull(userInfo)) { - userInfo = new TbUserInfo(); - - userInfo.setAmount(BigDecimal.ZERO); - userInfo.setChargeAmount(BigDecimal.ZERO); - userInfo.setLineOfCredit(BigDecimal.ZERO); - userInfo.setConsumeNumber(0); - userInfo.setConsumeAmount(BigDecimal.ZERO); - userInfo.setTotalScore(0); - userInfo.setLockScore(0); - userInfo.setHeadImg(ObjectUtil.isNotNull(headImage) ? headImage : ""); - userInfo.setNickName(ObjectUtil.isNotNull(nickName) ? nickName : "微信用户"); - userInfo.setTelephone(ObjectUtil.isNotNull(telephone) ? telephone : ""); - userInfo.setMiniAppOpenId(openId); - userInfo.setStatus(Byte.parseByte("1")); - userInfo.setParentType("PERSON"); - userInfo.setIsResource(Byte.parseByte("0")); - userInfo.setIsOnline(Byte.parseByte("0")); - userInfo.setIsVip(Byte.parseByte("0")); - userInfo.setSourcePath("WECHAT-APP"); - userInfo.setIsAttentionMp(Byte.parseByte("0")); - userInfo.setSearchWord("||微信用户"); - userInfo.setLastLogInAt(System.currentTimeMillis()); - userInfo.setCreatedAt(System.currentTimeMillis()); - userInfo.setUpdatedAt(System.currentTimeMillis()); - tbUserInfoMapper.insert(userInfo); - - } else { - userInfo.setHeadImg(ObjectUtil.isNotNull(headImage) ? headImage : ""); - userInfo.setNickName(ObjectUtil.isNotNull(nickName) ? nickName : "微信用户"); - userInfo.setTelephone(ObjectUtil.isNotNull(telephone) ? telephone : ""); - tbUserInfoMapper.updateByPrimaryKeySelective(userInfo); - } - //app与微信用户 互相关联 - if (ObjectUtil.isNotNull(telephone)) { - TbUserInfo appUser = tbUserInfoMapper.selectByPhone(telephone); - if (appUser != null) { - TbUserInfo wechatUser = tbUserInfoMapper.selectByOpenId(openId); - appUser.setUserId(wechatUser.getId()); - tbUserInfoMapper.updateByPrimaryKey(appUser); - wechatUser.setUserId(appUser.getId()); - tbUserInfoMapper.updateByPrimaryKey(wechatUser); + public Result wxCustomLogin(String openId, String headImage, String nickName, String telephone, String ip) throws Exception { + TbUserInfo userInfo = new TbUserInfo(); + if(StringUtils.isNotBlank(telephone)){ + userInfo = tbUserInfoMapper.selectByPhone(telephone); + if (ObjectUtil.isNull(userInfo)) { + userInfo = tbUserInfoMapper.selectByOpenId(openId); + if (ObjectUtil.isNull(userInfo)) { + userInfo = new TbUserInfo(); + userInfo.setAmount(BigDecimal.ZERO); + userInfo.setChargeAmount(BigDecimal.ZERO); + userInfo.setLineOfCredit(BigDecimal.ZERO); + userInfo.setConsumeNumber(0); + userInfo.setConsumeAmount(BigDecimal.ZERO); + userInfo.setTotalScore(0); + userInfo.setLockScore(0); + userInfo.setHeadImg("https://cashier-oss.oss-cn-beijing.aliyuncs.com/upload/20240411/a2be5869bfa24d72a4782f695cc53ed1.png"); + userInfo.setNickName(ObjectUtil.isNotNull(nickName) ? nickName : "微信用户"); + userInfo.setTelephone(telephone); + userInfo.setMiniAppOpenId(openId); + userInfo.setStatus(Byte.parseByte("1")); + userInfo.setParentType("PERSON"); + userInfo.setIsResource(Byte.parseByte("0")); + userInfo.setIsOnline(Byte.parseByte("0")); + userInfo.setIsVip(Byte.parseByte("0")); + userInfo.setSourcePath("WECHAT-APP"); + userInfo.setIsAttentionMp(Byte.parseByte("0")); + userInfo.setSearchWord("||微信用户"); + userInfo.setIsPwd("0"); + userInfo.setPwd(MD5Utils.md5("123456")); + userInfo.setLastLogInAt(System.currentTimeMillis()); + userInfo.setCreatedAt(System.currentTimeMillis()); + userInfo.setUpdatedAt(System.currentTimeMillis()); + tbUserInfoMapper.insert(userInfo); + List tbShopUsers = tbShopUserMapper.selectByPhone(telephone); + if (!CollectionUtils.isEmpty(tbShopUsers)) { + for (TbShopUser tbShopUser : tbShopUsers) { + tbShopUser.setUserId(userInfo.getId() + ""); + tbShopUser.setUpdatedAt(System.currentTimeMillis()); + tbShopUserMapper.updateByPrimaryKey(tbShopUser); + } + } + }else { + userInfo.setTelephone(telephone); + userInfo.setUpdatedAt(System.currentTimeMillis()); + tbUserInfoMapper.updateByPrimaryKeySelective(userInfo); + List tbShopUsers = tbShopUserMapper.selectByPhone(telephone); + if (!CollectionUtils.isEmpty(tbShopUsers)) { + for (TbShopUser tbShopUser : tbShopUsers) { + tbShopUser.setUserId(null); + tbShopUser.setUpdatedAt(System.currentTimeMillis()); + tbShopUserMapper.updateByPrimaryKey(tbShopUser); + } + } + } + }else { + if(!userInfo.getMiniAppOpenId().equals(openId)){ + userInfo.setMiniAppOpenId(openId); + userInfo.setUpdatedAt(System.currentTimeMillis()); + tbUserInfoMapper.updateByPrimaryKeySelective(userInfo); + } + } + }else { + userInfo = tbUserInfoMapper.selectByOpenId(openId); + if(ObjectUtil.isNull(userInfo)){ + userInfo = new TbUserInfo(); + userInfo.setAmount(BigDecimal.ZERO); + userInfo.setChargeAmount(BigDecimal.ZERO); + userInfo.setLineOfCredit(BigDecimal.ZERO); + userInfo.setConsumeNumber(0); + userInfo.setConsumeAmount(BigDecimal.ZERO); + userInfo.setTotalScore(0); + userInfo.setLockScore(0); + userInfo.setHeadImg("https://cashier-oss.oss-cn-beijing.aliyuncs.com/upload/20240411/a2be5869bfa24d72a4782f695cc53ed1.png"); + userInfo.setNickName(ObjectUtil.isNotNull(nickName) ? nickName : "微信用户"); + userInfo.setTelephone(telephone); + userInfo.setMiniAppOpenId(openId); + userInfo.setStatus(Byte.parseByte("1")); + userInfo.setParentType("PERSON"); + userInfo.setIsResource(Byte.parseByte("0")); + userInfo.setIsOnline(Byte.parseByte("0")); + userInfo.setIsVip(Byte.parseByte("0")); + userInfo.setSourcePath("WECHAT-APP"); + userInfo.setIsAttentionMp(Byte.parseByte("0")); + userInfo.setSearchWord("||微信用户"); + userInfo.setIsPwd("0"); + userInfo.setPwd(MD5Utils.md5("123456")); + userInfo.setLastLogInAt(System.currentTimeMillis()); + userInfo.setCreatedAt(System.currentTimeMillis()); + userInfo.setUpdatedAt(System.currentTimeMillis()); + tbUserInfoMapper.insert(userInfo); } } - TbShopInfo tbShopInfo = null; - if (ObjectUtil.isEmpty(qrCode)) { - tbShopInfo = tbShopInfoMapper.selectByPhone(defaultPhone); - - - } else { - tbShopInfo = tbShopInfoMapper.selectByQrCode(qrCode); - } - - - TbShopUser tbShopUser = null; - Map shopMap = new HashMap<>(); - if (ObjectUtil.isNotEmpty(tbShopInfo)) { - tbShopUser = tbShopUserMapper.selectByUserIdAndShopId(userInfo.getId().toString(), tbShopInfo.getId().toString()); - if (ObjectUtil.isEmpty(tbShopUser)) { - tbShopUser = new TbShopUser(); - tbShopUser.setAmount(BigDecimal.ZERO); - tbShopUser.setCreditAmount(BigDecimal.ZERO); - tbShopUser.setConsumeAmount(BigDecimal.ZERO); - tbShopUser.setConsumeNumber(0); - tbShopUser.setLevelConsume(BigDecimal.ZERO); - tbShopUser.setStatus(Byte.parseByte("1")); - tbShopUser.setShopId(tbShopInfo.getId().toString()); - tbShopUser.setUserId(userInfo.getId().toString()); - tbShopUser.setMiniOpenId(openId); - tbShopUser.setCreatedAt(System.currentTimeMillis()); - tbShopUserMapper.insert(tbShopUser); - } - shopMap.put("shopId", tbShopUser.getShopId()); - shopMap.put("name", tbShopInfo.getShopName()); - shopMap.put("amount", BigDecimal.ZERO.toPlainString()); - shopMap.put("levelConsume", BigDecimal.ZERO.toPlainString()); - - } - - //生成token 信息 String token = TokenUtil.generateToken(userInfo.getId(), userInfo.getMiniAppOpenId(), userInfo.getTelephone(), userInfo.getNickName()); - - //存储登录记录 - TbToken tbToken = new TbToken(tbShopInfo.getId(), userInfo.getId(), "wx_lite", token, ip, "1", new Date()); - tbTokenMapper.insert(tbToken); - - Map map = new HashMap<>(); try { map.put("token", token); map.put("userInfo", userInfo); - map.put("shopUser", shopMap); - map.put("shopInfo", tbShopInfo); - redisUtil.saveMessage(RedisCst.ONLINE_USER.concat(openId), JSON.toJSONString(map)); + redisUtil.saveMessage(RedisCst.ONLINE_USER.concat(openId), JSON.toJSONString(map),60*60*24*30L); + //redis里 获取要关注的公众号信息 + //userInfo 某字段存储关注公众号的标识 +// userInfo.get + //公众号 appid + //展示描述 + //图标 +// map.put("", ); + log.info("登录传参 结果:" + JSONUtil.toJSONString(map)); return Result.success(CodeEnum.SUCCESS, map); } catch (Exception e) { e.printStackTrace(); @@ -157,7 +170,15 @@ public class LoginService { return Result.fail("登录失败"); } - public TbUserInfo register(String phone, String password, String nickName) { + /** + * APP注册 + * + * @param phone + * @param password + * @param nickName + * @return + */ + public TbUserInfo register(String phone, String openId,String password, String nickName) { TbUserInfo userInfo = new TbUserInfo(); userInfo.setAmount(BigDecimal.ZERO); @@ -167,7 +188,7 @@ public class LoginService { userInfo.setConsumeAmount(BigDecimal.ZERO); userInfo.setTotalScore(0); userInfo.setLockScore(0); - userInfo.setHeadImg(""); + userInfo.setHeadImg("https://cashier-oss.oss-cn-beijing.aliyuncs.com/upload/20240411/a2be5869bfa24d72a4782f695cc53ed1.png");//默认头像 userInfo.setNickName(nickName); userInfo.setTelephone(phone); userInfo.setStatus(Byte.parseByte("1")); @@ -181,20 +202,19 @@ public class LoginService { userInfo.setLastLogInAt(System.currentTimeMillis()); userInfo.setCreatedAt(System.currentTimeMillis()); userInfo.setUpdatedAt(System.currentTimeMillis()); - if(StringUtils.isNotBlank(password)){ + userInfo.setMiniAppOpenId(openId); + userInfo.setIsPwd("0"); + userInfo.setPwd(MD5Utils.md5("123456")); + if (StringUtils.isNotBlank(password)) { userInfo.setPassword(MD5Utils.MD5Encode(password, "UTF-8")); } - tbUserInfoMapper.insert(userInfo); - //注册时 app与微信小程序用户关联 - TbUserInfo wechatUser = tbUserInfoMapper.selectUserByPhone(phone, "WECHAT-APP"); - TbUserInfo appUser = tbUserInfoMapper.selectByPhone(phone); - if (wechatUser != null) { - appUser.setUserId(wechatUser.getId()); - tbUserInfoMapper.updateByPrimaryKey(appUser); - wechatUser.setUserId(appUser.getId()); - tbUserInfoMapper.updateByPrimaryKey(wechatUser); + List tbShopUsers = tbShopUserMapper.selectByPhone(phone); + for (TbShopUser tbShopUser : tbShopUsers) { + tbShopUser.setUserId(userInfo.getId() + ""); + tbShopUserMapper.updateByPrimaryKey(tbShopUser); } - return appUser; + tbUserInfoMapper.insert(userInfo); + return userInfo; } /** @@ -217,19 +237,38 @@ public class LoginService { } @Transactional(rollbackFor = Exception.class) - public Result appLogin(String username, String password) { - TbUserInfo userInfo = tbUserInfoMapper.selectUserByPhone(username, "APP"); + public Result appLogin(String username,String openId, String password) { + TbUserInfo userInfo = tbUserInfoMapper.selectByPhone(username); if (ObjectUtil.isNull(userInfo)) { - //注册 - userInfo=register(username, password, username); + if (StringUtils.isNotBlank(password)) { + return Result.fail("暂未设置密码,请使用验证码登录"); + } + userInfo = register(username,openId, password, username); + } else { + if (StringUtils.isNotBlank(userInfo.getMiniAppOpenId())) { + if (!userInfo.getMiniAppOpenId().equals(openId)) { + userInfo.setMiniAppOpenId(openId); + } + } + String searchWord = userInfo.getSearchWord(); + if (!searchWord.contains("移动端用户")) { + userInfo.setSearchWord(userInfo.getSearchWord() + "||移动端用户"); + userInfo.setUpdatedAt(System.currentTimeMillis()); + tbUserInfoMapper.updateByPrimaryKeySelective(userInfo); + } } - if (StringUtils.isNotBlank(password) && !password.equalsIgnoreCase(userInfo.getPassword())) { - return Result.fail("密码错误"); + if (StringUtils.isNotBlank(password)) {//未使用验证码 + if (StringUtils.isBlank(userInfo.getPassword())) { + return Result.fail("暂未设置密码,请使用验证码登录"); + } else if (!password.equalsIgnoreCase(userInfo.getPassword())) { + return Result.fail("用户名或密码错误"); + } } + //生成token 信息 String token = null; try { - token = TokenUtil.generateToken(userInfo.getId(), null, userInfo.getTelephone(), userInfo.getNickName()); + token = TokenUtil.generateToken(userInfo.getId(), userInfo.getMiniAppOpenId(), userInfo.getTelephone(), userInfo.getNickName()); } catch (Exception e) { throw new RuntimeException(e); } @@ -237,7 +276,12 @@ public class LoginService { try { map.put("token", token); map.put("userInfo", userInfo); - redisUtil.saveMessage(RedisCst.ONLINE_APP_USER.concat(userInfo.getId() + ""), JSON.toJSONString(map)); + if (StringUtils.isNotBlank(userInfo.getMiniAppOpenId())) { + redisUtil.saveMessage(RedisCst.ONLINE_USER.concat(userInfo.getMiniAppOpenId()), JSON.toJSONString(map), 60 * 60 * 24 * 30L); + } else { + redisUtil.saveMessage(RedisCst.ONLINE_USER.concat(userInfo.getId() + ""), JSON.toJSONString(map), 60 * 60 * 24 * 30L); + } +// redisUtil.saveMessage(RedisCst.ONLINE_APP_USER.concat(userInfo.getId() + ""), JSON.toJSONString(map),60*60*24*30L); return Result.success(CodeEnum.SUCCESS, map); } catch (Exception e) { e.printStackTrace(); @@ -246,12 +290,11 @@ public class LoginService { return Result.fail("登录失败"); } - public Result createCardNo(String id, String openId) { + public Result createCardNo(String id, String openId, String shopId) { if (ObjectUtil.isEmpty(id) || ObjectUtil.isEmpty(openId)) { return Result.fail("head 信息不允许为空"); } - TbUserInfo userInfo = tbUserInfoMapper.selectByPrimaryKey(Integer.valueOf(id)); if (userInfo == null || ObjectUtil.isEmpty(userInfo)) { userInfo = tbUserInfoMapper.selectByOpenId(openId); @@ -261,49 +304,103 @@ public class LoginService { return Result.fail("用户信息不存在"); } - String cardNo = RandomUtil.randomNumbers(10); - userInfo.setCardNo(cardNo); - userInfo.setUpdatedAt(System.currentTimeMillis()); - tbUserInfoMapper.updateByPrimaryKeySelective(userInfo); - return Result.success(CodeEnum.SUCCESS, cardNo); + TbShopUser tbShopUser = tbShopUserMapper.selectByUserIdAndShopId(userInfo.getId().toString(), shopId); + if (ObjectUtil.isEmpty(tbShopUser) || tbShopUser == null) { + return Result.fail("用户信息错误"); + } + + String dynamicCode = RandomUtil.randomNumbers(8); + dynamicCode = StringUtils.rightPad(tbShopUser.getId(), 6, "0").concat(dynamicCode); + + tbShopUser.setDynamicCode("46".concat(dynamicCode)); + tbShopUser.setUpdatedAt(System.currentTimeMillis()); + tbShopUserMapper.updateByPrimaryKeySelective(tbShopUser); + + + return Result.success(CodeEnum.SUCCESS, "46"+dynamicCode); } - public Result userInfo(Integer userId, String shopId) { + public Result userInfo(Integer userId) { TbUserInfo tbUserInfo = tbUserInfoMapper.selectByPrimaryKey(userId); - if (tbUserInfo == null) { return Result.success(CodeEnum.ENCRYPT, new ArrayList()); } - - - TbShopInfo tbShopInfo = null; - if (ObjectUtil.isEmpty(shopId)) { - tbShopInfo = tbShopInfoMapper.selectByPhone(defaultPhone); - } else { - tbShopInfo = tbShopInfoMapper.selectByPrimaryKey(Integer.valueOf(shopId)); - } - - TbShopUser tbShopUser = null; - Map shopMap = new HashMap<>(); - if (ObjectUtil.isNotEmpty(tbShopInfo)) { - tbShopUser = tbShopUserMapper.selectByUserIdAndShopId(tbUserInfo.getId().toString(), tbShopInfo.getId().toString()); - shopMap.put("shopId", tbShopUser.getShopId()); - shopMap.put("name", tbShopInfo.getShopName()); - shopMap.put("amount", BigDecimal.ZERO.toPlainString()); - shopMap.put("levelConsume", BigDecimal.ZERO.toPlainString()); - } - - Map map = new HashMap<>(); - map.put("userInfo", tbUserInfo); - map.put("shopUser", shopMap); - map.put("shopInfo", tbShopInfo); - - - return Result.success(CodeEnum.ENCRYPT, map); + return Result.success(CodeEnum.ENCRYPT, tbUserInfo); } + public Result upPass(String userId, String oldPass, String newPass) { + TbUserInfo tbUserInfo = tbUserInfoMapper.selectByPrimaryKey(Integer.valueOf(userId)); + if (!tbUserInfo.getPassword().equals(oldPass)) { + return Result.success(CodeEnum.FAIL_OLDPASS); + } + if (tbUserInfo.getPassword().equals(newPass)) { + return Result.success(CodeEnum.FAIL_NEWPASS); + } + tbUserInfo.setPassword(newPass); + return upUserInfo(tbUserInfo); + } + + public Result upUserInfo(TbUserInfo userInfo) { + tbUserInfoMapper.updateByPrimaryKeySelective(userInfo); + return Result.success(CodeEnum.SUCCESS); + } + + + public Result resetPwd(String userId, Map map) { + if (ObjectUtil.isNull(map) || ObjectUtil.isEmpty(map) || !map.containsKey("pwd") + || ObjectUtil.isEmpty(map.get("pwd")) || !map.containsKey("code") + || ObjectUtil.isEmpty(map.get("code")) + ) { + return Result.fail("参数错误"); + } + + TbUserInfo userInfo = tbUserInfoMapper.selectByPrimaryKey(Integer.valueOf(userId)); + boolean flag = validate(map.get("code").toString(), userInfo.getTelephone()); + if (!flag) { + return Result.fail("验证码错误"); + } + + + userInfo.setIsPwd("1"); + userInfo.setPwd(MD5Utils.md5(map.get("pwd").toString())); + userInfo.setUpdatedAt(System.currentTimeMillis()); + tbUserInfoMapper.updateByPrimaryKey(userInfo); + + return Result.success(CodeEnum.SUCCESS); + + } + + + public Result modifyPwd(String userId, Map map) { + if (ObjectUtil.isNull(map) || ObjectUtil.isEmpty(map) || !map.containsKey("pwd") + || ObjectUtil.isEmpty(map.get("pwd")) || !map.containsKey("oldpwd") + || ObjectUtil.isEmpty(map.get("oldpwd")) + ) { + return Result.fail("参数错误"); + } + + TbUserInfo userInfo = tbUserInfoMapper.selectByPrimaryKey(Integer.valueOf(userId)); + if (ObjectUtil.isEmpty(userInfo) || ObjectUtil.isNull(userInfo)) { + return Result.fail("用户基本信息不存在"); + } + + if (!userInfo.getPwd().equals(MD5Utils.md5(map.get("oldpwd").toString()))) { + return Result.fail("用户旧密码错误"); + } + + + userInfo.setIsPwd("1"); + userInfo.setPwd(MD5Utils.md5(map.get("pwd").toString())); + userInfo.setUpdatedAt(System.currentTimeMillis()); + tbUserInfoMapper.updateByPrimaryKey(userInfo); + + return Result.success(CodeEnum.SUCCESS); + + } + + public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.println(RandomUtil.randomNumbers(10)); diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/OnlineUserService.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/OnlineUserService.java index d9300d0..85eec9c 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/service/OnlineUserService.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/OnlineUserService.java @@ -4,6 +4,7 @@ package com.chaozhanggui.system.cashierservice.service; import com.chaozhanggui.system.cashierservice.entity.dto.OnlineUserDto; import com.chaozhanggui.system.cashierservice.entity.dto.SecurityProperties; import com.chaozhanggui.system.cashierservice.exception.MsgException; +import com.chaozhanggui.system.cashierservice.util.TokenUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/OrderService.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/OrderService.java index 33463dd..50015b5 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/service/OrderService.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/OrderService.java @@ -1,30 +1,35 @@ package com.chaozhanggui.system.cashierservice.service; import cn.hutool.core.util.ObjectUtil; -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.entity.vo.CashierCarVo; import com.chaozhanggui.system.cashierservice.entity.vo.OrderVo; 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.sign.CodeEnum; import com.chaozhanggui.system.cashierservice.sign.Result; -import com.chaozhanggui.system.cashierservice.socket.AppWebSocketServer; -import com.chaozhanggui.system.cashierservice.util.SnowFlakeUtil; -import org.springframework.data.domain.Page; +import com.chaozhanggui.system.cashierservice.util.DateUtils; +import com.chaozhanggui.system.cashierservice.util.N; +import com.chaozhanggui.system.cashierservice.util.RedisUtils; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +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 javax.annotation.Resource; -import java.awt.print.Pageable; import java.io.IOException; import java.math.BigDecimal; -import java.time.Instant; -import java.util.ArrayList; +import java.text.ParseException; +import java.util.Collections; +import java.util.Date; import java.util.List; +import java.util.Objects; +import java.util.concurrent.TimeUnit; /** * @author 12847 @@ -33,7 +38,7 @@ import java.util.List; public class OrderService { @Resource - private TbCashierCartMapper cashierCartMapper; + private RabbitProducer producer; @Resource private TbOrderInfoMapper orderInfoMapper; @@ -48,18 +53,39 @@ public class OrderService { @Resource private TbUserInfoMapper userInfoMapper; + @Autowired + private TbWiningUserMapper tbWiningUserMapper; @Resource - private TbOrderDetailMapper tbOrderDetailMapper; + private TbOrderDetailMapper tbOrderDetailMapper; + @Autowired + private TbReleaseFlowMapper releaseFlowMapper; + @Resource + private TbParamsMapper paramsMapper; @Resource private RedisUtil redisUtil; + @Resource + private RedisUtils redisUtils; + @Resource + private TbUserCouponsMapper userCouponsMapper; + @Resource + private TbSystemCouponsMapper systemCouponsMapper; + @Autowired + private TbYhqParamsMapper yhqParamsMapper; + @Autowired + private TbShopUserMapper shopUserMapper; + + + @Autowired + private TbOrderInfoMapper tbOrderInfoMapper; /** * 创建订单 + * * @param tableId * @return */ @Transactional(rollbackFor = Exception.class) - public Result createOrder(Integer tableId,Integer shopId,Integer userId){ + public Result createOrder(Integer tableId, Integer shopId, Integer userId) { // //查询该台桌是否还有开启的购物车 // List cashierCarVoList = cashierCartMapper.selectByTableIdOpen(tableId); // if (cashierCarVoList.isEmpty()){ @@ -139,26 +165,25 @@ public class OrderService { // orderVo.setOrderType(orderInfo.getOrderType()); // orderVo.setOrderId(orderInfo.getId()); // orderVo.setSendType(orderInfo.getSendType()); - return Result.success(CodeEnum.ENCRYPT,orderVo); + return Result.success(CodeEnum.ENCRYPT, orderVo); } - public Result orderInfo(Integer orderId){ + public Result orderInfo(Integer orderId) { TbOrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId); - if (orderInfo == null){ + if (orderInfo == null) { return Result.fail("未找到订单"); } - TbShopInfo tbShopInfo = tbShopInfoMapper.selectByPrimaryKey(Integer.valueOf(orderInfo.getShopId())); - if (tbShopInfo == null){ + if (tbShopInfo == null) { return Result.fail("未找到订单"); } TbShopTable tbShopTable = shopTableMapper.selectQRcode(orderInfo.getTableId()); - List details= tbOrderDetailMapper.selectAllByOrderId(orderId); - if(ObjectUtil.isEmpty(details)||details.size()<=0){ + List details = tbOrderDetailMapper.selectAllByOrderId(orderId); + if (ObjectUtil.isEmpty(details) || details.size() <= 0) { return Result.fail("未找到订单"); } @@ -170,38 +195,41 @@ public class OrderService { orderVo.setDetails(details); orderVo.setOrderNo(orderInfo.getOrderNo()); orderVo.setTime(orderInfo.getCreatedAt()); + if (orderInfo.getStatus().equals("paying") || orderInfo.getStatus().equals("unpaid")) { + Long totalSeconds = orderInfo.getCreatedAt() + 15 * 60 * 1000l - System.currentTimeMillis(); + if(totalSeconds>0){ + orderVo.setExpiredMinutes(totalSeconds/1000 / 60); + orderVo.setExpiredSeconds(totalSeconds/1000 % 60); + } + } orderVo.setPayAmount(orderInfo.getOrderAmount()); - orderVo.setTableName(tbShopTable == null?"":tbShopTable.getName()); + orderVo.setTableName(tbShopTable == null ? "" : tbShopTable.getName()); orderVo.setOrderType(orderInfo.getOrderType()); orderVo.setOrderId(orderInfo.getId()); orderVo.setSendType(orderInfo.getSendType()); + orderVo.setOutNumber(orderInfo.getOutNumber()); - return Result.success(CodeEnum.ENCRYPT,orderVo); + return Result.success(CodeEnum.ENCRYPT, orderVo); } - public Result orderList(Integer userId,Integer page,Integer size,String status){ - TbUserInfo tbUserInfo = userInfoMapper.selectByPrimaryKey(userId); - if (tbUserInfo == null){ - return Result.fail("生成订单失败"); - } - //获取页码号 - int beginNo; - if(page <=0){ - beginNo = 0; - }else{ - beginNo = (page - 1) * size; - } - List tbOrderInfos = orderInfoMapper.selectByUserId(userId, beginNo, size,status); + public Result orderList(Integer userId, Integer page, Integer size, String status) { +// TbUserInfo tbUserInfo = userInfoMapper.selectByPrimaryKey(userId); +// if (tbUserInfo == null) { +// return Result.fail("获取订单失败"); +// } + PageHelper.startPage(page, size); + List tbOrderInfos = orderInfoMapper.selectByUserId(userId, status); - for (TbOrderInfo orderInfo:tbOrderInfos){ - List list = tbOrderDetailMapper.selectAllByOrderId(orderInfo.getId()); - int num = 0; - for (TbOrderDetail orderDetail:list){ - num = num+orderDetail.getNum(); - } - orderInfo.setDetailList(list); - orderInfo.setTotalNumber(num); + for (TbOrderInfo orderInfo : tbOrderInfos) { + orderInfo.setDescription(); + List list = tbOrderDetailMapper.selectAllByOrderId(orderInfo.getId()); + int num = 0; + for (TbOrderDetail orderDetail : list) { + num = num + orderDetail.getNum(); + } + orderInfo.setDetailList(list); + orderInfo.setTotalNumber(num); } // // for (OrderVo date :tbOrderInfos) { @@ -216,7 +244,7 @@ public class OrderService { // date.setTotalNumber(number); // } // } - return Result.success(CodeEnum.ENCRYPT,tbOrderInfos); + return Result.success(CodeEnum.ENCRYPT, new PageInfo<>(tbOrderInfos)); } @@ -225,10 +253,185 @@ public class OrderService { // redisUtil.seckill(tableId,message); // AppWebSocketServer.onClosed(tableId); List list = productSkuMapper.selectAll(); - for (TbProductSku productSku:list){ + for (TbProductSku productSku : list) { // productSku.setStockNumber(200.00); - redisUtil.saveMessage("PRODUCT:"+productSku.getShopId()+":"+productSku.getId(),productSku.getStockNumber().intValue()+""); + redisUtil.saveMessage("PRODUCT:" + productSku.getShopId() + ":" + productSku.getId(), "10000"); } } + + @Transactional(rollbackFor = Exception.class) + public Result tradeIntegral(String userId, String id) throws ParseException { + updateIntegral(userId, id); + return Result.success(CodeEnum.ENCRYPT); + } + + private void updateIntegral(String userId, String id) throws ParseException { + + boolean lock_coin = redisUtils.lock(RedisCst.INTEGRAL_COIN_KEY + userId, 5000, TimeUnit.MILLISECONDS); + if (lock_coin) { + TbUserCoupons userCoupons = userCouponsMapper.selectByPrimaryKey(Integer.valueOf(id)); + if (Objects.isNull(userCoupons) || !userCoupons.getStatus().equals("0")) { + throw new MsgException("该优惠券已被使用"); + } + TbParams params = paramsMapper.selectByPrimaryKey(1); + BigDecimal jfAmount = params.getTradeRatio().multiply(userCoupons.getCouponsAmount()); + TbUserInfo tbShopUser = userInfoMapper.selectByPrimaryKey(Integer.valueOf(userId)); + tbShopUser.setTotalScore(tbShopUser.getTotalScore()+jfAmount.intValue()); + userInfoMapper.updateByPrimaryKeySelective(tbShopUser); + userCoupons.setStatus("2"); + userCoupons.setUpdateTime(new Date()); + userCouponsMapper.updateByPrimaryKeySelective(userCoupons); + TbSystemCoupons systemCoupons = new TbSystemCoupons(); + systemCoupons.setEndTime(DateUtils.getNewDate(new Date(),3,30)); + systemCoupons.setCouponsAmount(userCoupons.getCouponsAmount()); + systemCoupons.setCouponsPrice(userCoupons.getCouponsPrice()); + systemCoupons.setStatus("0"); + systemCoupons.setName(userCoupons.getCouponsAmount()+"无门槛优惠券"); + systemCoupons.setCreateTime(new Date()); + String typeName = findName(userCoupons.getCouponsAmount()); + systemCoupons.setTypeName(typeName); + systemCouponsMapper.insert(systemCoupons); + TbReleaseFlow releaseFlow = new TbReleaseFlow(); + releaseFlow.setNum(jfAmount); + releaseFlow.setCreateTime(new Date()); + releaseFlow.setFromSource("OWER"); + releaseFlow.setUserId(userId); + releaseFlow.setOperationType("ADD"); + releaseFlow.setType("EXCHANGEADD"); + releaseFlow.setRemark("兑换增加"); + releaseFlowMapper.insert(releaseFlow); + redisUtils.releaseLock(RedisCst.INTEGRAL_COIN_KEY + userId); + } else { + updateIntegral(userId, id); + } + } + + private String findName(BigDecimal amount) { + List list = yhqParamsMapper.selectAll(); + String typeName = ""; + for (TbYhqParams yhqParams:list){ + if (N.egt(amount,yhqParams.getMinPrice()) && N.gt(yhqParams.getMaxPrice(),amount)){ + typeName = yhqParams.getName(); + break; + } + } + return typeName; + } + + + public Result mineCoupons(String userId, String orderId,String status, Integer page, Integer size) { + BigDecimal amount=null; + if(ObjectUtil.isNotNull(orderId)&&ObjectUtil.isNotEmpty(orderId)){ + TbOrderInfo orderInfo= tbOrderInfoMapper.selectByPrimaryKey(Integer.valueOf(orderId)); + amount=orderInfo.getOriginAmount(); + } + + + PageHelper.startPage(page, size); + List list = userCouponsMapper.selectByUserId(userId,status,amount); + PageInfo pageInfo = new PageInfo(list); + return Result.success(CodeEnum.SUCCESS, pageInfo); + } + + public Result findCoupons(String type, Integer page, Integer size) { + PageHelper.startPage(page, size); + List list = systemCouponsMapper.selectAll(type); + PageInfo pageInfo = new PageInfo(list); + return Result.success(CodeEnum.SUCCESS, pageInfo); + } + + public Result findWiningUser() { + String day = DateUtils.getDay(); + List list = tbWiningUserMapper.selectAllByTrade(day); + return Result.success(CodeEnum.SUCCESS, list); + } + + public Result getYhqPara() { + List list = yhqParamsMapper.selectAll(); + return Result.success(CodeEnum.SUCCESS, list); + } + + public Result testPay(Integer orderId) { + TbOrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId); + orderInfo.setStatus("closed"); + orderInfo.setPayType("wx_lite"); + orderInfo.setPayOrderNo("test"); + orderInfo.setPayAmount(orderInfo.getOrderAmount()); + orderInfoMapper.updateByPrimaryKeySelective(orderInfo); + JSONObject jsonObject=new JSONObject(); + jsonObject.put("token",0); + jsonObject.put("type","wxcreate"); + jsonObject.put("orderId",orderId.toString()); + producer.putOrderCollect(jsonObject.toJSONString()); + JSONObject coupons = new JSONObject(); + coupons.put("type","buy"); + coupons.put("orderId",orderId); + producer.printCoupons(coupons.toJSONString()); + return Result.success(CodeEnum.SUCCESS); + } + + public Result getYhqDouble(Integer orderId) { + TbUserCoupons userCoupons = userCouponsMapper.selectByOrderId(orderId); + if (Objects.nonNull(userCoupons)){ + TbOrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId); + userCoupons.setOrderInfo(orderInfo); + } + return Result.success(CodeEnum.SUCCESS,userCoupons); + } + @Transactional(rollbackFor = Exception.class) + public Result yhqDouble(Integer conponsId) { + TbUserCoupons userCoupons = userCouponsMapper.selectByPrimaryKey(conponsId); + if (Objects.isNull(userCoupons) || userCoupons.getIsDouble().equals("true")){ + throw new MsgException("该优惠券翻倍已领取"); + } + modityDouble(conponsId); + return Result.success(CodeEnum.SUCCESS); + } + + + private void modityDouble(Integer conponsId) { + + boolean lock_coin = redisUtils.lock(RedisCst.COUPONS_COIN_KEY + conponsId, 5000, TimeUnit.MILLISECONDS); + if (lock_coin) { + TbUserCoupons userCoupons = userCouponsMapper.selectByPrimaryKey(conponsId); + if (Objects.isNull(userCoupons) || !userCoupons.getStatus().equals("0") || userCoupons.getIsDouble().equals("true")) { + throw new MsgException("该优惠券已翻倍"); + } + TbParams params = shopUserMapper.selectParams(); + userCoupons.setIsDouble("true"); + userCoupons.setCouponsAmount(userCoupons.getCouponsAmount().multiply(params.getTwoRatio())); + userCoupons.setCouponsPrice(userCoupons.getCouponsPrice().multiply(params.getTwoRatio())); + userCoupons.setUpdateTime(new Date()); + userCouponsMapper.updateByPrimaryKeySelective(userCoupons); + redisUtils.releaseLock(RedisCst.COUPONS_COIN_KEY + conponsId); + } else { + modityDouble(conponsId); + } + } + + public Result mineWinner(Integer userId, Integer page, Integer size) { + PageHelper.startPage(page, size); + List list = orderInfoMapper.selectWinnerByUserId(userId); + for (TbOrderInfo tbOrderInfo:list){ + if (StringUtils.isNotEmpty(tbOrderInfo.getWinnnerNo())){ + tbOrderInfo.setIsWinner("true"); + }else { + tbOrderInfo.setIsWinner("false"); + } + } + PageInfo pageInfo = new PageInfo(list); + if (page > pageInfo.getPages()) { + pageInfo.setList(Collections.emptyList()); + } + return Result.success(CodeEnum.SUCCESS, pageInfo); + } + + public Result kc() { + List list = productSkuMapper.selectAll(); + for (TbProductSku productSku:list){ + redisUtil.saveMessage(RedisCst.PRODUCT + productSku.getShopId() + ":" +productSku.getId(),"10000"); + } + return Result.success(CodeEnum.SUCCESS); + } } 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 4b74b25..585aecc 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/service/PayService.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/PayService.java @@ -1,22 +1,33 @@ package com.chaozhanggui.system.cashierservice.service; import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.RandomUtil; 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.entity.dto.ReturnGroupOrderDto; +import com.chaozhanggui.system.cashierservice.entity.vo.ShopUserListVo; +import com.chaozhanggui.system.cashierservice.exception.MsgException; import com.chaozhanggui.system.cashierservice.model.PayReq; import com.chaozhanggui.system.cashierservice.model.TradeQueryReq; +import com.chaozhanggui.system.cashierservice.netty.PushToClientChannelHandlerAdapter; 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.util.BeanUtil; -import com.chaozhanggui.system.cashierservice.util.MD5Util; -import com.chaozhanggui.system.cashierservice.util.SnowFlakeUtil; +import com.chaozhanggui.system.cashierservice.thirdpay.resp.OrderStatusQueryResp; +import com.chaozhanggui.system.cashierservice.thirdpay.resp.PublicResp; +import com.chaozhanggui.system.cashierservice.thirdpay.resp.WxScanPayResp; +import com.chaozhanggui.system.cashierservice.thirdpay.service.ThirdPayService; +import com.chaozhanggui.system.cashierservice.util.*; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; @@ -27,16 +38,14 @@ import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; import java.io.IOException; import java.math.BigDecimal; -import java.util.Date; -import java.util.LinkedHashMap; -import java.util.Map; +import java.time.LocalDateTime; +import java.util.*; @Service @Slf4j public class PayService { - @Autowired TbOrderInfoMapper tbOrderInfoMapper; @@ -52,6 +61,15 @@ public class PayService { @Autowired TbOrderDetailMapper tbOrderDetailMapper; + @Autowired + private TbMerchantAccountMapper merchantAccountMapper; + + @Autowired + private GroupOrderCouponService groupOrderCouponService; + + + @Autowired + TbShopPayTypeMapper tbShopPayTypeMapper; @Value("${ysk.url}") @@ -60,12 +78,13 @@ public class PayService { @Value("${ysk.callBackurl}") private String callBackurl; + @Value("${ysk.callBackGroupurl}") + private String callBackGroupurl; + @Value("${ysk.callBackIn}") private String callBackIn; - - @Autowired private TbCashierCartMapper tbCashierCartMapper; @@ -89,21 +108,73 @@ public class PayService { @Autowired TbShopUserFlowMapper tbShopUserFlowMapper; + @Value("${thirdPay.payType}") + private String thirdPayType; + + + @Value("${thirdPay.url}") + private String thirdUrl; + + + + @Value("${thirdPay.callInBack}") + private String callInBack; + + @Value("${thirdPay.callFSTBack}") + private String callFSTBack; + + @Autowired + ThirdPayService thirdPayService; + + @Autowired + TbUserInfoMapper tbUserInfoMapper; + + + + @Resource + private TbGroupOrderInfoMapper tbGroupOrderInfoMapper; + @Autowired + private TbProductMapper tbProductMapper; + @Resource + private GroupOrderCouponService orderCouponService; + + @Autowired + TbActivateMapper tbActivateMapper; @Transactional(rollbackFor = Exception.class) public Result payOrder(String openId,String orderId,String ip) throws Exception { + + if(ObjectUtil.isEmpty(openId)||Objects.isNull(openId)){ + return Result.fail("付款用户[userId]参数不能为空"); + } + TbOrderInfo orderInfo= tbOrderInfoMapper.selectByPrimaryKey(Integer.valueOf(orderId)); if(!"unpaid".equals(orderInfo.getStatus())&&!"paying".equals(orderInfo.getStatus())){ return Result.fail("订单状态异常,不允许支付"); } + if (System.currentTimeMillis() - orderInfo.getCreatedAt() > 60 * 15 * 1000) { + return Result.fail("订单十五分钟内有效,当前已超时,请重新下单。"); + } if(ObjectUtil.isNull(orderInfo.getMerchantId())||ObjectUtil.isEmpty(orderInfo.getMerchantId())){ return Result.fail("没有对应的商户"); } + List cashierCarts= tbCashierCartMapper.selectByOrderId(orderId,null); + if(ObjectUtil.isEmpty(cashierCarts)||ObjectUtil.isNull(cashierCarts)){ + return Result.fail("购物车信息不存在"); + } + + StringBuffer body=new StringBuffer(); + for (TbCashierCart cashierCart : cashierCarts) { + body.append(cashierCart.getName()); + } + + + TbMerchantThirdApply thirdApply= tbMerchantThirdApplyMapper.selectByPrimaryKey(Integer.valueOf(orderInfo.getMerchantId())); if(ObjectUtil.isEmpty(thirdApply)||ObjectUtil.isNull(thirdApply)){ @@ -131,57 +202,412 @@ public class PayService { tbOrderPaymentMapper.updateByPrimaryKey(payment); } - PayReq req=new PayReq(); + if("ysk".equals(thirdPayType)){ + PayReq req=new PayReq(); - req.setAppId(thirdApply.getAppId()); - req.setTimestamp(System.currentTimeMillis()); - req.setIp(ip); - req.setMercOrderNo(orderInfo.getOrderNo()); - req.setNotifyUrl(callBackurl); - req.setPayAmt(payment.getAmount().setScale(2,BigDecimal.ROUND_DOWN).toPlainString()); - req.setPayType("03"); - req.setPayWay("WXZF"); - req.setSubject("扫码点餐"); - req.setUserId(openId); + req.setAppId(thirdApply.getAppId()); + req.setTimestamp(System.currentTimeMillis()); + req.setIp(ip); + req.setMercOrderNo(orderInfo.getOrderNo()); + req.setNotifyUrl(callBackurl); + req.setPayAmt(payment.getAmount().setScale(2,BigDecimal.ROUND_DOWN).toPlainString()); + req.setPayType("03"); + req.setPayWay("WXZF"); + req.setSubject("扫码点餐"); + req.setUserId(openId); - Map map= BeanUtil.transBeanMap(req); - req.setSign(MD5Util.encrypt(map,thirdApply.getAppToken(),true)); + Map map= BeanUtil.transBeanMap(req); + req.setSign(MD5Util.encrypt(map,thirdApply.getAppToken(),true)); - ResponseEntity response= restTemplate.postForEntity(url.concat("trans/pay"),req,String.class); - if(response.getStatusCodeValue()==200&&ObjectUtil.isNotEmpty(response.getBody())){ - JSONObject object=JSONObject.parseObject(response.getBody()); - if(object.get("code").equals("0")){ - payment.setTradeNumber(object.getJSONObject("data").get("orderNumber").toString()); - payment.setUpdatedAt(System.currentTimeMillis()); - tbOrderPaymentMapper.updateByPrimaryKeySelective(payment); - orderInfo.setStatus("paying"); - orderInfo.setPayOrderNo(payment.getTradeNumber()); + ResponseEntity response= restTemplate.postForEntity(url.concat("trans/pay"),req,String.class); + if(response.getStatusCodeValue()==200&&ObjectUtil.isNotEmpty(response.getBody())){ + JSONObject object=JSONObject.parseObject(response.getBody()); + if(object.get("code").equals("0")){ + payment.setTradeNumber(object.getJSONObject("data").get("orderNumber").toString()); + payment.setUpdatedAt(System.currentTimeMillis()); + tbOrderPaymentMapper.updateByPrimaryKeySelective(payment); + orderInfo.setStatus("paying"); + orderInfo.setPayOrderNo(payment.getTradeNumber()); - tbOrderInfoMapper.updateByPrimaryKey(orderInfo); - String key= RedisCst.TABLE_CART.concat(orderInfo.getTableId()).concat("-").concat(orderInfo.getShopId()); - //清除缓存购物车数据 - redisUtil.deleteByKey(key); - JSONObject jsonObject1 = new JSONObject(); - jsonObject1.put("status", "success"); - jsonObject1.put("msg", "成功"); - jsonObject1.put("type", ""); - jsonObject1.put("data", new JSONArray()); - jsonObject1.put("amount", 0); - AppWebSocketServer.AppSendInfo(jsonObject1,key, false); - tbCashierCartMapper.updateStatusByOrderId(orderId.toString(),"final"); - return Result.success(CodeEnum.SUCCESS,object.getJSONObject("data")); + tbOrderInfoMapper.updateByPrimaryKey(orderInfo); + String key= RedisCst.TABLE_CART.concat(orderInfo.getTableId()).concat("-").concat(orderInfo.getShopId()); + //清除缓存购物车数据 + redisUtil.deleteByKey(key); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("status", "success"); + jsonObject1.put("msg", "成功"); + jsonObject1.put("type", ""); + jsonObject1.put("data", new JSONArray()); + jsonObject1.put("amount", 0); +// AppWebSocketServer.AppSendInfo(jsonObject1,key, "",false); + tbCashierCartMapper.updateStatusByOrderId(orderId.toString(),"final"); + return Result.success(CodeEnum.SUCCESS,object.getJSONObject("data")); + }else { + return Result.fail(object.getString("msg")); + } + } + }else { + String reqbody=""; + + if(body.length()>15){ + reqbody=body.substring(0,6).concat("....").concat(body.substring(body.length()-6,body.length())).toString(); }else { - return Result.fail(object.getString("msg")); + reqbody=body.toString(); + } + + PublicResp publicResp= thirdPayService.scanpay(thirdUrl,thirdApply.getAppId(),reqbody,reqbody,payment.getAmount().setScale(2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100)).longValue(),"WECHAT",thirdApply.getSmallAppid(),openId,ip,DateUtils.getsdfTimesSS(),thirdApply.getStoreId(),callFSTBack,null,thirdApply.getAppToken()); + if(ObjectUtil.isNotNull(publicResp)&&ObjectUtil.isNotEmpty(publicResp)){ + if("000000".equals(publicResp.getCode())){ + WxScanPayResp wxScanPayResp= publicResp.getObjData(); + if("TRADE_AWAIT".equals(wxScanPayResp.getState())){ + payment.setTradeNumber(wxScanPayResp.getPayOrderId()); + payment.setUpdatedAt(System.currentTimeMillis()); + tbOrderPaymentMapper.updateByPrimaryKeySelective(payment); + orderInfo.setStatus("paying"); + orderInfo.setPayOrderNo(payment.getTradeNumber()); + + + tbOrderInfoMapper.updateByPrimaryKey(orderInfo); + String key= RedisCst.TABLE_CART.concat(orderInfo.getTableId()).concat("-").concat(orderInfo.getShopId()); + //清除缓存购物车数据 + redisUtil.deleteByKey(key); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("status", "success"); + jsonObject1.put("msg", "成功"); + jsonObject1.put("type", ""); + jsonObject1.put("data", new JSONArray()); + jsonObject1.put("amount", 0); + +// AppWebSocketServer.AppSendInfo(jsonObject1,key, "",false); + tbCashierCartMapper.updateStatusByOrderId(orderId.toString(),"final"); + ObjectMapper mapper = new ObjectMapper(); + return Result.success(CodeEnum.SUCCESS,mapper.readTree(wxScanPayResp.getPayInfo())); + }else{ + return Result.fail(publicResp.getMsg()); + } + } } } + + return Result.fail("失败"); } + + + + + + @Transactional(rollbackFor = Exception.class) + public Result accountPay(String orderId, String memberId, String token,String pwd) { + if (ObjectUtil.isEmpty(orderId) || ObjectUtil.isEmpty(memberId)) { + return Result.fail("参数错误"); + } + + TbOrderInfo orderInfo = tbOrderInfoMapper.selectByPrimaryKey(Integer.valueOf(orderId)); + if (ObjectUtil.isEmpty(orderInfo)) { + return Result.fail("订单信息不存在"); + } + if (System.currentTimeMillis() - orderInfo.getCreatedAt() > 60 * 15 * 1000) { + return Result.fail("订单十五分钟内有效,当前已超时,请重新下单。"); + } + + + TbUserInfo userInfo= tbUserInfoMapper.selectByPrimaryKey(Integer.valueOf(orderInfo.getUserId())); + if(ObjectUtil.isEmpty(userInfo)){ + return Result.fail("未获取到用户信息"); + } + + if(StringUtils.isBlank(userInfo.getPwd())){ +// return Result.fail("支付密码未设置"); + return Result.success(CodeEnum.SUCCESS,"3"); + } + if(!userInfo.getPwd().equals(MD5Utils.md5(pwd))){ + return Result.fail("支付密码错误"); + } + + + if (!"unpaid".equals(orderInfo.getStatus()) && !"paying".equals(orderInfo.getStatus()) ) { + return Result.fail("订单状态异常"); + } + + + int count = tbShopPayTypeMapper.countSelectByShopIdAndPayType(orderInfo.getShopId(), "deposit"); + if (count < 1) { + return Result.fail("店铺未开通此支付方式"); + } + + + TbShopUser user = tbShopUserMapper.selectByPrimaryKey(memberId); + if (ObjectUtil.isEmpty(user) || user.getIsVip()==null || !"1".equals(user.getIsVip().toString())) { +// return Result.failCode("会员卡余额不足","1"); + return Result.success(CodeEnum.SUCCESS,"4"); + } + + if (N.gt(orderInfo.getOrderAmount(), user.getAmount())) { +// return Result.failCode("会员卡余额不足","2"); + return Result.success(CodeEnum.SUCCESS,"2"); + } + + user.setAmount(user.getAmount().subtract(orderInfo.getOrderAmount())); + user.setConsumeAmount(user.getConsumeAmount().add(orderInfo.getPayAmount())); + user.setConsumeNumber(user.getConsumeNumber() + 1); + user.setUpdatedAt(System.currentTimeMillis()); + tbShopUserMapper.updateByPrimaryKeySelective(user); + + + TbShopUserFlow flow = new TbShopUserFlow(); + flow.setShopUserId(Integer.valueOf(user.getId())); + flow.setBizCode("accountPay"); + flow.setBizName("会员储值卡支付"); + flow.setType("-"); + flow.setAmount(orderInfo.getOrderAmount()); + flow.setBalance(user.getAmount()); + flow.setCreateTime(new Date()); + tbShopUserFlowMapper.insert(flow); + + + orderInfo.setPayAmount(orderInfo.getOrderAmount()); + orderInfo.setMemberId(memberId); + orderInfo.setPayType("deposit"); + orderInfo.setStatus("closed"); + orderInfo.setPayOrderNo("deposit".concat(SnowFlakeUtil.generateOrderNo())); + tbOrderInfoMapper.updateByPrimaryKeySelective(orderInfo); + //更新购物车状态 + int cartCount = tbCashierCartMapper.updateStatusByOrderId(orderId, "final"); + + + tbOrderDetailMapper.updateStatusByOrderId(Integer.valueOf(orderId), "closed"); + + tbOrderDetailMapper.updateStatusByOrderIdAndStatus(Integer.valueOf(orderId), "closed"); + + log.info("更新购物车:{}", cartCount); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("token", token); + jsonObject.put("type", "wxcreate"); + jsonObject.put("orderId", orderId); + + producer.putOrderCollect(jsonObject.toJSONString()); + + producer.printMechine(orderId); + sendOrderToClient(orderInfo); + return Result.success(CodeEnum.SUCCESS,"1"); + } + + + @Transactional(rollbackFor = Exception.class) + public Result groupOrderPay(String orderId, String payType, String userId, String ip,String pwd) throws JsonProcessingException { + TbGroupOrderInfo orderInfo = tbGroupOrderInfoMapper.queryById(Integer.valueOf(orderId)); + if (!"unpaid".equals(orderInfo.getStatus())) { + return Result.fail("订单状态异常,不允许支付"); + } + if(payType.equals("deposit")){ + int count = tbShopPayTypeMapper.countSelectByShopIdAndPayType(orderInfo.getShopId().toString(), "deposit"); + if (count < 1) { + return Result.fail("店铺未开通此支付方式"); + } + + TbUserInfo userInfo= tbUserInfoMapper.selectByPrimaryKey(Integer.valueOf(orderInfo.getUserId())); + if(ObjectUtil.isEmpty(userInfo)){ + return Result.fail("未获取到用户信息"); + } + if(!userInfo.getPwd().equals(MD5Utils.md5(pwd))){ + return Result.fail("支付密码错误"); + } + + TbShopUser user = tbShopUserMapper.selectByUserIdAndShopId(userId,orderInfo.getShopId().toString()); + if (ObjectUtil.isEmpty(user) || !"1".equals(user.getIsVip().toString())) { + return Result.failCode("会员卡余额不足","1"); + } + + if (N.gt(orderInfo.getPayAmount(), user.getAmount())) { + return Result.failCode("会员卡余额不足","2"); + } + + user.setAmount(user.getAmount().subtract(orderInfo.getOrderAmount())); + user.setConsumeAmount(user.getConsumeAmount().add(orderInfo.getPayAmount())); + user.setConsumeNumber(user.getConsumeNumber() + 1); + user.setUpdatedAt(System.currentTimeMillis()); + tbShopUserMapper.updateByPrimaryKeySelective(user); + TbShopUserFlow flow = new TbShopUserFlow(); + flow.setShopUserId(Integer.valueOf(user.getId())); + flow.setBizCode("accountGroupPay"); + flow.setType("-"); + flow.setBizName("会员储值卡支付团购卷"); + flow.setAmount(orderInfo.getOrderAmount()); + flow.setBalance(user.getAmount()); + flow.setCreateTime(new Date()); + tbShopUserFlowMapper.insert(flow); + + for (int i = 0; i < orderInfo.getNumber(); i++) { + TbGroupOrderCoupon groupOrderCoupon = new TbGroupOrderCoupon(); + groupOrderCoupon.setOrderId(orderInfo.getId()); + groupOrderCoupon.setCouponNo(genCouponNumber()); + groupOrderCoupon.setIsRefund(0); + groupOrderCouponService.insert(groupOrderCoupon); + } + orderInfo.setExpDate(getNextMonDate()); + //修改主单状态 + orderInfo.setStatus("unused"); + orderInfo.setPayAmount(orderInfo.getOrderAmount()); + orderInfo.setPayTime(new Date()); + orderInfo.setPayType("deposit"); + tbGroupOrderInfoMapper.update(orderInfo); + orderInfo.setPayOrderNo("deposit".concat(SnowFlakeUtil.generateOrderNo())); + tbGroupOrderInfoMapper.update(orderInfo); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("type", "groupCreate"); + jsonObject.put("orderId", orderId); + producer.putOrderCollect(jsonObject.toJSONString()); + return Result.success(CodeEnum.SUCCESS); + } + else { + TbMerchantAccount tbMerchantAccount = merchantAccountMapper.selectByShopId(orderInfo.getShopId().toString()); + if (tbMerchantAccount == null) { + throw new MsgException("生成订单错误"); + } + + if (ObjectUtil.isNull(tbMerchantAccount)) { + return Result.fail("没有对应的商户"); + } + + TbMerchantThirdApply thirdApply = tbMerchantThirdApplyMapper.selectByPrimaryKey(Integer.valueOf(tbMerchantAccount.getId())); + + if (ObjectUtil.isEmpty(thirdApply) || ObjectUtil.isNull(thirdApply)) { + return Result.fail("支付通道不存在"); + } + StringBuffer body=new StringBuffer(); + body.append(orderInfo.getProName()); + TbOrderPayment payment = tbOrderPaymentMapper.selectByOrderId(orderInfo.getOrderNo()); + if (ObjectUtil.isEmpty(payment) || payment == null) { + payment = new TbOrderPayment(); + payment.setPayTypeId("ysk"); + payment.setAmount(orderInfo.getOrderAmount()); + payment.setPaidAmount(orderInfo.getPayAmount()); + payment.setHasRefundAmount(BigDecimal.ZERO); + if (payType.equals("wechatPay")) { + payment.setPayName("微信支付"); + payment.setPayType("wechatPay"); + } else if (payType.equals("aliPay")) { + payment.setPayName("支付宝支付"); + payment.setPayType("aliPay"); + } + payment.setReceived(payment.getAmount()); + payment.setChangeFee(BigDecimal.ZERO); +// payment.setMemberId(orderInfo.getMemberId()); + payment.setShopId(orderInfo.getShopId().toString()); + payment.setOrderId(orderInfo.getOrderNo()); + payment.setCreatedAt(System.currentTimeMillis()); + tbOrderPaymentMapper.insert(payment); + } + else { + if (payType.equals("wechatPay")) { + payment.setPayName("微信支付"); + payment.setPayType("wechatPay"); + } else if (payType.equals("aliPay")) { + payment.setPayName("支付宝支付"); + payment.setPayType("aliPay"); + } + payment.setUpdatedAt(System.currentTimeMillis()); + tbOrderPaymentMapper.updateByPrimaryKey(payment); + } + if("ysk".equals(thirdPayType)){ + PayReq req = new PayReq(); + req.setAppId(thirdApply.getAppId()); + req.setTimestamp(System.currentTimeMillis()); + req.setIp(ip); + req.setMercOrderNo(orderInfo.getOrderNo()); + req.setNotifyUrl(callBackGroupurl+"Ysk"); + req.setPayAmt(payment.getAmount().setScale(2, BigDecimal.ROUND_DOWN).toPlainString()); + if (payType.equals("wechatPay")) { + req.setPayType("03"); + req.setPayWay("WXZF");//WXZF ZFBZF UNIONPAY + } else if (payType.equals("aliPay")) { + req.setPayWay("ZFBZF"); + } + req.setSubject("零点八零:团购卷"); + req.setUserId(userId); + Map map = BeanUtil.transBeanMap(req); + req.setSign(MD5Util.encrypt(map, thirdApply.getAppToken(), true)); + ResponseEntity response = restTemplate.postForEntity(url.concat("trans/pay"), req, String.class); + if (response.getStatusCodeValue() == 200 && ObjectUtil.isNotEmpty(response.getBody())) { + JSONObject object = JSONObject.parseObject(response.getBody()); + log.info("团购卷支付响应:{}",object); + if (object.get("code").equals("0")) { + payment.setTradeNumber(object.getJSONObject("data").get("orderNumber").toString()); + payment.setUpdatedAt(System.currentTimeMillis()); + tbOrderPaymentMapper.updateByPrimaryKeySelective(payment); + orderInfo.setPayType(payType); + orderInfo.setPayOrderNo(payment.getTradeNumber()); + tbGroupOrderInfoMapper.update(orderInfo); + tbProductMapper.upGroupRealSalesNumber(orderInfo.getProId().toString(), orderInfo.getNumber()); + return Result.success(CodeEnum.SUCCESS, object.getJSONObject("data")); + } else { + return Result.fail("支付失败"); + } + } + } + else { + String reqbody=""; + + if(body.length()>15){ + reqbody=body.substring(0,6).concat("....").concat(body.substring(body.length()-6,body.length())).toString(); + }else { + reqbody=body.toString(); + } + PublicResp publicResp= thirdPayService.scanpay( + thirdUrl, + thirdApply.getAppId(), + reqbody, + reqbody, + payment.getAmount().setScale(2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100)).longValue(), + "WECHAT", + thirdApply.getSmallAppid(), + userId, + ip, +// orderInfo.getOrderNo(), + DateUtils.getsdfTimesSS(), + thirdApply.getStoreId(), + callBackGroupurl, + null, + thirdApply.getAppToken()); + if(ObjectUtil.isNotNull(publicResp)&&ObjectUtil.isNotEmpty(publicResp)){ + if("000000".equals(publicResp.getCode())){ + WxScanPayResp wxScanPayResp= publicResp.getObjData(); + log.info("团购订单下单结果2:{}",wxScanPayResp); + if("TRADE_AWAIT".equals(wxScanPayResp.getState())){ + payment.setTradeNumber(wxScanPayResp.getPayOrderId()); + payment.setUpdatedAt(System.currentTimeMillis()); + tbOrderPaymentMapper.updateByPrimaryKeySelective(payment); + orderInfo.setPayType(payType); + orderInfo.setPayOrderNo(payment.getTradeNumber()); + tbGroupOrderInfoMapper.update(orderInfo); + tbProductMapper.upGroupRealSalesNumber(orderInfo.getProId().toString(), orderInfo.getNumber()); + ObjectMapper mapper = new ObjectMapper(); + return Result.success(CodeEnum.SUCCESS,mapper.readTree(wxScanPayResp.getPayInfo())); + } else{ + return Result.fail(wxScanPayResp.getNote()); + } + }else { + return Result.fail(publicResp.getMsg()); + } + } + } + return Result.fail("失败"); + } + } + + @Transactional(rollbackFor = Exception.class) + public Result returngroupOrder(ReturnGroupOrderDto param) { + return Result.success(CodeEnum.SUCCESS); + } + @Transactional(rollbackFor = Exception.class) public Result modifyOrderStatus(Integer orderId) throws IOException { TbOrderInfo orderInfo= tbOrderInfoMapper.selectByPrimaryKey(Integer.valueOf(orderId)); @@ -198,97 +624,145 @@ public class PayService { if(ObjectUtil.isEmpty(thirdApply)||ObjectUtil.isNull(thirdApply)){ return Result.fail("支付通道不存在"); } - TradeQueryReq req=new TradeQueryReq(); - req.setAppId(thirdApply.getAppId()); - req.setTimestamp(System.currentTimeMillis()); - req.setOrderNumber(payment.getTradeNumber()); - Map map= BeanUtil.transBeanMap(req); - - req.setSign(MD5Util.encrypt(map,thirdApply.getAppToken(),true)); - - ResponseEntity response= restTemplate.postForEntity(url.concat("merchantOrder/tradeQuery"),req,String.class); - if(response.getStatusCodeValue()==200&&ObjectUtil.isNotEmpty(response.getBody())){ - JSONObject object=JSONObject.parseObject(response.getBody()); - - if(object.get("code").equals("0")){ - JSONObject data=object.getJSONObject("data"); - String status=data.getString("status"); - String cartStatus=""; - switch (status){ - case "0": //交易失败 - break; - case "1": //交易成功 - - //修改数据库中购物车数据 - int cartCount= tbCashierCartMapper.updateStatusByOrderId(orderId.toString(),"final"); - - log.info("更新购物车:{}",cartCount); - - //更新子单状态 - tbOrderDetailMapper.updateStatusByOrderIdAndStatus(Integer.valueOf(orderId),"closed"); - - //修改主单状态 - orderInfo.setStatus("closed"); - orderInfo.setPayType("wx_lite"); - orderInfo.setPayOrderNo(payment.getTradeNumber()); - orderInfo.setPayAmount(orderInfo.getOrderAmount()); - tbOrderInfoMapper.updateByPrimaryKeySelective(orderInfo); - - - JSONObject jsonObject=new JSONObject(); - jsonObject.put("token",0); - jsonObject.put("type","wxcreate"); - jsonObject.put("orderId",orderInfo.getId().toString()); - - producer.putOrderCollect(jsonObject.toJSONString()); - log.info("发送打印数据"); - producer.printMechine(orderInfo.getId() + ""); + if("ysk".equals(thirdPayType)){ + TradeQueryReq req=new TradeQueryReq(); + req.setAppId(thirdApply.getAppId()); + req.setTimestamp(System.currentTimeMillis()); + req.setOrderNumber(payment.getTradeNumber()); + Map map= BeanUtil.transBeanMap(req); - return Result.success(CodeEnum.SUCCESS,orderId); - case "2": //退款成功 - cartStatus="refund"; - orderInfo.setStatus("refund"); - break; - case "3": //退款失败 - break; - case "4": //退款中 - cartStatus="refunding"; - orderInfo.setStatus("refunding"); - break; + req.setSign(MD5Util.encrypt(map,thirdApply.getAppToken(),true)); + + ResponseEntity response= restTemplate.postForEntity(url.concat("merchantOrder/tradeQuery"),req,String.class); + if(response.getStatusCodeValue()==200&&ObjectUtil.isNotEmpty(response.getBody())){ + JSONObject object=JSONObject.parseObject(response.getBody()); + + if(object.get("code").equals("0")){ + JSONObject data=object.getJSONObject("data"); + String status=data.getString("status"); + String cartStatus=""; + switch (status){ + case "0": //交易失败 + break; + case "1": //交易成功 + + //修改数据库中购物车数据 + int cartCount= tbCashierCartMapper.updateStatusByOrderId(orderId.toString(),"final"); + + log.info("更新购物车:{}",cartCount); + + //更新子单状态 + tbOrderDetailMapper.updateStatusByOrderIdAndStatus(Integer.valueOf(orderId),"closed"); + + //修改主单状态 + orderInfo.setStatus("closed"); + orderInfo.setPayType("wx_lite"); + orderInfo.setPayOrderNo(payment.getTradeNumber()); + orderInfo.setPayAmount(orderInfo.getOrderAmount()); + tbOrderInfoMapper.updateByPrimaryKeySelective(orderInfo); + + + JSONObject jsonObject=new JSONObject(); + jsonObject.put("token",0); + jsonObject.put("type","wxcreate"); + jsonObject.put("orderId",orderInfo.getId().toString()); + + producer.putOrderCollect(jsonObject.toJSONString()); + + + + log.info("发送打印数据"); + producer.printMechine(orderInfo.getId() + ""); + + return Result.success(CodeEnum.SUCCESS,orderId); + case "2": //退款成功 + cartStatus="refund"; + orderInfo.setStatus("refund"); + break; + case "3": //退款失败 + break; + case "4": //退款中 + cartStatus="refunding"; + orderInfo.setStatus("refunding"); + break; + } + + tbCashierCartMapper.updateStatusByOrderId(orderId.toString(),cartStatus); + orderInfo.setUpdatedAt(System.currentTimeMillis()); + tbOrderInfoMapper.updateByPrimaryKeySelective(orderInfo); } + } + }else { + PublicResp publicResp=thirdPayService.queryOrder(thirdUrl,thirdApply.getAppId(),payment.getTradeNumber(),null,thirdApply.getAppToken()); + if(ObjectUtil.isNotNull(publicResp)&&ObjectUtil.isNotEmpty(publicResp)){ + if("000000".equals(publicResp.getCode())){ + String cartStatus=""; + switch (publicResp.getObjData().getState()){ + case "TRADE_SUCCESS": + //修改数据库中购物车数据 + int cartCount= tbCashierCartMapper.updateStatusByOrderId(orderId.toString(),"final"); - tbCashierCartMapper.updateStatusByOrderId(orderId.toString(),cartStatus); - orderInfo.setUpdatedAt(System.currentTimeMillis()); - tbOrderInfoMapper.updateByPrimaryKeySelective(orderInfo); + log.info("更新购物车:{}",cartCount); + + //更新子单状态 + tbOrderDetailMapper.updateStatusByOrderIdAndStatus(Integer.valueOf(orderId),"closed"); + + //修改主单状态 + orderInfo.setStatus("closed"); + orderInfo.setPayType("wx_lite"); + orderInfo.setPayOrderNo(payment.getTradeNumber()); + orderInfo.setPayAmount(orderInfo.getOrderAmount()); + tbOrderInfoMapper.updateByPrimaryKeySelective(orderInfo); + + + JSONObject jsonObject=new JSONObject(); + jsonObject.put("token",0); + jsonObject.put("type","wxcreate"); + jsonObject.put("orderId",orderInfo.getId().toString()); + + producer.putOrderCollect(jsonObject.toJSONString()); + + + + log.info("发送打印数据"); + producer.printMechine(orderInfo.getId() + ""); + sendOrderToClient(orderInfo); + redisUtil.deleteByKey(RedisCst.ORDER_EXPIRED.concat(orderInfo.getId().toString())); + return Result.success(CodeEnum.SUCCESS,orderId); + case "REFUND_ING": + cartStatus="refunding"; + orderInfo.setStatus("refunding"); + break; + } + } } } + } } return Result.success(CodeEnum.SUCCESS,orderId); } - - @Transactional(rollbackFor = Exception.class) - public Result memberIn(String openId,String userId,String amount,String shopId,String ip){ + public Result memberIn(String openId,String userId,String amount,String shopId,String ip) throws JsonProcessingException { if(ObjectUtil.isEmpty(openId)||ObjectUtil.isEmpty(userId)){ return Result.fail("用户信息允许为空"); } + TbUserInfo userInfo= tbUserInfoMapper.selectByPrimaryKey(Integer.valueOf(userId)); + if(ObjectUtil.isEmpty(userInfo)){ + return Result.fail("用户基本信息不存在"); + } TbShopUser tbShopUser= tbShopUserMapper.selectByUserIdAndShopId(userId,shopId); if(ObjectUtil.isEmpty(tbShopUser)){ return Result.fail("对应的用户信息不存在"); } - if(ObjectUtil.isEmpty(tbShopUser.getIsVip())||!"1".equals(tbShopUser.getIsVip().toString())){ - return Result.fail("非会员用户不允许充值"); - } - TbShopInfo shopInfo= tbShopInfoMapper.selectByPrimaryKey(Integer.valueOf(shopId)); if(ObjectUtil.isEmpty(shopInfo)){ @@ -315,35 +789,56 @@ public class PayService { tbMemberInMapper.insert(memberIn); + if("ysk".equals(thirdPayType)){ + PayReq req=new PayReq(); - PayReq req=new PayReq(); - - req.setAppId(thirdApply.getAppId()); - req.setTimestamp(System.currentTimeMillis()); - req.setIp(ip); - req.setMercOrderNo(SnowFlakeUtil.generateOrderNo()); - req.setNotifyUrl(callBackIn); - req.setPayAmt(amount); - req.setPayType("03"); - req.setPayWay("WXZF"); - req.setSubject("充值"); - req.setUserId(openId); + req.setAppId(thirdApply.getAppId()); + req.setTimestamp(System.currentTimeMillis()); + req.setIp(ip); + req.setMercOrderNo(SnowFlakeUtil.generateOrderNo()); + req.setNotifyUrl(callBackIn); + req.setPayAmt(amount); + req.setPayType("03"); + req.setPayWay("WXZF"); + req.setSubject("充值"); + req.setUserId(openId); - Map map= BeanUtil.transBeanMap(req); - req.setSign(MD5Util.encrypt(map,thirdApply.getAppToken(),true)); + Map map= BeanUtil.transBeanMap(req); + req.setSign(MD5Util.encrypt(map,thirdApply.getAppToken(),true)); - ResponseEntity response= restTemplate.postForEntity(url.concat("trans/pay"),req,String.class); - if(response.getStatusCodeValue()==200&&ObjectUtil.isNotEmpty(response.getBody())){ - JSONObject object=JSONObject.parseObject(response.getBody()); - if(object.get("code").equals("0")){ - memberIn.setOrderNo(object.getJSONObject("data").get("orderNumber").toString()); - memberIn.setUpdateTime(new Date()); - tbMemberInMapper.updateByPrimaryKeySelective(memberIn); + ResponseEntity response= restTemplate.postForEntity(url.concat("trans/pay"),req,String.class); + if(response.getStatusCodeValue()==200&&ObjectUtil.isNotEmpty(response.getBody())){ + JSONObject object=JSONObject.parseObject(response.getBody()); + if(object.get("code").equals("0")){ + memberIn.setOrderNo(object.getJSONObject("data").get("orderNumber").toString()); + memberIn.setUpdateTime(new Date()); + tbMemberInMapper.updateByPrimaryKeySelective(memberIn); - return Result.success(CodeEnum.SUCCESS,object.getJSONObject("data")); - }else { - return Result.fail(object.getString("msg")); + return Result.success(CodeEnum.SUCCESS,object.getJSONObject("data")); + }else { + return Result.fail(object.getString("msg")); + } + } + }else { + String orderNo=DateUtils.getsdfTimesSS(); + PublicResp publicResp= thirdPayService.scanpay(thirdUrl,thirdApply.getAppId(),"会员充值","会员充值",new BigDecimal(amount).setScale(2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100)).longValue(),"WECHAT",thirdApply.getSmallAppid(),openId,ip, orderNo,thirdApply.getStoreId(),callInBack,null,thirdApply.getAppToken()); + if(ObjectUtil.isNotNull(publicResp)&&ObjectUtil.isNotEmpty(publicResp)){ + if("000000".equals(publicResp.getCode())){ + WxScanPayResp wxScanPayResp= publicResp.getObjData(); + if("TRADE_AWAIT".equals(wxScanPayResp.getState())){ + + memberIn.setOrderNo(orderNo); + memberIn.setTradeNo(wxScanPayResp.getPayOrderId()); + memberIn.setUpdateTime(new Date()); + tbMemberInMapper.updateByPrimaryKeySelective(memberIn); + ObjectMapper mapper = new ObjectMapper(); + return Result.success(CodeEnum.SUCCESS,mapper.readTree(wxScanPayResp.getPayInfo())); + + }else{ + return Result.fail(publicResp.getMsg()); + } + } } } return Result.fail("失败"); @@ -383,7 +878,8 @@ public class PayService { log.info("发送打印数据"); producer.printMechine(orderInfo.getId() + ""); - + sendOrderToClient(orderInfo); + redisUtil.deleteByKey(RedisCst.ORDER_EXPIRED.concat(orderInfo.getId().toString())); return "SUCCESS"; } @@ -391,6 +887,144 @@ public class PayService { } + + @Transactional(rollbackFor = Exception.class) + public String callBackPayFST(String payOrderNO) { + TbOrderInfo orderInfo = tbOrderInfoMapper.selectByPayOrderNo(payOrderNO); + if (ObjectUtil.isEmpty(orderInfo)) { + return "订单信息不存在"; + } + + if ("paying".equals(orderInfo.getStatus())) { + int cartCount = tbCashierCartMapper.updateStatusByOrderId(orderInfo.getId().toString(), "final"); + + log.info("更新购物车:{}", cartCount); + + //更新子单状态 + tbOrderDetailMapper.updateStatusByOrderIdAndStatus(orderInfo.getId(), "closed"); + + //修改主单状态 + orderInfo.setStatus("closed"); + orderInfo.setPayType("wx_lite"); + orderInfo.setPayOrderNo(payOrderNO); + orderInfo.setPayAmount(orderInfo.getOrderAmount()); + tbOrderInfoMapper.updateByPrimaryKeySelective(orderInfo); + + + JSONObject jsonObject=new JSONObject(); + jsonObject.put("token",0); + jsonObject.put("type","wxcreate"); + jsonObject.put("orderId",orderInfo.getId().toString()); + + producer.putOrderCollect(jsonObject.toJSONString()); + + log.info("发送打印数据"); + producer.printMechine(orderInfo.getId() + ""); + JSONObject coupons = new JSONObject(); + coupons.put("type","buy"); + coupons.put("orderId",orderInfo.getId().toString()); + producer.printCoupons(coupons.toJSONString()); + sendOrderToClient(orderInfo); + redisUtil.deleteByKey(RedisCst.ORDER_EXPIRED.concat(orderInfo.getId().toString())); + return "SUCCESS"; + + } + return null; + } + + @Transactional(rollbackFor = Exception.class) + public String callBackGroupPay(String payOrderNO,String payTime) { + TbGroupOrderInfo orderInfo = tbGroupOrderInfoMapper.selectByPayOrderNo(payOrderNO); + if (ObjectUtil.isEmpty(orderInfo)) { + return "订单信息不存在"; + } + + if ("unpaid".equals(orderInfo.getStatus())) { + for (int i = 0; i < orderInfo.getNumber(); i++) { + TbGroupOrderCoupon groupOrderCoupon = new TbGroupOrderCoupon(); + groupOrderCoupon.setOrderId(orderInfo.getId()); + groupOrderCoupon.setCouponNo(genCouponNumber()); + groupOrderCoupon.setIsRefund(0); + groupOrderCouponService.insert(groupOrderCoupon); + } + orderInfo.setExpDate(getNextMonDate()); + //修改主单状态 + orderInfo.setStatus("unused"); + orderInfo.setPayAmount(orderInfo.getOrderAmount()); + orderInfo.setPayTime(DateUtils.fomatDateTime(payTime)); + tbGroupOrderInfoMapper.update(orderInfo); + return "SUCCESS"; + }else { + log.error("支付回调异常,订单状态为{}",orderInfo); + } + return null; + } + + + public Result getActivate(String shopId,int page ,int pageSize){ + PageHelper.startPage(page, pageSize); + List list=tbActivateMapper.selectByShpopId(shopId); + PageInfo pageInfo=new PageInfo(list); + return Result.success(CodeEnum.SUCCESS,pageInfo); + } + + + + public Result getShopByMember(String userId,String shopId,int page,int pageSize){ + PageHelper.startPage(page, pageSize); + List list= tbShopUserMapper.selectByUserId(userId,shopId); + PageInfo pageInfo=new PageInfo(list); + return Result.success(CodeEnum.SUCCESS,pageInfo); + } + + public Result queryMemberAccount(String memberId,int page, int pageSize){ + if(StringUtils.isBlank(memberId)){ + return Result.fail("会员编号不许为空"); + } + PageHelper.startPage(page,pageSize); + List> list=tbShopUserFlowMapper.selectByMemberAccountFlow(memberId); + PageInfo pageInfo=new PageInfo(list); + return Result.success(CodeEnum.SUCCESS,pageInfo); + + } + + @Transactional(rollbackFor = Exception.class) + public void test(String payOrderNO) { + TbOrderInfo orderInfo = tbOrderInfoMapper.selectByPayOrderNo(payOrderNO); + sendOrderToClient(orderInfo); + } + + + + /** + * 生成长度为12的随机串 + * + * @return + */ + public static String genCouponNumber() { + Random random = new Random(); + long min = 10000000000L; + long max = 19999999999L; + // 生成介于min和max之间的随机整数 + long randomNumber = min + ((long) (random.nextDouble() * (max - min))); + // 将随机整数转换为字符串,并在前面补0,直到长度为12位 + return String.format("%012d", randomNumber); + } + + /** + * 获取一个月后的时间 + * + * @return + */ + public Date getNextMonDate() { + // 获取当前日期和时间 + LocalDateTime currentDateTime = LocalDateTime.now(); + // 计算一个月后的日期和时间 + LocalDateTime nextMonthDateTime = currentDateTime.plusMonths(1); + return java.sql.Timestamp.valueOf(nextMonthDateTime); + } + + @Transactional(rollbackFor = Exception.class) public String minsuccess(String payOrderNO,String tradeNo){ @@ -421,62 +1055,210 @@ public class PayService { TbShopUserFlow flow=new TbShopUserFlow(); flow.setShopUserId(Integer.valueOf(tbShopUser.getId())); flow.setBizCode("scanMemberIn"); + flow.setBizName("会员扫码充值"); + flow.setType("+"); flow.setAmount(memberIn.getAmount()); flow.setBalance(tbShopUser.getAmount()); flow.setCreateTime(new Date()); tbShopUserFlowMapper.insert(flow); + TbActivate activate= tbActivateMapper.selectByAmount(tbShopUser.getShopId(),memberIn.getAmount()); + if(ObjectUtil.isNotEmpty(activate)&&ObjectUtil.isNotNull(activate)){ + BigDecimal amount=BigDecimal.ZERO; + switch (activate.getHandselType()){ + case "GD": + amount=activate.getHandselNum(); + break; + case "RATIO": + amount=memberIn.getAmount().multiply(activate.getHandselNum()); + break; + } + + + tbShopUser.setAmount(tbShopUser.getAmount().add(amount)); + tbShopUser.setUpdatedAt(System.currentTimeMillis()); + tbShopUserMapper.updateByPrimaryKeySelective(tbShopUser); + + flow=new TbShopUserFlow(); + flow.setShopUserId(Integer.valueOf(tbShopUser.getId())); + flow.setBizCode("scanMemberAwardIn"); + flow.setBizName("会员充值奖励"); + flow.setType("+"); + flow.setAmount(amount); + flow.setBalance(tbShopUser.getAmount()); + flow.setCreateTime(new Date()); + tbShopUserFlowMapper.insert(flow); + + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("shopId", memberIn.getShopId()); + jsonObject.put("type", "wxMemberIn"); + jsonObject.put("amount",memberIn.getAmount()); + producer.putOrderCollect(jsonObject.toJSONString()); + + } return "success"; } + + public String fstMemberInSuccess(String payOrderNO,String tradeNo){ + TbMemberIn memberIn= tbMemberInMapper.selectByOrderNo(payOrderNO); + if(ObjectUtil.isEmpty(memberIn)){ + return "充值记录不存在"; + } + + if(!"7".equals(memberIn.getStatus())){ + return "订单已处理"; + } + + memberIn.setTradeNo(tradeNo); + memberIn.setStatus("0"); + memberIn.setUpdateTime(new Date()); + tbMemberInMapper.updateByPrimaryKeySelective(memberIn); + + TbShopUser tbShopUser= tbShopUserMapper.selectByUserIdAndShopId(memberIn.getUserId().toString(),memberIn.getShopId().toString()); + if(ObjectUtil.isEmpty(tbShopUser)){ + return "用户信息不存在"; + } + + if(!"1".equals(tbShopUser.getIsVip().toString())){ + TbUserInfo userInfo = tbUserInfoMapper.selectByPrimaryKey(memberIn.getUserId()); + tbShopUser.setName(userInfo.getNickName()); + tbShopUser.setTelephone(userInfo.getTelephone()); + tbShopUser.setCode(RandomUtil.randomNumbers(8)); + tbShopUser.setIsVip(Byte.parseByte("1")); + } + + //修改客户资金 + tbShopUser.setAmount(tbShopUser.getAmount().add(memberIn.getAmount())); + tbShopUser.setUpdatedAt(System.currentTimeMillis()); + tbShopUserMapper.updateByPrimaryKeySelective(tbShopUser); + + TbShopUserFlow flow=new TbShopUserFlow(); + flow.setShopUserId(Integer.valueOf(tbShopUser.getId())); + flow.setBizCode("scanMemberIn"); + flow.setType("+"); + + flow.setBizName("线上充值"); + flow.setAmount(memberIn.getAmount()); + flow.setBalance(tbShopUser.getAmount()); + flow.setCreateTime(new Date()); + tbShopUserFlowMapper.insert(flow); + + TbActivate activate= tbActivateMapper.selectByAmount(tbShopUser.getShopId(),memberIn.getAmount()); + if(ObjectUtil.isNotEmpty(activate)&&ObjectUtil.isNotNull(activate)){ + BigDecimal amount=BigDecimal.ZERO; + switch (activate.getHandselType()){ + case "GD": + amount=activate.getHandselNum(); + break; + case "RATIO": + amount=memberIn.getAmount().multiply(activate.getHandselNum()); + break; + } + + + tbShopUser.setAmount(tbShopUser.getAmount().add(amount)); + tbShopUser.setUpdatedAt(System.currentTimeMillis()); + tbShopUserMapper.updateByPrimaryKeySelective(tbShopUser); + + flow=new TbShopUserFlow(); + flow.setShopUserId(Integer.valueOf(tbShopUser.getId())); + flow.setBizCode("scanMemberAwardIn"); + flow.setType("+"); + flow.setBizName("充值活动奖励"); + flow.setAmount(amount); + flow.setBalance(tbShopUser.getAmount()); + flow.setCreateTime(new Date()); + tbShopUserFlowMapper.insert(flow); + } + + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("shopId", memberIn.getShopId()); + jsonObject.put("type", "wxMemberIn"); + jsonObject.put("amount",memberIn.getAmount()); + producer.putOrderCollect(jsonObject.toJSONString()); + return "SUCCESS"; + } + + public void sendOrderToClient(TbOrderInfo orderInfo) { + List tbCashierCarts = tbCashierCartMapper.selectByOrderId(orderInfo.getId().toString(), null); + JSONObject client = new JSONObject(); + JSONObject order = new JSONObject(); + order.put("orderNo",orderInfo.getOrderNo()); + order.put("masterId",StringUtils.isNotBlank(orderInfo.getMasterId())?orderInfo.getMasterId():""); + order.put("tableName",StringUtils.isNotBlank(orderInfo.getTableName())?orderInfo.getTableName():""); + client.put("carts", tbCashierCarts); + client.put("type", "order"); + client.put("amount", orderInfo.getPayAmount()); + client.put("remark", StringUtils.isNotBlank(orderInfo.getRemark())?orderInfo.getRemark():""); + client.put("orderInfo", order); + client.put("createdAt", orderInfo.getCreatedAt()); + client.put("outNumber", StringUtils.isNotBlank(orderInfo.getOutNumber())?orderInfo.getOutNumber():""); +// client.put("outNumberCode", ""); +// if(StringUtils.isNotBlank(orderInfo.getOutNumber())){ +// try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { +// QrCodeUtils.createCodeToOutputStream(orderInfo.getOutNumber(), outputStream); +// String s = Base64Utils.encodeToString(outputStream.toByteArray()); +// client.put("outNumberCode", s); +// } catch (Exception e) { +// log.info("生成 失败"); +// e.printStackTrace(); +// } +// } + PushToClientChannelHandlerAdapter.getInstance().AppSendInfo(client.toString(), orderInfo.getShopId(), "", false); + } + + // public Result returnOrder(){ // // } - public static void main(String[] args){ - - RestTemplate restTemplate1= new RestTemplate(); - JSONObject param=new JSONObject(); - - String priv="MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIqNqTqhN8zE7eFZnwKcyBTENce2wdAtl/gaDHNuNVgg33dS27Jx0fKl9QSHXyzyxbAdG8F94niYbRBstrMymFRjuO72jH+rIH62Ym1k7l8JSLVK2dKHXt8lHDaQGUP10q0EEocnDQ9cL93oBNG1ttsV6vOAu1TPvRK9TGihRAe1AgMBAAECgYBmI8KCl0DkcrSOsRvYuC2DqZWf8el1B3eFjeZp3e/zVOCIPYv6Q5ArWg6DVSxjnWEA0KSagqvGjU+xkQMqnXzPcPMhsIS+1wyR/pP+pwiatO2ioHaQpEqHg9eXhxrgA477/xuKVw9zl5GNqaIgd++2NDXnqLh0Y6OR73f0OB5eDQJBAPihEm+UWLOam/Q/k2+k4Lm2dvxJTBur1fslBiJpgMhgcz/PlwRwpL7aPD0AuPv0NqLouuoTiKpq9icnUv12tgsCQQCOqTANw0IErCHUNdinjXewmG3ui1j9XgM41rSn5ZeTrPL4GhZc2zbS/pZT4PBKUL6NLGkfPHmw4rOmNL/Xc5E/AkBqAwQBX5eSvVHSC2mqKPtJNGv3lqlFAzfyJg8/jQzEY5vAkZsq4Xzdg+A7gptdkvvY6rMIK9wSDhl3CGVyfbORAkA1N+g1OiHmnFACWhP4bU25EyPvWQxZeDi7e1zpRTzGWj5JT3IIMb7B9zcdE0yQbI6pG2gbvvOmiOt7lTH7raEBAkBas2gugvR3f0aGqQcqMpyM627pyRppQ2h58/7KBylP3oR2BReqMUcXeiJ8TuBXzbRXpeVQ0DWOva5CWZJmBMdz"; - - PayReq req=new PayReq(); - - req.setAppId("M8002023120892f1e4"); - req.setTimestamp(System.currentTimeMillis()); - req.setIp("127.0.0.1"); - req.setMercOrderNo(System.currentTimeMillis()+""); - req.setNotifyUrl("https"); - req.setPayAmt("0.01"); - req.setPayType("03"); - req.setPayWay("WXZF"); - req.setSubject("ddd"); - req.setUserId("or1l864NBOoJZhC5x_yeziZ26j6c"); - - Map map= BeanUtil.transBeanMap(req); - - req.setSign(MD5Util.encrypt(map,priv,true)); - - - ResponseEntity response= restTemplate1.postForEntity("https://gatewaytestapi.sxczgkj.cn/gate-service/trans/pay",req,String.class); - - - -// TradeQueryReq req=new TradeQueryReq(); -// req.setAppId("M800202305094c170c"); +// public static void main(String[] args){ +// +// RestTemplate restTemplate1= new RestTemplate(); +// JSONObject param=new JSONObject(); +// +// String priv="MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIqNqTqhN8zE7eFZnwKcyBTENce2wdAtl/gaDHNuNVgg33dS27Jx0fKl9QSHXyzyxbAdG8F94niYbRBstrMymFRjuO72jH+rIH62Ym1k7l8JSLVK2dKHXt8lHDaQGUP10q0EEocnDQ9cL93oBNG1ttsV6vOAu1TPvRK9TGihRAe1AgMBAAECgYBmI8KCl0DkcrSOsRvYuC2DqZWf8el1B3eFjeZp3e/zVOCIPYv6Q5ArWg6DVSxjnWEA0KSagqvGjU+xkQMqnXzPcPMhsIS+1wyR/pP+pwiatO2ioHaQpEqHg9eXhxrgA477/xuKVw9zl5GNqaIgd++2NDXnqLh0Y6OR73f0OB5eDQJBAPihEm+UWLOam/Q/k2+k4Lm2dvxJTBur1fslBiJpgMhgcz/PlwRwpL7aPD0AuPv0NqLouuoTiKpq9icnUv12tgsCQQCOqTANw0IErCHUNdinjXewmG3ui1j9XgM41rSn5ZeTrPL4GhZc2zbS/pZT4PBKUL6NLGkfPHmw4rOmNL/Xc5E/AkBqAwQBX5eSvVHSC2mqKPtJNGv3lqlFAzfyJg8/jQzEY5vAkZsq4Xzdg+A7gptdkvvY6rMIK9wSDhl3CGVyfbORAkA1N+g1OiHmnFACWhP4bU25EyPvWQxZeDi7e1zpRTzGWj5JT3IIMb7B9zcdE0yQbI6pG2gbvvOmiOt7lTH7raEBAkBas2gugvR3f0aGqQcqMpyM627pyRppQ2h58/7KBylP3oR2BReqMUcXeiJ8TuBXzbRXpeVQ0DWOva5CWZJmBMdz"; +// +// PayReq req=new PayReq(); +// +// req.setAppId("M8002023120892f1e4"); // req.setTimestamp(System.currentTimeMillis()); -// req.setOrderNumber("SXF_W_MERC_20240205182102491"); +// req.setIp("127.0.0.1"); +// req.setMercOrderNo(System.currentTimeMillis()+""); +// req.setNotifyUrl("https"); +// req.setPayAmt("0.01"); +// req.setPayType("03"); +// req.setPayWay("WXZF"); +// req.setSubject("ddd"); +// req.setUserId("or1l864NBOoJZhC5x_yeziZ26j6c"); +// // Map map= BeanUtil.transBeanMap(req); // // req.setSign(MD5Util.encrypt(map,priv,true)); // -// ResponseEntity response= restTemplate1.postForEntity("https://gateway.api.sxczgkj.cn/gate-service/merchantOrder/tradeQuery",req,String.class); +// +// ResponseEntity response= restTemplate1.postForEntity("https://gatewaytestapi.sxczgkj.cn/gate-service/trans/pay",req,String.class); // // - System.out.println(">>>>>>>>>>>>>>>"+response.getBody()); - } +// +//// TradeQueryReq req=new TradeQueryReq(); +//// req.setAppId("M800202305094c170c"); +//// req.setTimestamp(System.currentTimeMillis()); +//// req.setOrderNumber("SXF_W_MERC_20240205182102491"); +//// Map map= BeanUtil.transBeanMap(req); +//// +//// req.setSign(MD5Util.encrypt(map,priv,true)); +//// +//// ResponseEntity response= restTemplate1.postForEntity("https://gateway.api.sxczgkj.cn/gate-service/merchantOrder/tradeQuery",req,String.class); +//// +//// +// System.out.println(">>>>>>>>>>>>>>>"+response.getBody()); +// } 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 4942b0e..6eab725 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/service/ProductService.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/ProductService.java @@ -1,22 +1,31 @@ package com.chaozhanggui.system.cashierservice.service; - import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.RandomUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; import com.chaozhanggui.system.cashierservice.dao.*; import com.chaozhanggui.system.cashierservice.entity.*; +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; 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.util.CollectionUtils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Set; +import javax.annotation.Resource; +import java.math.BigDecimal; +import java.util.*; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import java.util.stream.Collectors; @Service @Slf4j @@ -37,85 +46,391 @@ public class ProductService { @Autowired private TbShopTableMapper tbShopTableMapper; - - + @Resource + private TagProductDeptsMapper tagProductDeptsMapper; + @Resource + private TbPlatformDictMapper platformDictMapper; + @Resource + private TbShopUnitMapper unitMapper; + @Resource + private TbShopCategoryMapper categoryMapper; + @Resource + private TbPurchaseNoticeMapper purchaseNoticeMapper; @Autowired TbProductSkuMapper tbProductSkuMapper; + @Autowired + private TbShopUserMapper tbShopUserMapper; + @Autowired + private TbUserInfoMapper tbUserInfoMapper; + public Result queryShopIdByTableCode(String userId,String openId,String code) { + String shopId = tbShopTableMapper.queryShopIdByTableCode(code); + if (StringUtils.isBlank(shopId)) { + return Result.fail("台桌信息不存在"); + } + TbShopUser shopUser = tbShopUserMapper.selectByUserIdAndShopId(userId, shopId); + try{ + if (ObjectUtil.isEmpty(shopUser)) { + TbUserInfo tbUserInfo = tbUserInfoMapper.selectByPrimaryKey(Integer.valueOf(userId)); + shopUser = tbShopUserMapper.selectByPhoneAndShopId(tbUserInfo.getTelephone(), shopId); + if(ObjectUtil.isEmpty(shopUser)){ + shopUser=new TbShopUser(); + shopUser.setName(tbUserInfo.getNickName()); + shopUser.setSex(tbUserInfo.getSex()); + shopUser.setBirthDay(tbUserInfo.getBirthDay()); + shopUser.setLevel(Byte.parseByte("1")); + String dynamicCode = RandomUtil.randomNumbers(8); + shopUser.setCode(dynamicCode); + shopUser.setTelephone(tbUserInfo.getTelephone()); + shopUser.setAmount(BigDecimal.ZERO); + shopUser.setIsVip(Byte.parseByte("0")); + shopUser.setCreditAmount(BigDecimal.ZERO); + shopUser.setConsumeAmount(BigDecimal.ZERO); + shopUser.setConsumeNumber(0); + shopUser.setLevelConsume(BigDecimal.ZERO); + shopUser.setStatus(Byte.parseByte("1")); + shopUser.setShopId(shopId); + shopUser.setUserId(userId); + shopUser.setMiniOpenId(openId); + shopUser.setCreatedAt(System.currentTimeMillis()); + shopUser.setUpdatedAt(System.currentTimeMillis()); + tbShopUserMapper.insert(shopUser); + }else { + shopUser.setUserId(userId); + shopUser.setUpdatedAt(System.currentTimeMillis()); + tbShopUserMapper.updateByPrimaryKey(shopUser); + } + }else { + shopUser.setUpdatedAt(System.currentTimeMillis()); + tbShopUserMapper.updateByPrimaryKey(shopUser); + } + }catch (Exception e){ + log.info("通过桌码获取shopId 进行用户绑定错误:{}",e.getMessage()); + e.printStackTrace(); + } + return Result.success(CodeEnum.SUCCESS, shopId); + } + public Result queryProduct(String code, String productGroupId) { + ConcurrentMap concurrentMap = new ConcurrentHashMap<>(); - - public Result queryProduct(String code,String productGroupId){ - - ConcurrentMap concurrentMap=new ConcurrentHashMap<>(); - - TbShopTable tbShopTable= tbShopTableMapper.selectQRcode(code); - if(ObjectUtil.isEmpty(tbShopTable)||ObjectUtil.isNull(tbShopTable)){ + TbShopTable tbShopTable = tbShopTableMapper.selectQRcode(code); + if (ObjectUtil.isEmpty(tbShopTable) || ObjectUtil.isNull(tbShopTable)) { return Result.fail("台桌信息不存在"); } - Integer id= ObjectUtil.isNotEmpty(productGroupId)?Integer.valueOf(productGroupId):null; - List groupList=tbProductGroupMapper.selectByQrcode(code,id); - if(ObjectUtil.isNotEmpty(groupList)&&groupList.size()>0){ + Integer id = ObjectUtil.isNotEmpty(productGroupId) ? Integer.valueOf(productGroupId) : null; + List groupList = tbProductGroupMapper.selectByQrcode(code, id); + if (ObjectUtil.isNotEmpty(groupList) && groupList.size() > 0) { - TbProductGroup group= groupList.get(0); - TbShopInfo shopInfo= tbShopInfoMapper.selectByPrimaryKey(group.getShopId()) ; - concurrentMap.put("shopTableInfo",tbShopTable); - concurrentMap.put("storeInfo",shopInfo); - groupList.parallelStream().forEach(g->{ - String in=g.getProductIds().substring(1,g.getProductIds().length()-1); + TbProductGroup group = groupList.get(0); + TbShopInfo shopInfo = tbShopInfoMapper.selectByPrimaryKey(group.getShopId()); + concurrentMap.put("shopTableInfo", tbShopTable); + concurrentMap.put("storeInfo", shopInfo); + groupList.parallelStream().forEach(g -> { + String in = g.getProductIds().substring(1, g.getProductIds().length() - 1); - 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()); - } - it.setCartNumber(sum==null?"0":String.valueOf(sum)); - TbProductSkuResult skuResult= tbProductSkuResultMapper.selectByPrimaryKey(it.getId()); + if (ObjectUtil.isNotEmpty(in) && ObjectUtil.isNotNull(in)) { + List products = tbProductMapper.selectByIdIn(in); + if (ObjectUtil.isNotEmpty(products) && products.size() > 0) { + products.parallelStream().forEach(it -> { + 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); }); g.setProducts(products); - }else { + } else { g.setProducts(new ArrayList<>()); } - }else { + } else { g.setProducts(new ArrayList<>()); } }); - concurrentMap.put("productInfo",groupList); + concurrentMap.put("productInfo", groupList); } - return Result.success(CodeEnum.SUCCESS,concurrentMap); + return Result.success(CodeEnum.SUCCESS, concurrentMap); } - public Result queryProductSku(String shopId, String productId, String spec_tag){ - if(ObjectUtil.isEmpty(shopId)||ObjectUtil.isEmpty(productId)){ + public Result queryProductSku(String shopId, String productId, String spec_tag) { + if (ObjectUtil.isEmpty(shopId) || ObjectUtil.isEmpty(productId)) { return Result.fail("参数错误"); } - TbProductSkuWithBLOBs tbProductSkuWithBLOBs= tbProductSkuMapper.selectByShopIdAndProductIdAndSpec(shopId,productId,spec_tag); - return Result.success(CodeEnum.SUCCESS,tbProductSkuWithBLOBs); + TbProductSkuWithBLOBs tbProductSkuWithBLOBs = tbProductSkuMapper.selectByShopIdAndProductIdAndSpec(shopId, productId, spec_tag); + return Result.success(CodeEnum.SUCCESS, tbProductSkuWithBLOBs); } + + /** + * 商品列表 + * 首页底部列表 + * 爆品上新 + * 销量榜 + * 咖啡饮品 + */ + public PageInfo products(HomeDto homeDto) { + if (homeDto.getOrderBy() == 5) { + homeDto.setPage(1); + homeDto.setSize(4); + } + if (homeDto.getType().equals("near")) { + homeDto.setType(""); + homeDto.setDistanceInKm("1"); + } + PageHelper.startPage(homeDto.getPage(), homeDto.getSize()); + //经纬度(附近一km) + Map topAndBottomMap = LocationUtils.returnLLSquarePoint( + Double.parseDouble(homeDto.getLng()), Double.parseDouble(homeDto.getLat()), homeDto.getDistanceInKm()); + List shopGroupInfoVos = new ArrayList<>(); + if (homeDto.getOrderBy() == 4) { + Long stTime = null; + Long enTime = null; + if (homeDto.getDateType() == 0) { + stTime = DateUtils.getDayStartLong(); + enTime = DateUtils.getDayEndLong(); + } else if (homeDto.getDateType() == 1) { + enTime = System.currentTimeMillis(); + stTime = enTime - 3600000L * 2; + } + shopGroupInfoVos = tbProductMapper.selHotGroups( + homeDto.getProName(),homeDto.getType(), +// DateUtils.getStrTime(new Date(stTime)), DateUtils.getStrTime(new Date(enTime)), + null, null, + homeDto.getAddress(), homeDto.getOrderBy().toString(), homeDto.getLng(), homeDto.getLat()); + } else { + shopGroupInfoVos = tbProductMapper.selGroups( + homeDto.getProName(),homeDto.getType(), + topAndBottomMap.get("rightTopPoint")[1], topAndBottomMap.get("rightTopPoint")[0], + topAndBottomMap.get("leftBottomPoint")[1], topAndBottomMap.get("leftBottomPoint")[0], + homeDto.getAddress(), homeDto.getOrderBy().toString(), homeDto.getLng(), homeDto.getLat()); + } + if (CollectionUtils.isEmpty(shopGroupInfoVos)) { + return new PageInfo(shopGroupInfoVos); + } + List productIds = shopGroupInfoVos.stream() + .filter(Objects::nonNull) // 过滤掉 null 的 ShopGroupInfoVo 对象 + .map(ShopGroupInfoVo::getProId) + .filter(Objects::nonNull) // 过滤掉 null 的 ProId + .collect(Collectors.toList()); + + List stringList = productIds.stream() + .map(Object::toString) // 将 Integer 对象映射为 String 对象 + .collect(Collectors.toList()); + List tbProductSkus = tbProductSkuMapper.selectSkus(stringList); + List dictPro = tagProductDeptsMapper.queryTagAndProduct(productIds); + //组装 + List homeVOList = new ArrayList<>(); + for (ShopGroupInfoVo o : shopGroupInfoVos) { + if (o.getProId() == null) { + continue; + } + HomeVO homeVO = new HomeVO(); + homeVO.setId(o.getProId()); + homeVO.setShopName(o.getShopName()); + homeVO.setShopImage(o.getShopImg()); + homeVO.setDistricts(o.getDistricts()); + if (StringUtils.isBlank(o.getShopTag())) { + homeVO.setShopTag(new ArrayList<>()); + } else { + List shopTagIds = Arrays.stream(o.getShopTag().split(",")) + .map(Integer::parseInt) + .collect(Collectors.toList()); + List tbPlatformDicts = platformDictMapper.queryByIdList(shopTagIds); + homeVO.setShopTag(JSONUtil.parseListTNewList(tbPlatformDicts, TagVo.class)); + } + if (StringUtils.isNotBlank(o.getLat()) && StringUtils.isNotBlank(o.getLng())) { + String distance = LocationUtils.getDistanceString( + Double.parseDouble(homeDto.getLng()), Double.parseDouble(homeDto.getLat()), + Double.parseDouble(o.getLng()), Double.parseDouble(o.getLat())); + homeVO.setDistances(distance); + } + homeVO.setProductName(o.getProName()); + homeVO.setImage(o.getProImg()); + for (TagProductVO tagProductVO : dictPro) { + if (o.getProId().toString().equals(tagProductVO.getProductId().toString())) { + homeVO.getProTag().add(tagProductVO); + } + } + for (TbProductSku tbProductSku : tbProductSkus) { + if (o.getProId().toString().equals(tbProductSku.getProductId())) { + //原价 + if (tbProductSku.getOriginPrice().compareTo(BigDecimal.ZERO) == 0) { + homeVO.setOriginPrice(BigDecimal.ZERO); + homeVO.setDiscount(BigDecimal.ZERO); + } else { + homeVO.setOriginPrice(tbProductSku.getOriginPrice()); + homeVO.setDiscount(BigDecimalUtils.getDiscount(tbProductSku.getOriginPrice(), tbProductSku.getSalePrice())); + } + //销量 + homeVO.setRealSalesNumber(new BigDecimal(o.getNumber())); + //现价 + homeVO.setSalePrice(new BigDecimal(tbProductSku.getSalePrice().toString())); + // 共省金额 + homeVO.setSave(homeVO.getOriginPrice().subtract(homeVO.getSalePrice())); + } + } + + homeVO.setEndTime(DateUtils.getDayEndLong()); + homeVOList.add(homeVO); + } + PageInfo pageInfo = new PageInfo<>(shopGroupInfoVos); + pageInfo.setList(homeVOList); + + return pageInfo; + } + + + /** + * 团购卷详情 + * + * @param productId 团购卷Id + * @return + * @throws Exception + */ + public Result productInfo(Integer productId, String lat, String lng, String environment) throws Exception { + if (StringUtils.isBlank(lat) || lat.equals("undefined")) { + lat = "34.343207"; + lng = "108.939645"; + } + CompletableFuture product = CompletableFuture.supplyAsync(() -> + tbProductMapper.selectByPrimaryKey(productId)); + CompletableFuture> productSku = CompletableFuture.supplyAsync(() -> + tbProductSkuMapper.selectSku(productId.toString())); + Threads.call(product, productSku); + + TbProductWithBLOBs tbProduct = product.get(); + TbShopInfo tbShopInfo = tbShopInfoMapper.selectByPrimaryKey(Integer.valueOf(tbProduct.getShopId())); + TbPurchaseNotice tbPurchaseNotice = purchaseNoticeMapper.queryByCouponId(tbProduct.getId()); + + + ProductInfoVo productInfo = new ProductInfoVo(); + // 图片组装 + if (StringUtils.isNotBlank(tbProduct.getImages())) { + productInfo.setImages(JSON.parseArray(tbProduct.getImages())); + } else { + productInfo.setImages(new JSONArray()); + } + + //价格组装 + for (TbProductSku tbProductSku : productSku.get()) { + //售价 + if (tbProductSku.getSalePrice().compareTo(BigDecimal.ZERO) == 0) { + if (tbProductSku.getOriginPrice().compareTo(BigDecimal.ZERO) == 0) { + productInfo.setOriginPrice(BigDecimal.ZERO); + productInfo.setDiscount(BigDecimal.ZERO); + productInfo.setSalePrice(BigDecimal.ZERO); + } else { + productInfo.setOriginPrice(tbProductSku.getOriginPrice()); + productInfo.setDiscount(BigDecimal.ZERO); + productInfo.setSalePrice(tbProductSku.getOriginPrice()); + } + } else { + productInfo.setOriginPrice(tbProductSku.getOriginPrice()); + productInfo.setDiscount(BigDecimalUtils.getDiscount(tbProductSku.getOriginPrice(), tbProductSku.getSalePrice())); + //现价 + productInfo.setSalePrice(tbProductSku.getSalePrice()); + } + } + //销量 + productInfo.setRealSalesNumber(new BigDecimal(tbProduct.getRealSalesNumber())); + //名称 + productInfo.setProductName(tbProduct.getName()); + //店铺 + productInfo.setShopName(tbShopInfo.getShopName()); + if (StringUtils.isNotBlank(tbShopInfo.getChainName())) { + productInfo.setChainName(tbShopInfo.getChainName()); + Integer i = tbShopInfoMapper.selNumByChain(tbShopInfo.getChainName()); + productInfo.setShopNum(i); + } + productInfo.setPhone(tbShopInfo.getPhone()); + productInfo.setLat(tbShopInfo.getLat()); + productInfo.setLng(tbShopInfo.getLng()); + if(StringUtils.isNotBlank(tbShopInfo.getBusinessStartDay())){ + productInfo.setBusinessTime(tbShopInfo.getBusinessStartDay() + "至" + tbShopInfo.getBusinessEndDay() + " " + tbShopInfo.getBusinessTime()); + } + String distance = LocationUtils.getDistanceString( + Double.parseDouble(lng), Double.parseDouble(lat), + Double.parseDouble(tbShopInfo.getLng()), Double.parseDouble(tbShopInfo.getLat())); + productInfo.setDistances(distance);//距离 + productInfo.setAddress(tbShopInfo.getAddress()); + productInfo.setDistricts(tbShopInfo.getDistricts()); + + List productVos = JSONUtil.parseListTNewList(tbProduct.getGroupSnap(), ProductVo.class); + for (ProductVo productVo : productVos) { + for (ProductVo.Food good : productVo.getGoods()) { + List dictPro = tagProductDeptsMapper.queryTagByProductId(good.getId().toString()); + good.setProTag(dictPro); + } + } + + productInfo.setProductList(productVos); + + List tbPlatformDicts = platformDictMapper.queryAllByType("prodetail", environment); + if (tbPurchaseNotice != null) { + productInfo.setPurchaseNotice(tbPurchaseNotice); + if (tbPurchaseNotice.getBookingType().startsWith("无需预约")) { + List book = platformDictMapper.queryAllByType("prodetail-book", environment); + tbPlatformDicts.addAll(book); + } + } + productInfo.setNoticeTag(JSONUtil.parseListTNewList(tbPlatformDicts, TagVo.class)); + return Result.success(CodeEnum.SUCCESS, productInfo); + } + + /** + * 订单确认页 + */ + public Result orderConfirm(Integer productId, String environment) throws Exception { + CompletableFuture product = CompletableFuture.supplyAsync(() -> + tbProductMapper.selectById(productId)); + CompletableFuture> productSku = CompletableFuture.supplyAsync(() -> + tbProductSkuMapper.selectSku(productId.toString())); + CompletableFuture notice = CompletableFuture.supplyAsync(() -> + purchaseNoticeMapper.queryByCouponId(productId)); + Threads.call(product, productSku, notice); + + TbProduct tbProduct = product.get(); + OrderConfirmVo confirmVo = new OrderConfirmVo(); + confirmVo.setProId(tbProduct.getId().toString()); + confirmVo.setShopId(tbProduct.getShopId()); + confirmVo.setProImg(tbProduct.getCoverImg()); + confirmVo.setProName(tbProduct.getName()); + + TbShopInfo tbShopInfo = tbShopInfoMapper.selectByPrimaryKey(Integer.valueOf(tbProduct.getShopId())); + confirmVo.setIsUseVip(tbShopInfo.getIsUseVip()); + TbPurchaseNotice tbPurchaseNotice = notice.get(); + if (tbPurchaseNotice != null) { + confirmVo.setAvaTime(tbPurchaseNotice.getAvailableTime()); + } + + //价格组装 + for (TbProductSku tbProductSku : productSku.get()) { + //原价 + if (tbProductSku.getOriginPrice().compareTo(BigDecimal.ZERO) == 0) { + confirmVo.setOriginPrice(BigDecimal.ZERO); + confirmVo.setSave(tbProductSku.getSalePrice()); + } else { + confirmVo.setOriginPrice(tbProductSku.getOriginPrice()); + confirmVo.setSave(tbProductSku.getOriginPrice().subtract(tbProductSku.getSalePrice())); + } + //现价=售价 + confirmVo.setSalePrice(tbProductSku.getSalePrice()); + } + List tbPlatformDicts = platformDictMapper.queryAllByType("order_confirm_no_counpon", environment); + if (!CollectionUtils.isEmpty(tbPlatformDicts)) { + confirmVo.setCouponDetail(JSONUtil.parseListTNewList(tbPlatformDicts, TagVo.class).get(0)); + } + return Result.success(CodeEnum.SUCCESS, confirmVo); + } } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/ShopTableService.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/ShopTableService.java index b172a9b..a85520e 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/service/ShopTableService.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/ShopTableService.java @@ -1,12 +1,11 @@ package com.chaozhanggui.system.cashierservice.service; -import com.chaozhanggui.system.cashierservice.annotation.ResultCode; import com.chaozhanggui.system.cashierservice.dao.TbShopAreaMapper; import com.chaozhanggui.system.cashierservice.dao.TbShopTableMapper; import com.chaozhanggui.system.cashierservice.entity.TbShopArea; import com.chaozhanggui.system.cashierservice.entity.TbShopTable; -import com.chaozhanggui.system.cashierservice.exception.MsgException; import com.chaozhanggui.system.cashierservice.sign.CodeEnum; import com.chaozhanggui.system.cashierservice.sign.Result; +import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import javax.annotation.Resource; @@ -25,6 +24,10 @@ public class ShopTableService { private TbShopAreaMapper shopAreaMapper; public Result bindingQrcode(TbShopTable shopTable){ + if(StringUtils.isBlank(shopTable.getQrcode())){ + return Result.fail("绑定桌码不可为空"); + } + shopTableMapper.upDateQrcodeNull(shopTable.getQrcode()); TbShopTable shopTableId = shopTableMapper.selectByPrimaryKey(shopTable.getId()); if (shopTableId == null){ return Result.fail("找不到台桌"); diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/ShopVideoService.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/ShopVideoService.java new file mode 100644 index 0000000..0a897e5 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/ShopVideoService.java @@ -0,0 +1,38 @@ +package com.chaozhanggui.system.cashierservice.service; + +import com.chaozhanggui.system.cashierservice.dao.TbShopVideoMapper; +import com.chaozhanggui.system.cashierservice.entity.TbShopVideo; +import com.chaozhanggui.system.cashierservice.sign.CodeEnum; +import com.chaozhanggui.system.cashierservice.sign.Result; + +import javax.annotation.Resource; + +/** + * 视频号 公众号 + * @author ww + * @since 2024-04-12 14:50:10 + */ +public class ShopVideoService { + + @Resource + private TbShopVideoMapper tbShopVideoMapper; + + /** + * 通过ID查询单条数据 + * + * @param id 主键 + * @return 实例对象 + */ + public Result queryById(Integer id) { + return Result.success(CodeEnum.ENCRYPT,tbShopVideoMapper.queryById(id)); + } + + /** + * @param tbShopVideo 筛选条件 + * @return 查询结果 + */ + public Result queryAll(TbShopVideo tbShopVideo) { + tbShopVideo.setStatus(1); + return Result.success(CodeEnum.ENCRYPT,tbShopVideoMapper.queryAll(tbShopVideo)); + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/UserService.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/UserService.java new file mode 100644 index 0000000..c39c22d --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/UserService.java @@ -0,0 +1,231 @@ +package com.chaozhanggui.system.cashierservice.service; + +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.RandomUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.chaozhanggui.system.cashierservice.dao.*; +import com.chaozhanggui.system.cashierservice.entity.*; +import com.chaozhanggui.system.cashierservice.entity.vo.IntegralFlowVo; +import com.chaozhanggui.system.cashierservice.entity.vo.IntegralVo; +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.sign.CodeEnum; +import com.chaozhanggui.system.cashierservice.sign.Result; +import com.chaozhanggui.system.cashierservice.util.*; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.math.BigDecimal; +import java.util.*; +import java.util.concurrent.TimeUnit; + +@Service +public class UserService { + + + @Autowired + private TbShopUserMapper shopUserMapper; + @Autowired + private TbReleaseFlowMapper releaseFlowMapper; + @Autowired + private TbUserInfoMapper userInfoMapper; + @Autowired + private TbUserCouponsMapper userCouponsMapper; + @Autowired + private TbSystemCouponsMapper systemCouponsMapper; + @Autowired + RedisUtils redisUtils; + + public JSONObject modityIntegral(IntegralVo integralVo, String userSign) { + JSONObject object = (JSONObject) JSONObject.toJSON(integralVo); + if (N.gt(BigDecimal.ZERO, integralVo.getNum())) { + JSONObject result = new JSONObject(); + result.put("status", "fail"); + result.put("msg", "积分数量不允许小于0"); + result.put("data", ""); + return result; + } + object.put("userSign", userSign); + + JSONObject jsonObject = JSONUtil.sortJSONObject(object, CacheMap.map); + System.out.println(jsonObject.toJSONString()); + String sign = MD5Util.encrypt(jsonObject.toJSONString()); + if (!sign.equals(integralVo.getSign())) { + JSONObject result = new JSONObject(); + result.put("status", "fail"); + result.put("msg", "签名验证失败"); + result.put("data", ""); + return result; + } + TbShopUser shopUser = shopUserMapper.selectByOpenId(integralVo.getOpenId()); + if (Objects.isNull(shopUser)) { + JSONObject result = new JSONObject(); + result.put("status", "fail"); + result.put("msg", "用户不存在"); + result.put("data", ""); + return result; + } + boolean falg = updateIntegral(shopUser.getUserId(), integralVo.getNum(), integralVo.getType()); + if (!falg) { + JSONObject result = new JSONObject(); + result.put("status", "fail"); + result.put("msg", "余额不足"); + result.put("data", ""); + return result; + } + JSONObject result = new JSONObject(); + result.put("status", "success"); + result.put("msg", "操作成功"); + return result; + } + + public static void main(String[] args) { + IntegralVo integralVo = new IntegralVo(); + integralVo.setNum(new BigDecimal("5254")); + integralVo.setOpenId("or1l864NBOoJZhC5x_yeziZ26j6c"); + integralVo.setType("sub"); + JSONObject object = (JSONObject) JSONObject.toJSON(integralVo); + object.put("userSign", "02c03d79c36b4c01b217ffb1baef9009"); + JSONObject jsonObject = JSONUtil.sortJSONObject(object, CacheMap.map); + System.out.println("加密前字符串:" + jsonObject.toJSONString()); + String sign = MD5Util.encrypt(jsonObject.toJSONString()); + System.out.println("加密后签名:" + sign); + } + + private Boolean updateIntegral(String userId, BigDecimal num, String type) { + + boolean lock_coin = redisUtils.lock(RedisCst.INTEGRAL_COIN_KEY + userId, 5000, TimeUnit.MILLISECONDS); + if (lock_coin) { + TbUserInfo tbShopUser = userInfoMapper.selectByPrimaryKey(Integer.valueOf(userId)); + boolean flag = true; + if (type.equals("sub")) { + if (num.intValue() < tbShopUser.getTotalScore()) { + flag = false; + } else { + tbShopUser.setTotalScore(tbShopUser.getTotalScore() - num.intValue()); + } + } else if (type.equals("add")) { + tbShopUser.setTotalScore(tbShopUser.getTotalScore() + num.intValue()); + } + if (flag) { + TbReleaseFlow releaseFlow = new TbReleaseFlow(); + releaseFlow.setNum(num); + releaseFlow.setCreateTime(new Date()); + releaseFlow.setFromSource("OWER"); + releaseFlow.setUserId(userId); + if (type.equals("sub")) { + releaseFlow.setType("BUYSUB"); + releaseFlow.setOperationType("SUB"); + releaseFlow.setRemark("购买商品扣除"); + } else if (type.equals("sub")) { + releaseFlow.setType("THREEADD"); + releaseFlow.setOperationType("ADD"); + releaseFlow.setRemark("退货增加"); + } + releaseFlowMapper.insert(releaseFlow); + userInfoMapper.updateByPrimaryKeySelective(tbShopUser); + } + redisUtils.releaseLock(RedisCst.INTEGRAL_COIN_KEY + userId); + return flag; + } else { + return updateIntegral(userId, num, type); + } + } + + public JSONObject userIntegral(IntegralFlowVo integralFlowVo, String userSign) { + JSONObject object = (JSONObject) JSONObject.toJSON(integralFlowVo); + object.put("userSign", userSign); + JSONObject jsonObject = JSONUtil.sortJSONObject(object, CacheMap.map); + System.out.println(jsonObject.toJSONString()); + String sign = MD5Util.encrypt(jsonObject.toJSONString()); + if (!sign.equals(integralFlowVo.getSign())) { + JSONObject result = new JSONObject(); + result.put("status", "fail"); + result.put("msg", "签名验证失败"); + result.put("data", ""); + return result; + } + TbUserInfo shopUser = userInfoMapper.selectByOpenId(integralFlowVo.getOpenId()); + if (Objects.isNull(shopUser)) { + JSONObject result = new JSONObject(); + result.put("status", "fail"); + result.put("msg", "用户不存在"); + result.put("data", ""); + return result; + } + PageHelper.startPage(integralFlowVo.getPage(), integralFlowVo.getPageSize()); + PageHelper.orderBy("id DESC"); + List list = releaseFlowMapper.selectByUserId(shopUser.getId().toString()); + for (TbReleaseFlow tbReleaseFlow:list){ + tbReleaseFlow.setCreateTr(DateUtils.getStrTime(tbReleaseFlow.getCreateTime())); + } + JSONObject result = new JSONObject(); + result.put("status", "success"); + result.put("msg", "成功"); + result.put("data", list); + return result; + } + + public JSONObject userAllIntegral(IntegralFlowVo integralFlowVo, String userSign) { +// JSONObject object = (JSONObject) JSONObject.toJSON(integralFlowVo); +// object.put("userSign", userSign); +// JSONObject jsonObject = JSONUtil.sortJSONObject(object, CacheMap.notOpenMap); +// System.out.println(jsonObject.toJSONString()); +// String sign = MD5Util.encrypt(jsonObject.toJSONString()); +// if (!sign.equals(integralFlowVo.getSign())) { +// JSONObject result = new JSONObject(); +// result.put("status", "fail"); +// result.put("msg", "签名验证失败"); +// result.put("data", ""); +// return result; +// } + PageHelper.startPage(integralFlowVo.getPage(), integralFlowVo.getPageSize()); + PageHelper.orderBy("id DESC"); + List list = releaseFlowMapper.selectAll(); + for (TbReleaseFlow tbReleaseFlow:list){ + tbReleaseFlow.setCreateTr(DateUtils.getStrTime(tbReleaseFlow.getCreateTime())); + } + PageInfo pageInfo = new PageInfo(list); + JSONObject result = new JSONObject(); + result.put("status", "success"); + result.put("msg", "成功"); + result.put("data", pageInfo); + return result; + } + + public JSONObject userAll(IntegralFlowVo integralFlowVo, String userSign) { +// JSONObject object = (JSONObject) JSONObject.toJSON(integralFlowVo); +// object.put("userSign", userSign); +// JSONObject jsonObject = JSONUtil.sortJSONObject(object, CacheMap.notOpenMap); +// System.out.println(jsonObject.toJSONString()); +// String sign = MD5Util.encrypt(jsonObject.toJSONString()); +// if (!sign.equals(integralFlowVo.getSign())) { +// JSONObject result = new JSONObject(); +// result.put("status", "fail"); +// result.put("msg", "签名验证失败"); +// result.put("data", ""); +// return result; +// } + PageHelper.startPage(integralFlowVo.getPage(), integralFlowVo.getPageSize()); + PageHelper.orderBy("id DESC"); + List list = userInfoMapper.selectAll(); + PageInfo pageInfo = new PageInfo(list); + JSONObject result = new JSONObject(); + result.put("status", "success"); + result.put("msg", "成功"); + result.put("data", pageInfo); + return result; + } + + public int userCoupon(String userId, BigDecimal orderNum) { + int userNum = userCouponsMapper.selectByUserIdAndAmount(userId,orderNum); + int sysNum = systemCouponsMapper.selectByAmount(orderNum); + return userNum+sysNum; + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/sign/CodeEnum.java b/src/main/java/com/chaozhanggui/system/cashierservice/sign/CodeEnum.java index ba24a7b..4cc4ff8 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/sign/CodeEnum.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/sign/CodeEnum.java @@ -8,8 +8,10 @@ public enum CodeEnum { UPGRADE_REQUIRED("426",false,"成功","success"), ENCRYPT("0",true,"成功","success"), FAIL("1",false,"失败","fail"), - TOKEN_EXEIST("-2",false,"token不能为空","fail"), - TOKEN_EXPIRED("-4",false,"账号已过期,请重新登陆","fail"), + FAIL_OLDPASS("1",false,"修改失败,旧密码错误","fail"), + FAIL_NEWPASS("1",false,"新密码不能与旧密码相同","fail"), + TOKEN_EXEIST("-4",false,"token不能为空","fail"), + TOKEN_EXPIRED("-4",false,"请先登陆","fail"), SIGN_FAIL("100013",false,"签名不正确","fail"), ORGAN_NO_EXEIST("100010",false,"机构代码不存在或状态异常,请联系服务商","fail"), diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/sign/Result.java b/src/main/java/com/chaozhanggui/system/cashierservice/sign/Result.java index 114d58a..e571b5c 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/sign/Result.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/sign/Result.java @@ -1,6 +1,7 @@ package com.chaozhanggui.system.cashierservice.sign; import cn.hutool.json.JSONUtil; +import com.chaozhanggui.system.cashierservice.exception.IError; import com.chaozhanggui.system.cashierservice.util.DESUtil; import java.util.List; @@ -52,6 +53,18 @@ public class Result { } +// public Result(String msg, Object data, String code, boolean encrypt, String icon) { +// this.msg = msg; +// this.code = code; +// this.encrypt = encrypt; +// this.icon = icon; +// if(encrypt){ +// this.data= DESUtil.encode(JSONUtil.toJsonStr(data)); +// }else{ +// this.data=data; +// } +// } + public Result(CodeEnum enums) { this.msg = enums.getMsg(); this.encrypt = enums.getEncrypt(); @@ -143,4 +156,21 @@ public class Result { dto.setIcon(CodeEnum.FAIL.getIcon()); return dto; } + public static Result failCode(String msg,String data) { + Result dto = new Result(); + dto.setMsg(msg); + dto.setEncrypt(false); + dto.setCode("1"); + dto.setData(data); + dto.setIcon(CodeEnum.FAIL.getIcon()); + return dto; + } + public static Result failure(IError error) { + Result dto = new Result(); + dto.setMsg(error.getErrorMessage()); + dto.setEncrypt(false); + dto.setCode(error.getErrorCode()); + dto.setIcon(CodeEnum.FAIL.getIcon()); + return dto; + } } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/socket/AppWebSocketServer.java b/src/main/java/com/chaozhanggui/system/cashierservice/socket/AppWebSocketServer.java deleted file mode 100644 index b689660..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/socket/AppWebSocketServer.java +++ /dev/null @@ -1,314 +0,0 @@ -package com.chaozhanggui.system.cashierservice.socket; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.chaozhanggui.system.cashierservice.config.WebSocketCustomEncoding; -import com.chaozhanggui.system.cashierservice.dao.TbShopTableMapper; -import com.chaozhanggui.system.cashierservice.entity.TbCashierCart; -import com.chaozhanggui.system.cashierservice.entity.TbShopTable; -import com.chaozhanggui.system.cashierservice.exception.MsgException; -import com.chaozhanggui.system.cashierservice.rabbit.RabbitProducer; -import com.chaozhanggui.system.cashierservice.redis.RedisCst; -import com.chaozhanggui.system.cashierservice.redis.RedisUtil; -import com.chaozhanggui.system.cashierservice.util.JSONUtil; -import com.chaozhanggui.system.cashierservice.util.SpringUtils; -import lombok.Data; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.springframework.stereotype.Component; - -import javax.annotation.PostConstruct; -import javax.annotation.Resource; -import javax.websocket.*; -import javax.websocket.server.PathParam; -import javax.websocket.server.ServerEndpoint; -import java.io.IOException; -import java.math.BigDecimal; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicBoolean; - -@ServerEndpoint(value = "/websocket/table/{tableId}/{shopId}/{userId}", encoders = WebSocketCustomEncoding.class) -@Component -@Slf4j -@Data -public class 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 ConcurrentHashMap> webSocketMap = new ConcurrentHashMap<>(); - public static ConcurrentHashMap> userMap = new ConcurrentHashMap<>(); - private static ConcurrentHashMap userSocketMap = new ConcurrentHashMap<>(); - //购物车的记录,用于第一次扫码的人同步购物车 - private static ConcurrentHashMap> recordMap = new ConcurrentHashMap<>(); - private static ConcurrentHashMap sessionMap = new ConcurrentHashMap<>(); - - /** - * 与某个客户端的连接会话,需要通过它来给客户端发送数据 - */ - private Session session; - - /** - * 接收tableId - */ - private String tableId = ""; - private String shopId = ""; - private String userId = ""; - - /** - * 用来标识这个用户需要接收同步的购物车信息 - */ - private volatile AtomicBoolean sync = new AtomicBoolean(true); - - private volatile AtomicBoolean createOrder = new AtomicBoolean(false); - - - /** - * 连接建立成功调用的方法 - */ - @OnOpen - public void onOpen(Session session, @PathParam("tableId") String tableId, @PathParam("shopId") String shopId, @PathParam("userId") String userId) { - this.session = session; - this.tableId = tableId; - this.shopId = shopId; - this.userId = userId; - try { - TbShopTable shopTable = shopTableMapper.selectQRcode(tableId); - if (Objects.isNull(shopTable)) { - JSONObject jsonObject1 = new JSONObject(); - jsonObject1.put("status", "fail"); - jsonObject1.put("msg", "桌码不存在"); - jsonObject1.put("type", "addCart"); - jsonObject1.put("data", new ArrayList<>()); - jsonObject1.put("amount", BigDecimal.ZERO); - sendMessage(jsonObject1); - onClose(); - } - if (webSocketMap.containsKey(tableId + "-" + shopId)) { - List serverList = webSocketMap.get(tableId + "-" + shopId); - serverList.add(this); - } else { - List serverList = new ArrayList<>(); - serverList.add(this); - webSocketMap.put(tableId + "-" + shopId, serverList); - } - if (userMap.containsKey(tableId + "-" + shopId)) { - Set userSet = userMap.get(tableId + "-" + shopId); - userSet.add(userId); - } else { - Set userSet = new HashSet<>(); - userSet.add(userId); - userMap.put(tableId + "-" + shopId,userSet); - } - - userSocketMap.put(userId, this); -// sessionMap.put(userId,session); - String mes = redisUtils.getMessage(RedisCst.TABLE_CART.concat(tableId + "-" + shopId)); - if (StringUtils.isEmpty(mes)) { - JSONObject jsonObject1 = new JSONObject(); - jsonObject1.put("status", "success"); - jsonObject1.put("msg", "成功"); - jsonObject1.put("type", "addCart"); - jsonObject1.put("data", new ArrayList<>()); - jsonObject1.put("amount", BigDecimal.ZERO); - sendMessage(jsonObject1); - } else { - JSONObject jsonObject1 = new JSONObject(); - jsonObject1.put("status", "success"); - jsonObject1.put("msg", "成功"); - jsonObject1.put("type", "addCart"); - BigDecimal amount = BigDecimal.ZERO; - JSONArray jsonArray = JSON.parseArray(redisUtils.getMessage(RedisCst.TABLE_CART.concat(tableId + "-" + shopId))); - for (int i = 0; i < jsonArray.size(); i++) { - JSONObject object = jsonArray.getJSONObject(i); - amount = amount.add(object.getBigDecimal("totalAmount")); - } - jsonObject1.put("amount", amount); - jsonObject1.put("data", jsonArray); - sendMessage(jsonObject1); - } -// sendMessage(recordMap.get(tableId)); - } catch (IOException e) { - log.error("用户:" + tableId + ",网络异常!!!!!!"); - } - } - - /** - * 连接关闭调用的方法 - */ - @OnClose - public void onClose() { - if (webSocketMap.containsKey(tableId + "-" + shopId)) { - List serverList = webSocketMap.get(tableId + "-" + shopId); - if (serverList.isEmpty()) { - webSocketMap.remove(tableId + "-" + shopId); - } - serverList.remove(this); - - } - if (userMap.containsKey(tableId + "-" + shopId)){ - Set userSet = userMap.get(tableId + "-" + shopId); - if (userSet.isEmpty()){ - userMap.remove(tableId + "-" + shopId); - } - userSet.remove(userId); - } - } - public static void onClosed(String user) throws IOException { - Session session1 = sessionMap.get(user); - session1.close(); - } - /** - * 收到客户端消息后调用的方法 - * - * @param message 客户端发送过来的消息 - */ - @OnMessage - public void onMessage(String message, Session session) { - - System.out.println(message); - //可以群发消息 - //消息保存到数据库、redis - if (StringUtils.isNotBlank(message) && !message.equals("undefined")) { - try { - //解析发送的报文 - JSONObject jsonObject = new JSONObject(); - if (StringUtils.isNotEmpty(message)) { - jsonObject = JSONObject.parseObject(message); - } - //追加发送人(防止串改) - jsonObject.put("tableId", this.tableId); - jsonObject.put("shopId", this.shopId); - - //这里采用责任链模式,每一个处理器对应一个前段发过来的请,这里还可以用工厂模式来生成对象 -// ChangeHandler changeHandler = new ChangeHandler(); -// CreateOrderHandler createOrderHandler = new CreateOrderHandler(); -// SyncHandler syncHandler = new SyncHandler(); -// ClearHandler clearHandler = new ClearHandler(); -// OtherHandler otherHandler = new OtherHandler(); -// -// changeHandler.addNextHandler(syncHandler).addNextHandler(createOrderHandler).addNextHandler(clearHandler).addNextHandler(otherHandler); -// changeHandler.handleRequest(webSocketMap,jsonObject,recordMap,this); - if ("sku".equals(jsonObject.getString("type"))){ - boolean exist = redisUtils.exists(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId))); - Integer num = 0; - if (exist){ - JSONArray array = JSON.parseArray(redisUtils.getMessage(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId)))); - for (int i = 0; i < array.size(); i++) { - JSONObject object = array.getJSONObject(i); - if (object.getString("skuId").equals(jsonObject.getString("skuId"))) { - num = object.getIntValue("totalNumber"); - break; - } - } - } - JSONObject jsonObject1 = new JSONObject(); - jsonObject1.put("status", "success"); - jsonObject1.put("msg", "成功"); - jsonObject1.put("type", "sku"); - jsonObject1.put("data", new ArrayList<>()); - jsonObject1.put("amount", num); - sendMessage(jsonObject1); - }else { - rabbitProducer.putCart(jsonObject.toJSONString()); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - /** - * 发生错误时候 - * - * @param session - * @param error - */ - @OnError - public void onError(Session session, Throwable error) { - log.error("用户错误:" + this.tableId + ",原因:" + error.getMessage()); - error.printStackTrace(); - } - - /** - * 实现服务器主动推送 - */ - public void sendMessage(Object message) throws IOException { - //加入线程锁 - synchronized (session) { - try { - //同步发送信息 - this.session.getBasicRemote().sendObject(message); - } catch (Exception e) { - log.error("服务器推送失败:" + e.getMessage()); - } - } - } - - - /** - * 发送自定义消息 - * */ - /** - * 发送自定义消息 - * - * @param message 发送的信息 - * @param tableId 如果为null默认发送所有 - * @throws IOException - */ - public static void AppSendInfo(Object message, String tableId, boolean userFlag) throws IOException { - if (userFlag) { - if (userSocketMap.containsKey(tableId)) { - AppWebSocketServer server = userSocketMap.get(tableId); - server.sendMessage(message); - } else { - log.error("请求的userId:" + tableId + "不在该服务器上"); - } - } else { - if (StringUtils.isEmpty(tableId)) { - // 向所有用户发送信息 - for (List serverList : webSocketMap.values()) { - for (AppWebSocketServer server : serverList) { - server.sendMessage(message); - } - } - } else if (webSocketMap.containsKey(tableId)) { - // 发送给指定用户信息 - List serverList = webSocketMap.get(tableId); - for (AppWebSocketServer server : serverList) { - server.sendMessage(message); - } - } else { - log.error("请求的tableId:" + tableId + "不在该服务器上"); - } - } - - } - - - public static synchronized ConcurrentHashMap> getWebSocketMap() { - return AppWebSocketServer.webSocketMap; - } - - public static synchronized ConcurrentHashMap> getRecordMap() { - return AppWebSocketServer.recordMap; - } -} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/socket/WebSocketConfig.java b/src/main/java/com/chaozhanggui/system/cashierservice/socket/WebSocketConfig.java deleted file mode 100644 index a66a79b..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/socket/WebSocketConfig.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.chaozhanggui.system.cashierservice.socket; - -import org.springframework.boot.web.servlet.ServletContextInitializer; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.stereotype.Component; -import org.springframework.web.socket.config.annotation.EnableWebSocket; -import org.springframework.web.socket.server.standard.ServerEndpointExporter; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; - -/** - * WebSocket配置 - */ -@Configuration -public class WebSocketConfig implements ServletContextInitializer { - - @Bean - public ServerEndpointExporter serverEndpointExporter () { - return new ServerEndpointExporter(); - } - @Override - public void onStartup(ServletContext servletContext) throws ServletException { - - } -} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/socket/WebSocketServer.java b/src/main/java/com/chaozhanggui/system/cashierservice/socket/WebSocketServer.java deleted file mode 100644 index 66b4d29..0000000 --- a/src/main/java/com/chaozhanggui/system/cashierservice/socket/WebSocketServer.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.chaozhanggui.system.cashierservice.socket; - -import org.springframework.stereotype.Component; - -import javax.websocket.*; -import javax.websocket.server.ServerEndpoint; -import java.io.IOException; -import java.util.concurrent.CopyOnWriteArraySet; -import java.util.concurrent.atomic.AtomicInteger; - - -@Component -@ServerEndpoint(value = "/ws") -public class WebSocketServer { - - //与某个客户端的连接会话,需要通过它来给客户端发送数据 - private Session session; - - private static final AtomicInteger OnlineCount = new AtomicInteger(0); - - private static CopyOnWriteArraySet SessionSet = new CopyOnWriteArraySet<>(); - - /** - * 连接建立成功调用的方法 - */ - @OnOpen - public void onOpen(Session session) { - SessionSet.add(session); - this.session = session; - int cnt = OnlineCount.incrementAndGet(); // 在线数加1 - System.out.println("有连接加入,当前连接数为:" + cnt); - } - - /** - * 连接关闭调用的方法 - */ - @OnClose - public void onClose() { - SessionSet.remove(this.session); - int cnt = OnlineCount.decrementAndGet(); - System.out.println("有连接关闭,当前连接数为:" + cnt); - } - - /** - * 收到客户端消息后调用的方法 - * @param message 客户端发送过来的消息 - */ - @OnMessage - public void onMessage(String message, Session session) { - System.out.println(message); - BroadCastInfo(message); - } - - /** - * 出现错误 - * @param error - */ - @OnError - public void onError(Throwable error) { - error.printStackTrace(); - } - - - /** - * 发送消息 - * - * @param session - * @param message - */ - public static void SendMessage(Session session, String message) { - try { - if (session.isOpen()) { - session.getBasicRemote().sendText(message); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * 群发消息 - * - * @param message - * @throws IOException - */ - public static void BroadCastInfo(String message) { - for (Session session : SessionSet) { - SendMessage(session, message); - } - } - - /** - * 指定Session发送消息 - * - * @param sessionId - * @param message - * @throws IOException - */ - public static void SendMessage(String message, String sessionId) { - Session session = null; - for (Session s : SessionSet) { - if (s.getId().equals(sessionId)) { - session = s; - break; - } - } - if (session != null) { - SendMessage(session, message); - } - } - -} - diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/task/TaskScheduler.java b/src/main/java/com/chaozhanggui/system/cashierservice/task/TaskScheduler.java new file mode 100644 index 0000000..8b4b4c0 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/task/TaskScheduler.java @@ -0,0 +1,163 @@ +package com.chaozhanggui.system.cashierservice.task; + +import com.chaozhanggui.system.cashierservice.dao.*; +import com.chaozhanggui.system.cashierservice.entity.*; +import com.chaozhanggui.system.cashierservice.util.DateUtils; +import com.chaozhanggui.system.cashierservice.util.NicknameGenerator; +import com.chaozhanggui.system.cashierservice.util.RandomUtil; +import lombok.SneakyThrows; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.text.ParseException; +import java.util.*; +import java.util.concurrent.*; + +@Component +public class TaskScheduler { + + @Autowired + private TbWiningUserMapper tbWiningUserMapper; + @Autowired + private TbOrderInfoMapper orderInfoMapper; + @Autowired + private TbWiningParamsMapper winingParamsMapper; + @Autowired + private TbUserInfoMapper userInfoMapper; + @Autowired + private TbReleaseFlowMapper releaseFlowMapper; + @Autowired + private TbUserCouponsMapper userCouponsMapper; + //更新订单状态 +// @Scheduled(fixedRate = 1000000) + public void orderStatus() throws InterruptedException { + for (int i = 0;i<10;i++){ + TbReleaseFlow releaseFlow = new TbReleaseFlow(); + BigDecimal orderAmount = RandomUtil.getRandomBigDecimal(BigDecimal.ONE, new BigDecimal("100")); + releaseFlow.setNum(orderAmount); + releaseFlow.setCreateTime(new Date()); + releaseFlow.setFromSource("OWER"); + releaseFlow.setUserId("15"); + releaseFlow.setOperationType("ADD"); + releaseFlow.setType("EXCHANGEADD"); + releaseFlow.setRemark("兑换增加"); + releaseFlowMapper.insert(releaseFlow); + } + for (int i = 0;i<10;i++){ + TbReleaseFlow releaseFlow = new TbReleaseFlow(); + BigDecimal orderAmount = RandomUtil.getRandomBigDecimal(BigDecimal.ONE, new BigDecimal("100")); + releaseFlow.setNum(orderAmount); + releaseFlow.setCreateTime(new Date()); + releaseFlow.setFromSource("OWER"); + releaseFlow.setUserId("15"); + releaseFlow.setOperationType("SUB"); + releaseFlow.setType("BUYSUB"); + releaseFlow.setRemark("购买商品扣除"); + releaseFlowMapper.insert(releaseFlow); + } + for (int i = 0;i<10;i++){ + TbReleaseFlow releaseFlow = new TbReleaseFlow(); + BigDecimal orderAmount = RandomUtil.getRandomBigDecimal(BigDecimal.ONE, new BigDecimal("100")); + releaseFlow.setNum(orderAmount); + releaseFlow.setCreateTime(new Date()); + releaseFlow.setFromSource("OWER"); + releaseFlow.setOperationType("ADD"); + releaseFlow.setUserId("15"); + releaseFlow.setType("THREEADD"); + releaseFlow.setRemark("退货增加"); + releaseFlowMapper.insert(releaseFlow); + } + } + + + @Scheduled(cron = "0 1 0 * * ?") + public void winningUser() { + String day = DateUtils.getDay(); + List list = winingParamsMapper.selectAll(); + ThreadPoolExecutor es = new ThreadPoolExecutor(5, 10, 60L, TimeUnit.SECONDS, + new LinkedBlockingQueue(), new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + Thread t = new Thread(r); + t.setDaemon(true); + return t; + } + }); + for (TbWiningParams winingParams : list) { + es.submit(new winingUser(winingParams, day)); + } + es.shutdown(); + + } + + class winingUser implements Runnable { + private TbWiningParams winingParams; + private String day; + + public winingUser(TbWiningParams winingParams, String day) { + this.winingParams = winingParams; + this.day = day; + } + + @Override + public void run() { + try { + List list = orderInfoMapper.selectByTradeDay(day, winingParams.getMinPrice(), winingParams.getMaxPrice()); + int num = winingParams.getWiningUserNum(); + List newList = new ArrayList<>(); + Map map = new HashMap<>(); + int noUserNum = winingParams.getWiningNum() - num; + if (list.size() < num) { + noUserNum = winingParams.getWiningNum(); + } else { + for (int i = 0; i < num; i++) { + TbOrderInfo orderInfo = RandomUtil.selectWinner(list, map); + newList.add(orderInfo); + map.put(orderInfo.getId(), 1); + } + } + for (int i = 0; i < noUserNum; i++) { + long endDate = DateUtils.convertDate1(day + " 00:00:00").getTime(); + long startDate = DateUtils.convertDate1(DateUtils.getSdfDayTimes(DateUtils.getNewDate(new Date(), 3, -1))+" 00:00:00").getTime(); + String orderNo = generateOrderNumber(startDate, endDate); + String userName = NicknameGenerator.generateRandomWeChatNickname(); + BigDecimal orderAmount = RandomUtil.getRandomBigDecimal(winingParams.getMinPrice(), winingParams.getMaxPrice()); + TbWiningUser winingUser = new TbWiningUser(userName, orderNo, orderAmount, "false", day); + tbWiningUserMapper.insert(winingUser); + } + for (TbOrderInfo orderInfo:newList){ + TbUserInfo userInfo = userInfoMapper.selectByPrimaryKey(Integer.valueOf(orderInfo.getUserId())); + TbWiningUser winingUser = new TbWiningUser(userInfo.getNickName(), orderInfo.getOrderNo(), orderInfo.getPayAmount(), "true", day); + tbWiningUserMapper.insert(winingUser); + TbUserCoupons userCoupons = new TbUserCoupons(); + userCoupons.setUserId(orderInfo.getUserId()); + userCoupons.setCouponsAmount(orderInfo.getOrderAmount().subtract(orderInfo.getUserCouponAmount())); + userCoupons.setStatus("0"); + userCoupons.setOrderId(orderInfo.getId()); + userCoupons.setCouponsPrice(userCoupons.getCouponsAmount().multiply(new BigDecimal("0.5"))); + userCoupons.setCreateTime(new Date()); + userCoupons.setEndTime(DateUtils.getNewDate(new Date(),3,30)); + //执行插入方法 + userCouponsMapper.insert(userCoupons); + } + } catch (ParseException e) { + e.printStackTrace(); + } + } + } + + public String generateOrderNumber(long startTimestamp, long endTimestamp) { + long date = getRandomTimestamp(startTimestamp, endTimestamp); + Random random = new Random(); + int randomNum = random.nextInt(900) + 100; + return "WX" + date + randomNum; + } + + public static long getRandomTimestamp(long startTimestamp, long endTimestamp) { + long randomMilliseconds = ThreadLocalRandom.current().nextLong(startTimestamp, endTimestamp); + return randomMilliseconds; + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/constants/SignTypeEnum.java b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/constants/SignTypeEnum.java new file mode 100644 index 0000000..142bfdf --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/constants/SignTypeEnum.java @@ -0,0 +1,16 @@ +package com.chaozhanggui.system.cashierservice.thirdpay.constants; + +public enum SignTypeEnum { + + MD5("MD5"),RSA2("RSA2"); + + private final String value; + + SignTypeEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/req/MainScanReq.java b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/req/MainScanReq.java new file mode 100644 index 0000000..502d535 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/req/MainScanReq.java @@ -0,0 +1,41 @@ +package com.chaozhanggui.system.cashierservice.thirdpay.req; + +import lombok.Data; + +import java.io.Serializable; + +@Data +public class MainScanReq implements Serializable { + + private String subject; + + private String body; + + private Long amount; + + private String subAppid; + + private String currency; + + private String authCode; + + private String mchOrderNo; + + private String storeId; + + private String notifyUrl; + + public MainScanReq(String subject, String body, Long amount, String subAppid, String currency, String authCode, String mchOrderNo, String storeId, String notifyUrl) { + this.subject = subject; + this.body = body; + this.amount = amount; + this.subAppid = subAppid; + this.currency = currency; + this.authCode = authCode; + this.mchOrderNo = mchOrderNo; + this.storeId = storeId; + this.notifyUrl = notifyUrl; + } + + +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/req/OrderRefundReq.java b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/req/OrderRefundReq.java new file mode 100644 index 0000000..9bdbbb8 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/req/OrderRefundReq.java @@ -0,0 +1,32 @@ +package com.chaozhanggui.system.cashierservice.thirdpay.req; + +import lombok.Data; + +import java.io.Serializable; +@Data +public class OrderRefundReq implements Serializable { + + private String mchRefundNo; + + private String payOrderId; + + private String mchOrderNo; + + private String refundReason; + + private Long refundAmount; + + private String notifyUrl; + + private String extParam; + + public OrderRefundReq(String mchRefundNo, String payOrderId, String mchOrderNo, String refundReason, Long refundAmount, String notifyUrl, String extParam) { + this.mchRefundNo = mchRefundNo; + this.payOrderId = payOrderId; + this.mchOrderNo = mchOrderNo; + this.refundReason = refundReason; + this.refundAmount = refundAmount; + this.notifyUrl = notifyUrl; + this.extParam = extParam; + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/req/OrderReturnQueryReq.java b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/req/OrderReturnQueryReq.java new file mode 100644 index 0000000..d39dba3 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/req/OrderReturnQueryReq.java @@ -0,0 +1,18 @@ +package com.chaozhanggui.system.cashierservice.thirdpay.req; + +import lombok.Data; + +import java.io.Serializable; + +@Data +public class OrderReturnQueryReq implements Serializable { + + private String mchRefundNo; + + private String refundOrderId; + + public OrderReturnQueryReq(String mchRefundNo, String refundOrderId) { + this.mchRefundNo = mchRefundNo; + this.refundOrderId = refundOrderId; + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/req/OrderStatusQueryReq.java b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/req/OrderStatusQueryReq.java new file mode 100644 index 0000000..c47a593 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/req/OrderStatusQueryReq.java @@ -0,0 +1,18 @@ +package com.chaozhanggui.system.cashierservice.thirdpay.req; + +import lombok.Data; + +import java.io.Serializable; + +@Data +public class OrderStatusQueryReq implements Serializable { + + private String payOrderId; + + private String mchOrderNo; + + public OrderStatusQueryReq(String payOrderId, String mchOrderNo) { + this.payOrderId = payOrderId; + this.mchOrderNo = mchOrderNo; + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/req/PublicParam.java b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/req/PublicParam.java new file mode 100644 index 0000000..855ceac --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/req/PublicParam.java @@ -0,0 +1,33 @@ +package com.chaozhanggui.system.cashierservice.thirdpay.req; + +import lombok.Data; + +import java.io.Serializable; + +@Data +public class PublicParam implements Serializable { + + private String appId; + + private String sign; + + private String signType; + + private String bizData; + + private String reqTime; + + private String version; + + private String reqId; + + public PublicParam(String appId, String sign, String signType, String bizData, String reqTime, String version, String reqId) { + this.appId = appId; + this.sign = sign; + this.signType = signType; + this.bizData = bizData; + this.reqTime = reqTime; + this.version = version; + this.reqId = reqId; + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/req/WxScanPayReq.java b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/req/WxScanPayReq.java new file mode 100644 index 0000000..0e6eab3 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/req/WxScanPayReq.java @@ -0,0 +1,49 @@ +package com.chaozhanggui.system.cashierservice.thirdpay.req; + +import lombok.Data; + +import java.io.Serializable; + +@Data +public class WxScanPayReq implements Serializable { + + private String subject; + + private String body; + + private Long amount; + + private String currency; + + private String payType; + + + private String subAppid; + + private String userId; + + private String clientIp; + + private String mchOrderNo; + + private String storeId; + + private String notifyUrl; + + private String returnUrl; + + public WxScanPayReq(String subject, String body, Long amount, String currency, String payType, String subAppid, String userId, String clientIp, String mchOrderNo, String storeId, String notifyUrl, String returnUrl) { + this.subject = subject; + this.body = body; + this.amount = amount; + this.currency = currency; + this.payType = payType; + this.subAppid = subAppid; + this.userId = userId; + this.clientIp = clientIp; + this.mchOrderNo = mchOrderNo; + this.storeId = storeId; + this.notifyUrl = notifyUrl; + this.returnUrl = returnUrl; + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/resp/MainScanResp.java b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/resp/MainScanResp.java new file mode 100644 index 0000000..46a1636 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/resp/MainScanResp.java @@ -0,0 +1,47 @@ +package com.chaozhanggui.system.cashierservice.thirdpay.resp; + +import lombok.Data; + +import java.io.Serializable; + +@Data +public class MainScanResp implements Serializable { + + private Long amount; + + private String mchOrderNo; + + private String payOrderId; + + private String mercNo; + + private String channelSendNo; + + private String channelTradeNo; + + private String state; + + private String payType; + + private String ifCode; + + private String extParam; + + private String note; + + private String tradeFee; + + private String storeId; + + private String subject; + + private String drType; + + private Long refundAmt; + + private Integer refundState; + + private Long cashFee; + + private String settlementType; +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/resp/OderReturnQueyResp.java b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/resp/OderReturnQueyResp.java new file mode 100644 index 0000000..b481b15 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/resp/OderReturnQueyResp.java @@ -0,0 +1,36 @@ +package com.chaozhanggui.system.cashierservice.thirdpay.resp; + +import lombok.Data; + +import java.io.Serializable; + +@Data +public class OderReturnQueyResp implements Serializable { + + + private String mchRefundNo; + + private String refundOrderId; + + private String state; + + private String oriPayOrderId; + + private String mercNo; + + private Long oriAmount; + + private Long refundAmt; + + private String refundReason; + + private String ifCode; + + private String note; + + private String refundTime; + + private String extParam; + + private String payType; +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/resp/OrderReturnResp.java b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/resp/OrderReturnResp.java new file mode 100644 index 0000000..1a930f8 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/resp/OrderReturnResp.java @@ -0,0 +1,33 @@ +package com.chaozhanggui.system.cashierservice.thirdpay.resp; + +import lombok.Data; + +import java.io.Serializable; + +@Data +public class OrderReturnResp implements Serializable { + + private String mchRefundNo; + + private String refundOrderId; + + private String state; + + private String oriPayOrderId; + + private String mercNo; + + private Long oriAmount; + + private Long refundAmt; + + private String refundReason; + + private String ifCode; + + private String refundTime; + + private String extParam; + + private String payType; +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/resp/OrderStatusQueryResp.java b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/resp/OrderStatusQueryResp.java new file mode 100644 index 0000000..0afc145 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/resp/OrderStatusQueryResp.java @@ -0,0 +1,49 @@ +package com.chaozhanggui.system.cashierservice.thirdpay.resp; + +import lombok.Data; + +import java.io.Serializable; + +@Data +public class OrderStatusQueryResp implements Serializable { + + private Long amount; + + private String channelSendNo; + + private String ifCode; + + private String mercNo; + + private String mchOrderNo; + + private String payOrderId; + + private String payType; + + private String channelTradeNo; + + private String state; + + private String refundAmt; + + private String refundState; + + private String drType; + + private String extParam; + + private String payTime; + + private String subject; + + private String tradeFee; + + private String cashFee; + + private String storeId; + + private String userId; + + private String settlementType; +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/resp/PublicResp.java b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/resp/PublicResp.java new file mode 100644 index 0000000..d911c21 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/resp/PublicResp.java @@ -0,0 +1,22 @@ +package com.chaozhanggui.system.cashierservice.thirdpay.resp; + +import lombok.Data; + +import java.io.Serializable; +@Data +public class PublicResp implements Serializable { + + private String code; + + private String msg; + + private String sign; + + private String bizData; + + private T objData; + + private String signType; + + private String timestamp; +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/resp/WxScanPayResp.java b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/resp/WxScanPayResp.java new file mode 100644 index 0000000..af8b012 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/resp/WxScanPayResp.java @@ -0,0 +1,51 @@ +package com.chaozhanggui.system.cashierservice.thirdpay.resp; + +import lombok.Data; + +import java.io.Serializable; + +@Data +public class WxScanPayResp implements Serializable { + + private Long amount; + + private String mchOrderNo; + + private String payOrderId; + + private String mercNo; + + private String channelSendNo; + + private String channelTradeNo; + + private String state; + + private String payType; + + private String ifCode; + + private String extParam; + + private String payInfo; + + private String liteInfo; + + private String note; + + private String tradeFee; + + private String storeId; + + private String subject; + + private String drType; + + private String refundAmt; + + private String refundState; + + private String cashFee; + + private String settlementType; +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/service/ThirdPayService.java b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/service/ThirdPayService.java new file mode 100644 index 0000000..4b1f928 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/thirdpay/service/ThirdPayService.java @@ -0,0 +1,299 @@ +package com.chaozhanggui.system.cashierservice.thirdpay.service; + +import cn.hutool.http.HttpRequest; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.chaozhanggui.system.cashierservice.thirdpay.constants.SignTypeEnum; +import com.chaozhanggui.system.cashierservice.thirdpay.req.*; +import com.chaozhanggui.system.cashierservice.thirdpay.resp.*; +import com.chaozhanggui.system.cashierservice.util.DateUtils; +import com.chaozhanggui.system.cashierservice.util.JSONUtil; +import com.chaozhanggui.system.cashierservice.util.MD5Util; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.Comparator; +import java.util.LinkedHashMap; + +@Service +@Slf4j +public class ThirdPayService { + + private static String micropay="/api/open/payment/micropay"; + + private static String ltpay="/api/open/payment/ltpay"; + + private static String trade="/api/open/query/trade"; + + /** + * 被扫接口 + * @param url + * @param appId + * @param subject + * @param body + * @param amount + * @param subAppId + * @param authCode + * @param orderNo + * @param storeId + * @param notifyUrl + * @param key + * @return + */ + public PublicResp mainScan(String url,String appId, String subject, String body, Long amount, String subAppId, String authCode, String orderNo, String storeId, String notifyUrl, + String key + ) { + + MainScanReq mainScanReq = new MainScanReq(subject, body, amount, subAppId, "cny", authCode, orderNo, storeId, notifyUrl); + PublicParam param = new PublicParam(appId, "", SignTypeEnum.MD5.getValue(), null, DateUtils.getSdfTimes(), "1.0", String.valueOf(System.currentTimeMillis())); + + + try { + String str = JSONUtil.toJSONString(sortFields(mainScanReq)); + param.setBizData(str); + String tt = sortFieldsAndPrint(param); + String MD5 = tt.concat("appSecret=" + key); + log.info("加签原传:{}", MD5); + String sign = MD5Util.encrypt(MD5); + param.setSign(sign); + String reqbody = JSONUtil.toJSONString(param); + log.info("请求参数:{}", reqbody); + String response = HttpRequest.post(url.concat(micropay)).body(reqbody).execute().body(); + log.info("返回结果:{}", response); + PublicResp resp =JSONUtil.parseJSONStr2T(response,PublicResp.class); + + resp.setObjData(JSONUtil.parseJSONStr2T(resp.getBizData(),MainScanResp.class)); + return resp; + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + + } + + + + /** + * 主扫接口(小程序) + * @param url + * @param appId + * @param subject + * @param body + * @param amount + * @param payType + * @param subAppId + * @param userId + * @param clinetIp + * @param orderNo + * @param storeId + * @param notifyUrl + * @param returnUrl + * @param key + * @return + */ + + public PublicResp scanpay(String url,String appId, String subject, String body, Long amount,String payType, String subAppId, String userId, + String clinetIp,String orderNo, String storeId, String notifyUrl,String returnUrl, + String key){ + WxScanPayReq scanPayReq=new WxScanPayReq(subject,body,amount,"cny",payType,subAppId,userId,clinetIp,orderNo,storeId,notifyUrl,returnUrl); + PublicParam param=new PublicParam(appId,null,SignTypeEnum.MD5.getValue(),null,DateUtils.getSdfTimes(), "1.0", String.valueOf(System.currentTimeMillis())); + + + try { + String str = JSONUtil.toJSONString(sortFields(scanPayReq)); + param.setBizData(str); + String tt = sortFieldsAndPrint(param); + String MD5 = tt.concat("appSecret=" + key); + log.info("加签原传:{}", MD5); + String sign = MD5Util.encrypt(MD5); + param.setSign(sign); + String reqbody = JSONUtil.toJSONString(param); + log.info("请求参数:{}", reqbody); + String response = HttpRequest.post(url.concat(ltpay)).body(reqbody).execute().body(); + log.info("返回结果:{}", response); + PublicResp resp =JSONUtil.parseJSONStr2T(response,PublicResp.class); + resp.setObjData(JSONUtil.parseJSONStr2T(resp.getBizData(),WxScanPayResp.class)); + return resp; + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + + } + + /** + * 查询订单状态 + * @param url + * @param appId + * @param payOrderId + * @param mchOrderNo + * @param key + * @return + */ + public PublicResp queryOrder(String url,String appId, String payOrderId,String mchOrderNo,String key){ + OrderStatusQueryReq req=new OrderStatusQueryReq(payOrderId,mchOrderNo); + PublicParam param=new PublicParam(appId,null,SignTypeEnum.MD5.getValue(), null,DateUtils.getSdfTimes(), "1.0", String.valueOf(System.currentTimeMillis())); + try { + String str = JSONUtil.toJSONString(sortFields(req)); + param.setBizData(str); + String tt = sortFieldsAndPrint(param); + String MD5 = tt.concat("appSecret=" + key); + log.info("加签原传:{}", MD5); + String sign = MD5Util.encrypt(MD5); + param.setSign(sign); + String reqbody = JSONUtil.toJSONString(param); + log.info("请求参数:{}", reqbody); + String response = HttpRequest.post(url.concat(trade)).body(reqbody).execute().body(); + log.info("返回结果:{}", response); + PublicResp resp =JSONUtil.parseJSONStr2T(response,PublicResp.class); + resp.setObjData(JSONUtil.parseJSONStr2T(resp.getBizData(),OrderStatusQueryResp.class)); + return resp; + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + + } + + + /** + * 退款 + * @param url + * @param appId + * @param mchRefundNo + * @param payOrderId + * @param mchOrderNo + * @param refundReason + * @param refundAmount + * @param notifyUrl + * @param extParam + * @param key + * @return + */ + public PublicResp returnOrder(String url,String appId, String mchRefundNo, String payOrderId, String mchOrderNo, String refundReason, Long refundAmount, String notifyUrl, String extParam,String key){ + OrderRefundReq req=new OrderRefundReq(mchRefundNo, payOrderId, mchOrderNo, refundReason, refundAmount, notifyUrl, extParam); + PublicParam param=new PublicParam(appId,null,SignTypeEnum.MD5.getValue(), null,DateUtils.getSdfTimes(), "1.0", String.valueOf(System.currentTimeMillis())); + try { + String str = JSONUtil.toJSONString(sortFields(req)); + param.setBizData(str); + String tt = sortFieldsAndPrint(param); + String MD5 = tt.concat("appSecret=" + key); + log.info("加签原传:{}", MD5); + String sign = MD5Util.encrypt(MD5); + param.setSign(sign); + String reqbody = JSONUtil.toJSONString(param); + log.info("请求参数:{}", reqbody); + String response = HttpRequest.post(url.concat(trade)).body(reqbody).execute().body(); + log.info("返回结果:{}", response); + PublicResp resp =JSONUtil.parseJSONStr2T(response,PublicResp.class); + resp.setObjData(JSONUtil.parseJSONStr2T(resp.getBizData(),OrderReturnResp.class)); + return resp; + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + + } + + + /** + * 查询退款订单 + * @param url + * @param appId + * @param mchRefundNo + * @param refundOrderId + * @param key + * @return + */ + public PublicResp returnOrderQuery(String url,String appId,String mchRefundNo, String refundOrderId,String key){ + OrderReturnQueryReq req=new OrderReturnQueryReq(mchRefundNo,refundOrderId); + PublicParam param=new PublicParam(appId,null,SignTypeEnum.MD5.getValue(), null,DateUtils.getSdfTimes(), "1.0", String.valueOf(System.currentTimeMillis())); + try { + String str = JSONUtil.toJSONString(sortFields(req)); + param.setBizData(str); + String tt = sortFieldsAndPrint(param); + String MD5 = tt.concat("appSecret=" + key); + log.info("加签原传:{}", MD5); + String sign = MD5Util.encrypt(MD5); + param.setSign(sign); + String reqbody = JSONUtil.toJSONString(param); + log.info("请求参数:{}", reqbody); + String response = HttpRequest.post(url.concat(trade)).body(reqbody).execute().body(); + log.info("返回结果:{}", response); + PublicResp resp =JSONUtil.parseJSONStr2T(response,PublicResp.class); + resp.setObjData(JSONUtil.parseJSONStr2T(resp.getBizData(),OrderReturnQueryReq.class)); + return resp; + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + + } + + + + + + + public static String sortFieldsAndPrint(Object obj) throws IllegalAccessException { + StringBuffer sb = new StringBuffer(); + Class clazz = obj.getClass(); + Field[] fields = clazz.getDeclaredFields(); + + // 按字段名称排序 + Arrays.sort(fields, Comparator.comparing(Field::getName)); + + for (Field field : fields) { + // 可能需要设置访问权限 + field.setAccessible(true); + if ("sign".equals(field.getName())) { + continue; + } + Object value = field.get(obj); + + + StringBuffer param = new StringBuffer(); + param.append(field.getName()); + param.append("="); + if (value instanceof String) { + param.append(value); + + } else if (value instanceof Integer) { + param.append(value); + } else if (value instanceof Long) { + param.append(value); + } + + param.append("&"); + sb.append(param); + } + return sb.toString(); + } + + + public static LinkedHashMap sortFields(Object obj) throws IllegalAccessException { + + LinkedHashMap map = new LinkedHashMap<>(); + Class clazz = obj.getClass(); + Field[] fields = clazz.getDeclaredFields(); + + // 按字段名称排序 + Arrays.sort(fields, Comparator.comparing(Field::getName)); + + for (Field field : fields) { + // 可能需要设置访问权限 + field.setAccessible(true); + Object value = field.get(obj); + if(value==null){ + continue; + } + + map.put(field.getName(), value); + } + return map; + } + + + + + public static void main(String[] args) { + new ThirdPayService().mainScan("https://paymentapi.sxczgkj.cn","6639fdc9fdf6f35856a23b3c", "测试支付", "测试支付", 1L, "wx212769170d2c6b2a", "132933158610062686", "CZ".concat(String.valueOf(System.currentTimeMillis())), "S2405103298", "https://cashierclient.sxczgkj.cn/cashierService/notify/fstmemberInCallBack", "fEu7tJgqaoPCA5QevafnSHfqHtO7rWcvhyfA0ltuab7rbpgOlab7CFCmqxMIbssUvbOnFKLdQqW5xUvhzb7FoxJNMAkIf2KDzlgDl6Diw1oBq56agSAFHhgYr3bLxXXI"); + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/util/BigDecimalUtils.java b/src/main/java/com/chaozhanggui/system/cashierservice/util/BigDecimalUtils.java new file mode 100644 index 0000000..2a92831 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/util/BigDecimalUtils.java @@ -0,0 +1,20 @@ +package com.chaozhanggui.system.cashierservice.util; + +import java.math.BigDecimal; + +public class BigDecimalUtils { + + /** + * 折扣计算 + * @param orPrice 原价 + * @param saPrice 现价 + * @return + */ + public static BigDecimal getDiscount(BigDecimal orPrice,BigDecimal saPrice){ + BigDecimal discountRate = saPrice.divide(orPrice, 2, BigDecimal.ROUND_HALF_UP); + // 将折扣率转换为百分比形式 + BigDecimal discountPercentage = discountRate.multiply(BigDecimal.TEN); + return discountPercentage; + } + +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/util/CacheMap.java b/src/main/java/com/chaozhanggui/system/cashierservice/util/CacheMap.java new file mode 100644 index 0000000..512987f --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/util/CacheMap.java @@ -0,0 +1,14 @@ +package com.chaozhanggui.system.cashierservice.util; + +import java.util.HashMap; +import java.util.Map; + +public interface CacheMap { + Map map = new HashMap(){{ + put("sign","1"); + }}; + Map notOpenMap = new HashMap(){{ + put("sign","1"); + put("openId","1"); + }}; +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/util/DateUtils.java b/src/main/java/com/chaozhanggui/system/cashierservice/util/DateUtils.java index 040b90e..809d0ff 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/util/DateUtils.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/util/DateUtils.java @@ -3,8 +3,14 @@ package com.chaozhanggui.system.cashierservice.util; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.Date; +import java.util.GregorianCalendar; /** * Created by SEELE on 2018/4/19. @@ -15,9 +21,12 @@ public class DateUtils { private final static SimpleDateFormat sdfDay = new SimpleDateFormat("yyyy-MM-dd"); private final static SimpleDateFormat sdfDays = new SimpleDateFormat("yyyyMMdd"); private final static SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + private final static SimpleDateFormat sdfTimeM = new SimpleDateFormat("yyyy-MM-dd HH:mm"); private final static SimpleDateFormat sdfTimeSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); private final static SimpleDateFormat sdfTimes = new SimpleDateFormat("yyyyMMddHHmmss"); + private final static SimpleDateFormat sdfTimesSS = new SimpleDateFormat("yyyyMMddHHmmssSSS"); + private final static SimpleDateFormat sdfday = new SimpleDateFormat("MM-dd HH:mm"); @@ -53,6 +62,12 @@ public class DateUtils { public static String getTimes(Date date){ return sdfday.format(date); } + public static String getTimeM(Date date){ + return sdfTimeM.format(date); + } + public static String getSdfDayTimes(Date date){ + return sdfDay.format(date); + } /** @@ -64,6 +79,12 @@ public class DateUtils { } + + public static String getsdfTimesSS(){ + return sdfTimesSS.format(new Date()); + } + + public static String getNextSdfTimes(Date date){ return sdfTimes.format(date); } @@ -99,7 +120,9 @@ public class DateUtils { public static String getTime() { return sdfTime.format(new Date()); } - + public static String getStrTime(Date date) { + return sdfTime.format(date); + } /** * @Title: compareDate * @Description: TODO(日期比较,如果s>=e 返回true 否则返回false) @@ -242,6 +265,58 @@ public class DateUtils { return date; } + /** + * 今天结束时间 + * @return + */ + public static Date getDayEnd() { + Calendar cal = new GregorianCalendar(); + cal.set(Calendar.HOUR_OF_DAY, 23); + cal.set(Calendar.MINUTE, 59); + cal.set(Calendar.SECOND, 59); + cal.set(Calendar.MILLISECOND, 999); + return cal.getTime(); + } + + public static Long getDayStartLong() { + // 获取今天的日期和时间(00:00:00) + LocalDateTime todayStart = LocalDateTime.now().toLocalDate().atStartOfDay(); + // 转换为UTC时间戳(毫秒) + long timestampInMillis = todayStart.toInstant(ZoneOffset.UTC).toEpochMilli(); + + return timestampInMillis; + } + + public static Long getDayEndLong() { + // 获取今天的日期和时间(00:00:00) + LocalDateTime todayStart = LocalDateTime.now().toLocalDate().atStartOfDay(); + + // 将时间设置为今天的结束时间(23:59:59.999999999) + LocalDateTime endOfDay = todayStart.plusDays(1).minusNanos(1); + + // 转换为UTC时间戳(毫秒) + long timestampInMillis = endOfDay.toInstant(ZoneOffset.UTC).toEpochMilli(); + + return timestampInMillis; + } + + public static String getTodayEndTimeAsString() { + // 获取今天的日期 + LocalDate today = LocalDate.now(); + + // 创建今天的结束时间(23:59:59.999) + LocalTime endTime = LocalTime.of(23, 59, 59, 999_000_000); + + // 组合日期和时间 + LocalDateTime todayEndTime = LocalDateTime.of(today, endTime); + + // 格式化时间 + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); + + // 转换为字符串 + return todayEndTime.format(formatter); + } + /** * 得到n天之后是周几 * @param days diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/util/JSONUtil.java b/src/main/java/com/chaozhanggui/system/cashierservice/util/JSONUtil.java index 69ff2ee..0cd2c85 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/util/JSONUtil.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/util/JSONUtil.java @@ -5,6 +5,7 @@ import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.serializer.SerializerFeature; +import com.fasterxml.jackson.databind.ObjectMapper; import java.util.*; @@ -172,6 +173,37 @@ public class JSONUtil { } } + /** + * @param list 某集合 + * @param clazz 要转成的实体 + * 需要在目标实体增加注解 忽略未知属性 @JsonIgnoreProperties(ignoreUnknown = true) + * @return + * @param + */ + public static List parseListTNewList(List list, Class clazz) { + ObjectMapper objectMapper = new ObjectMapper(); // 创建JSON转换器 + try { + // 将List转换为JSON字符串 + String json = objectMapper.writeValueAsString(list); + // 将JSON字符串转换为List + return objectMapper.readValue(json, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz)); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public static List parseListTNewList(String json, Class clazz) { + ObjectMapper objectMapper = new ObjectMapper(); // 创建JSON转换器 + try { + // 将JSON字符串转换为List + return objectMapper.readValue(json, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz)); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + public static class JSONEntity { public JSONEntity() { } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/util/LocationUtils.java b/src/main/java/com/chaozhanggui/system/cashierservice/util/LocationUtils.java index ad4ccb9..44ac565 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/util/LocationUtils.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/util/LocationUtils.java @@ -1,5 +1,13 @@ package com.chaozhanggui.system.cashierservice.util; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang3.StringUtils; +import org.springframework.web.client.RestTemplate; + +import java.math.BigDecimal; +import java.math.RoundingMode; import java.util.HashMap; import java.util.Map; @@ -7,32 +15,61 @@ import static java.lang.Math.*; import static java.lang.Math.sin; public class LocationUtils { - - public static String district(String keywords) { - Map param=new HashMap<>(); + /** + * 通过Ip获取定位信息 + * + * @param ip + * @return + */ + public static String getGPSByIp(String ip) { + Map param = new HashMap<>(); //超掌柜生活-用户端 - param.put("key","7a7f2e4790ea222660a027352ee3af39"); - param.put("keywords",keywords); - param.put("subdistrict","1"); - param.put("extensions","base"); + param.put("key", "7a7f2e4790ea222660a027352ee3af39"); + if (StringUtils.isNotBlank(ip)) { + param.put("ip", ip); + } + String s = HttpClientUtil.doGet("https://restapi.amap.com/v3/ip", param); + return s; + } + + /** + * 通过经纬度获取信息 + */ + public static JsonNode geocode(String location) { + RestTemplate restTemplate = new RestTemplate(); + String s = restTemplate.getForObject("https://restapi.amap.com/v3/geocode/regeo?key=7a7f2e4790ea222660a027352ee3af39&location=" + location, String.class); + ObjectMapper objectMapper = new ObjectMapper(); + // 将 JSON 字符串解析为 JsonNode 对象 + try { + JsonNode jsonNode = objectMapper.readTree(s).get("regeocode"); + return jsonNode; + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + } + + /** + * 行政区域查询 + * + * @param keywords + * @return + */ + public static String district(String keywords,String subdistrict) { + Map param = new HashMap<>(); + //超掌柜生活-用户端 + param.put("key", "7a7f2e4790ea222660a027352ee3af39"); + param.put("keywords", keywords); + param.put("subdistrict", "1"); + if (StringUtils.isNotBlank(subdistrict)) { + param.put("subdistrict", "2"); + } + param.put("extensions", "base"); String s = HttpClientUtil.doGet("https://restapi.amap.com/v3/config/district", param); return s; } - /** - * 将角度转化为弧度 - */ - public static double radians(double d) { - return d * Math.PI / 180.0; - } /** * 根据两点经纬度坐标计算直线距离 - *

- * S = 2arcsin√sin²(a/2)+cos(lat1)*cos(lat2)*sin²(b/2) ̄*6378.137 - *

- * 1. lng1 lat1 表示A点经纬度,lng2 lat2 表示B点经纬度;
- * 2. a=lat1 – lat2 为两点纬度之差 b=lng1 -lng2 为两点经度之差;
- * 3. 6378.137为地球赤道半径,单位为千米; * * @param lng1 点1经度 * @param lat1 点1纬度 @@ -41,9 +78,9 @@ public class LocationUtils { * @return 距离,单位千米(KM) * @see 半正矢(Haversine)公式 */ - public static double getDistanceFrom2LngLat(double lng1, double lat1, double lng2, double lat2) { + public static BigDecimal getDistanceFrom2LngLat(double lng1, double lat1, double lng2, double lat2) { //将角度转化为弧度 - double radLng1 = radians(lng1); + double radLng1 = radians(lng1);//d * Math.PI / 180.0; double radLat1 = radians(lat1); double radLng2 = radians(lng2); double radLat2 = radians(lat2); @@ -51,19 +88,83 @@ public class LocationUtils { double a = radLat1 - radLat2; double b = radLng1 - radLng2; - return 2 * asin(sqrt(sin(a / 2) * sin(a / 2) + cos(radLat1) * cos(radLat2) * sin(b / 2) * sin(b / 2))) * 6378.137; + double dis = 2 * asin(sqrt(sin(a / 2) * sin(a / 2) + cos(radLat1) * cos(radLat2) * sin(b / 2) * sin(b / 2))) * 6378.137; + BigDecimal bigDecimalValue = new BigDecimal(dis); + bigDecimalValue = bigDecimalValue.setScale(1, RoundingMode.DOWN); + return bigDecimalValue; } -// public static void main(String[] args) { -// // 示例经纬度坐标 -// double lat1 = 108.954398; -// double lon1 = 34.308687; -// -// double lat2 = 108.953555; -// double lon2 = 34.276169; -// -// // 计算距离 -// double distance = getDistanceFrom2LngLat(lat1, lon1, lat2, lon2); -// System.out.println("Distance between the two points is: " + distance + " km"); -// } + public static String getDistanceString(double lng1, double lat1, double lng2, double lat2) { + BigDecimal distance = getDistanceFrom2LngLat(lng1, lat1, lng2, lat2); + if (distance.compareTo(BigDecimal.ONE) < 0) { + return distance.multiply(new BigDecimal(1000)).setScale(0, RoundingMode.DOWN) + "m"; + } else { + return distance + "km"; + } + } + + /** + * @param longitude 经度 108 + * @param latitude 纬度 34 + * @param distanceInKm 范围(千米) + * 大于左下的经度lat,小于右上的经度lat + * 大于左下的纬度lng,小于右上的纬度lng + * return Map stringMap + * 右上顶点 double[] leftTopPoints = stringMap.get("rightTopPoint"); + * 左下点 double[] leftBottomPoints = stringMap.get("leftBottomPoint"); + */ + public static Map returnLLSquarePoint(double longitude, double latitude, String distanceInKm) { + BigDecimal distanceKm = new BigDecimal(20); + if (StringUtils.isNotBlank(distanceInKm)) { + distanceKm = new BigDecimal(distanceInKm); + } + Map squareMap = new HashMap<>(); + BigDecimal bdlongitude = new BigDecimal(longitude); + // 地球平均半径,单位:千米 + BigDecimal earthRadius = new BigDecimal("6378.137"); + // 将距离转换为弧度 + BigDecimal radialDistance = distanceKm.divide(earthRadius, 10, RoundingMode.HALF_UP); + // 计算纬度上变化对应的角度 + BigDecimal dLatitude = BigDecimal.valueOf(Math.toDegrees(2 * Math.asin(Math.sin(radialDistance.divide(BigDecimal.valueOf(2)).doubleValue()) / Math.cos(Math.toRadians(latitude))))); + // 计算经度上变化对应的角度,这里需要考虑纬度对距离的影响 + // 使用Haversine公式来估算在给定纬度上,距离对应的经度变化 + BigDecimal estimatedLongitudeDistance = getDistanceFrom2LngLat(latitude, longitude, latitude, bdlongitude.add(BigDecimal.valueOf(0.01)).doubleValue()); // 假设0.01度经度变化对应的距离 + BigDecimal dLongitude = distanceKm.divide(estimatedLongitudeDistance, 10, RoundingMode.HALF_UP).multiply(new BigDecimal("0.0192736")); // 根据比例计算经度变化 + // 正方形四个顶点的坐标 + double[] rightTopPoint = {BigDecimal.valueOf(latitude).add(dLatitude.divide(BigDecimal.valueOf(2))).doubleValue(), BigDecimal.valueOf(longitude).add(dLongitude.divide(BigDecimal.valueOf(2))).doubleValue()}; + double[] leftBottomPoint = {BigDecimal.valueOf(latitude).subtract(dLatitude.divide(BigDecimal.valueOf(2))).doubleValue(), BigDecimal.valueOf(longitude).subtract(dLongitude.divide(BigDecimal.valueOf(2))).doubleValue()}; + + squareMap.put("rightTopPoint", rightTopPoint); + squareMap.put("leftBottomPoint", leftBottomPoint); +// System.out.println("rightTop:" + rightTopPoint[0] + "======" + rightTopPoint[1]); +// System.out.println("leftBottom:" + leftBottomPoint[0] + "======" + leftBottomPoint[1]); + return squareMap; + } + + + /** + * 将角度转化为弧度 + */ + public static double radians(double d) { + return d * Math.PI / 180.0; + } + + //1KM + public static void main(String[] args) { + Map stringMap = returnLLSquarePoint(108.975418, 34.280890, "5"); + double[] leftTopPoints = stringMap.get("rightTopPoint"); + double[] leftBottomPoints = stringMap.get("leftBottomPoint"); + + double lat2 = 108.975418; + double lon2 = 34.280890; + BigDecimal distance3 = getDistanceFrom2LngLat(108.975418, 34.280890, 109.019993, 34.342849); + System.out.println(distance3); + + // 计算距离 + BigDecimal distance1 = getDistanceFrom2LngLat(leftTopPoints[1], leftTopPoints[0], lat2, lon2); + BigDecimal distance2 = getDistanceFrom2LngLat(leftBottomPoints[1], leftBottomPoints[0], lat2, lon2); + System.out.println("Distance between the two points is: " + distance1 + " km"); + System.out.println("Distance between the two points is: " + distance2 + " km"); + } +//108.88883399281181(Double), 109.06200200718818(Double), 34.22653139523867(Double), 34.335248604761325(Double) } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/util/NicknameGenerator.java b/src/main/java/com/chaozhanggui/system/cashierservice/util/NicknameGenerator.java new file mode 100644 index 0000000..f50d390 --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/util/NicknameGenerator.java @@ -0,0 +1,40 @@ +package com.chaozhanggui.system.cashierservice.util; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.chaozhanggui.system.cashierservice.entity.TbOrderInfo; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Random; + +public class NicknameGenerator { + private static final String[] FIRST_NAMES = { + "晓", "小", "云", "飞", "宝", "琳", "静", "翔", "晨", "昊", "若", "萌", "悦", "舒", "婷", "紫", "凡", "佳", "雨", "阳" + }; + + private static final String[] LAST_NAMES = { + "天", "星", "月", "琪", "雪", "梦", "婷", "晨", "宇", "瑞", "颖", "欣", "莹", "妍", "娜", "辰", "楠", "妮", "欢", "瑶" + }; + + private static final String[] WORDS = { + "烟火", "夜景", "小巷", "阳光", "雨滴", "星空", "花海", "梦境", "魔法", "飞翔", "童话", "温柔", "快乐", "微笑", "甜蜜", "浪漫", "幸福" + }; + + private static final String[] EMOJIS = { + "(^-^)", "( ̄▽ ̄)~■干杯□~( ̄▽ ̄)", "(*^▽^*)", "≧◡≦", "ヾ(≧▽≦*)o", + "(*^3^)/~☆", "(*^▽^*)", "╰( ̄▽ ̄)╮", "(o^^)o", "(づ ̄ 3 ̄)づ" + }; + + public static String generateRandomWeChatNickname() { + Random random = new Random(); + String firstName = FIRST_NAMES[random.nextInt(FIRST_NAMES.length)]; + String lastName = LAST_NAMES[random.nextInt(LAST_NAMES.length)]; + String word = WORDS[random.nextInt(WORDS.length)]; + String emoji = EMOJIS[random.nextInt(EMOJIS.length)]; + return firstName + lastName + word + emoji; + } + +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/util/PrinterUtils.java b/src/main/java/com/chaozhanggui/system/cashierservice/util/PrinterUtils.java index 66145ee..7ab595a 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/util/PrinterUtils.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/util/PrinterUtils.java @@ -89,6 +89,7 @@ public class PrinterUtils { sb.append(""+detailPO.getMerchantName()+"

"); sb.append(""+type+"【"+detailPO.getMasterId()+"】

"); + sb.append(""+detailPO.getOutNumber()+"

"); sb.append("订单号: "+detailPO.getOrderNo()+"
"); sb.append("交易时间: "+detailPO.getTradeDate()+"
"); sb.append("收银员: "+detailPO.getOperator()+"


"); @@ -96,7 +97,7 @@ public class PrinterUtils { char paddingCharacter = ' '; sb.append(""+String.format("%-15s","品名").replace(' ', paddingCharacter)+String.format("%-4s","数量").replace(' ', paddingCharacter)+String.format("%4s","小计").replace(' ', paddingCharacter)+"
"); for (OrderDetailPO.Detail detail : detailPO.getDetailList()) { - if(detail.getProductName().length()>4){ + if(detail.getProductName().length()>4&&detail.getProductName().length()<=10){ int count=getProducrName(detail.getProductName()); if(count<=0){ @@ -107,6 +108,11 @@ public class PrinterUtils { sb.append(""+String.format("%-"+length+"s",detail.getProductName()).replace(' ', paddingCharacter)+String.format("%-4s",detail.getNumber()).replace(' ', paddingCharacter)+String.format("%8s",detail.getAmount()).replace(' ', paddingCharacter)+"
"); } + }else if(detail.getProductName().length()>10){ + + sb.append(""+detail.getProductName()+"
"); + sb.append(""+String.format("%20s",detail.getNumber()).replace(' ', paddingCharacter)+String.format("%11s",detail.getAmount()).replace(' ', paddingCharacter)+"
"); + }else { sb.append(""+String.format("%-15s",detail.getProductName()).replace(' ', paddingCharacter)+String.format("%-4s",detail.getNumber()).replace(' ', paddingCharacter)+String.format("%8s",detail.getAmount()).replace(' ', paddingCharacter)+"
"); } @@ -131,6 +137,10 @@ public class PrinterUtils { sb.append("余额:"+detailPO.getBalance()+"
"); sb.append("------------------------
"); + if(Objects.nonNull(detailPO.getOutNumber())){ + sb.append("".concat(detailPO.getOutNumber()).concat("
")); + } + sb.append("打印时间:"+DateUtils.getTime(new Date())+"
"); sb.append(""); diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/util/QrCodeUtils.java b/src/main/java/com/chaozhanggui/system/cashierservice/util/QrCodeUtils.java new file mode 100644 index 0000000..c88cbda --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/util/QrCodeUtils.java @@ -0,0 +1,115 @@ +package com.chaozhanggui.system.cashierservice.util; + +import com.google.zxing.BarcodeFormat; +import com.google.zxing.EncodeHintType; +import com.google.zxing.MultiFormatWriter; +import com.google.zxing.WriterException; +import com.google.zxing.common.BitMatrix; +import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; +import org.apache.commons.lang3.StringUtils; + +import javax.imageio.ImageIO; +import javax.swing.filechooser.FileSystemView; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.OutputStream; +import java.util.HashMap; +import java.util.Map; + +/** + * 二维码工具类 + * + * @author GYJ + */ +public class QrCodeUtils { + + //CODE_WIDTH:二维码宽度,单位像素 + private static final int CODE_WIDTH = 400; + //CODE_HEIGHT:二维码高度,单位像素 + private static final int CODE_HEIGHT = 400; + //FRONT_COLOR:二维码前景色,0x000000 表示黑色 + private static final int FRONT_COLOR = 0x000000; + //BACKGROUND_COLOR:二维码背景色,0xFFFFFF 表示白色 + //演示用 16 进制表示,和前端页面 CSS 的取色是一样的,注意前后景颜色应该对比明显,如常见的黑白 + private static final int BACKGROUND_COLOR = 0xFFFFFF; + + public static void createCodeToFile(String content, File codeImgFileSaveDir, String fileName) { + try { + if (StringUtils.isBlank(content) || StringUtils.isBlank(fileName)) { + return; + } + content = content.trim(); + if (codeImgFileSaveDir==null || codeImgFileSaveDir.isFile()) { + //二维码图片存在目录为空,默认放在桌面... + codeImgFileSaveDir = FileSystemView.getFileSystemView().getHomeDirectory(); + } + if (!codeImgFileSaveDir.exists()) { + //二维码图片存在目录不存在,开始创建... + codeImgFileSaveDir.mkdirs(); + } + + //核心代码-生成二维码 + BufferedImage bufferedImage = getBufferedImage(content); + + File codeImgFile = new File(codeImgFileSaveDir, fileName); + ImageIO.write(bufferedImage, "png", codeImgFile); + + System.out.println("二维码图片生成成功:" + codeImgFile.getPath()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 生成二维码并输出到输出流, 通常用于输出到网页上进行显示,输出到网页与输出到磁盘上的文件中,区别在于最后一句 ImageIO.write + * write(RenderedImage im,String formatName,File output):写到文件中 + * write(RenderedImage im,String formatName,OutputStream output):输出到输出流中 + * @param content :二维码内容 + * @param outputStream :输出流,比如 HttpServletResponse 的 getOutputStream + */ + public static void createCodeToOutputStream(String content, OutputStream outputStream) { + try { + if (StringUtils.isBlank(content)) { + return; + } + content = content.trim(); + //核心代码-生成二维码 + BufferedImage bufferedImage = getBufferedImage(content); + + //区别就是这一句,输出到输出流中,如果第三个参数是 File,则输出到文件中 + ImageIO.write(bufferedImage, "png", outputStream); + + System.out.println("二维码图片生成到输出流成功..."); + } catch (Exception e) { + e.printStackTrace(); + } + } + + //核心代码-生成二维码 + private static BufferedImage getBufferedImage(String content) throws WriterException { + + //com.google.zxing.EncodeHintType:编码提示类型,枚举类型 + Map hints = new HashMap(); + + //EncodeHintType.CHARACTER_SET:设置字符编码类型 + hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); + + //EncodeHintType.ERROR_CORRECTION:设置误差校正 + //ErrorCorrectionLevel:误差校正等级,L = ~7% correction、M = ~15% correction、Q = ~25% correction、H = ~30% correction + //不设置时,默认为 L 等级,等级不一样,生成的图案不同,但扫描的结果是一样的 + hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); + + //EncodeHintType.MARGIN:设置二维码边距,单位像素,值越小,二维码距离四周越近 + hints.put(EncodeHintType.MARGIN, 1); + + MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); + BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, CODE_WIDTH, CODE_HEIGHT, hints); + BufferedImage bufferedImage = new BufferedImage(CODE_WIDTH, CODE_HEIGHT, BufferedImage.TYPE_INT_BGR); + for (int x = 0; x < CODE_WIDTH; x++) { + for (int y = 0; y < CODE_HEIGHT; y++) { + bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? FRONT_COLOR : BACKGROUND_COLOR); + } + } + return bufferedImage; + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/util/RandomUtil.java b/src/main/java/com/chaozhanggui/system/cashierservice/util/RandomUtil.java new file mode 100644 index 0000000..6557edf --- /dev/null +++ b/src/main/java/com/chaozhanggui/system/cashierservice/util/RandomUtil.java @@ -0,0 +1,62 @@ +package com.chaozhanggui.system.cashierservice.util; + +import com.chaozhanggui.system.cashierservice.entity.TbOrderInfo; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.List; +import java.util.Map; +import java.util.Random; + +/** + * @author lyf + */ +public class RandomUtil { + //获取BigDeciaml随机数 + public static BigDecimal getRandomBigDecimal(BigDecimal minAmount, BigDecimal maxAmount) { + BigDecimal randomBigDecimal = maxAmount.subtract(minAmount).multiply(new BigDecimal(Math.random())).add(minAmount); + return randomBigDecimal.setScale(2, RoundingMode.HALF_UP); // 设置保留两位小数并四舍五入 + } + //获取中奖随机数 + public static TbOrderInfo selectWinner(List list, Map map) { + if (list == null || list.isEmpty()) { + return null; // 如果用户列表为空,则返回null + } + + Random random = new Random(); + int randomIndex = random.nextInt(list.size()); // 生成一个随机的索引值 + TbOrderInfo orderInfo = list.get(randomIndex); + if (map.containsKey(orderInfo.getId())) { + return selectWinner(list, map); + } + return list.get(randomIndex); // 返回对应索引的用户 + } + + public static BigDecimal randomDecimalGenerator(){ + + double number = generateRandomInt(2, 40); + BigDecimal bdNumber = BigDecimal.valueOf(number); + BigDecimal bdMultiplier = BigDecimal.valueOf(5); + + BigDecimal result = bdNumber.setScale(1, RoundingMode.HALF_UP); + BigDecimal multiply = result.multiply(bdMultiplier); + return multiply; + } + private static double generateRandomInt(double min, double max) { + Random random = new Random(); + return min + (max-min) * random.nextDouble(); + } + public static void main(String[] args) { + for (int i = 0; i < 20; i++) { + System.out.println("随机数为"+randomDecimalGenerator()); + } + } + + public static Integer randomInt() { + Random random = new Random(); + + // 生成1到27之间的随机整数(包括1和27) + + return random.nextInt(46) + 1; + } +} diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/util/RedisUtils.java b/src/main/java/com/chaozhanggui/system/cashierservice/util/RedisUtils.java index 21a5920..21d2563 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/util/RedisUtils.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/util/RedisUtils.java @@ -1,163 +1,48 @@ package com.chaozhanggui.system.cashierservice.util; -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Configurable; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.redis.connection.RedisConnection; -import org.springframework.data.redis.connection.RedisConnectionFactory; -import org.springframework.data.redis.core.*; -import org.springframework.data.redis.core.script.DefaultRedisScript; -import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; -import org.springframework.data.redis.serializer.RedisSerializer; -import org.springframework.data.redis.serializer.StringRedisSerializer; +import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; -import javax.annotation.PostConstruct; -import javax.annotation.Resource; import java.util.*; import java.util.concurrent.TimeUnit; -/** - * @author / - */ @Component -@SuppressWarnings({"unchecked", "all"}) public class RedisUtils { - private static final Logger log = LoggerFactory.getLogger(RedisUtils.class); - @Resource - private RedisTemplate redisTemplate; - @Value("${jwt.online-key}") - private String onlineKey; + + @Autowired + private RedisTemplate redisTemplate; + /** * 指定缓存失效时间 * * @param key 键 * @param time 时间(秒) + * @return */ public boolean expire(String key, long time) { try { if (time > 0) { redisTemplate.expire(key, time, TimeUnit.SECONDS); } + return true; } catch (Exception e) { - log.error(e.getMessage(), e); + e.printStackTrace(); return false; } - return true; } /** - * 指定缓存失效时间 - * - * @param key 键 - * @param time 时间(秒) - * @param timeUnit 单位 - */ - public boolean expire(String key, long time, TimeUnit timeUnit) { - try { - if (time > 0) { - redisTemplate.expire(key, time, timeUnit); - } - } catch (Exception e) { - log.error(e.getMessage(), e); - return false; - } - return true; - } - - /** - * 根据 key 获取过期时间 + * 根据key 获取过期时间 * * @param key 键 不能为null * @return 时间(秒) 返回0代表为永久有效 */ - public long getExpire(Object key) { + public long getExpire(String key) { return redisTemplate.getExpire(key, TimeUnit.SECONDS); } - /** - * 查找匹配key - * - * @param pattern key - * @return / - */ - public List scan(String pattern) { - ScanOptions options = ScanOptions.scanOptions().match(pattern).build(); - RedisConnectionFactory factory = redisTemplate.getConnectionFactory(); - RedisConnection rc = Objects.requireNonNull(factory).getConnection(); - Cursor cursor = rc.scan(options); - List result = new ArrayList<>(); - while (cursor.hasNext()) { - result.add(new String(cursor.next())); - } - try { - RedisConnectionUtils.releaseConnection(rc, factory); - } catch (Exception e) { - log.error(e.getMessage(), e); - } - return result; - } - - /** - * 分页查询 key - * - * @param patternKey key - * @param page 页码 - * @param size 每页数目 - * @return / - */ - public List findKeysForPage(String patternKey, int page, int size) { - ScanOptions options = ScanOptions.scanOptions().match(patternKey).build(); - RedisConnectionFactory factory = redisTemplate.getConnectionFactory(); - RedisConnection rc = Objects.requireNonNull(factory).getConnection(); - Cursor cursor = rc.scan(options); - List result = new ArrayList<>(size); - int tmpIndex = 0; - int fromIndex = page * size; - int toIndex = page * size + size; - while (cursor.hasNext()) { - if (tmpIndex >= fromIndex && tmpIndex < toIndex) { - result.add(new String(cursor.next())); - tmpIndex++; - continue; - } - // 获取到满足条件的数据后,就可以退出了 - if (tmpIndex >= toIndex) { - break; - } - tmpIndex++; - cursor.next(); - } - try { - RedisConnectionUtils.releaseConnection(rc, factory); - } catch (Exception e) { - log.error(e.getMessage(), e); - } - return result; - } - /** * 判断key是否存在 * @@ -168,7 +53,7 @@ public class RedisUtils { try { return redisTemplate.hasKey(key); } catch (Exception e) { - log.error(e.getMessage(), e); + e.printStackTrace(); return false; } } @@ -178,23 +63,13 @@ public class RedisUtils { * * @param key 可以传一个值 或多个 */ - public void del(String... keys) { - if (keys != null && keys.length > 0) { - if (keys.length == 1) { - boolean result = redisTemplate.delete(keys[0]); - log.debug("--------------------------------------------"); - log.debug(new StringBuilder("删除缓存:").append(keys[0]).append(",结果:").append(result).toString()); - log.debug("--------------------------------------------"); + @SuppressWarnings("unchecked") + public void del(String... key) { + if (key != null && key.length > 0) { + if (key.length == 1) { + redisTemplate.delete(key[0]); } else { - Set keySet = new HashSet<>(); - for (String key : keys) { - keySet.addAll(redisTemplate.keys(key)); - } - long count = redisTemplate.delete(keySet); - log.debug("--------------------------------------------"); - log.debug("成功删除缓存:" + keySet.toString()); - log.debug("缓存删除数量:" + count + "个"); - log.debug("--------------------------------------------"); + redisTemplate.delete((Collection) CollectionUtils.arrayToList(key)); } } } @@ -211,19 +86,6 @@ public class RedisUtils { return key == null ? null : redisTemplate.opsForValue().get(key); } - /** - * 批量获取 - * - * @param keys - * @return - */ - public List multiGet(List keys) { - List list = redisTemplate.opsForValue().multiGet(Sets.newHashSet(keys)); - List resultList = Lists.newArrayList(); - Optional.ofNullable(list).ifPresent(e-> list.forEach(ele-> Optional.ofNullable(ele).ifPresent(resultList::add))); - return resultList; - } - /** * 普通缓存放入 * @@ -236,9 +98,10 @@ public class RedisUtils { redisTemplate.opsForValue().set(key, value); return true; } catch (Exception e) { - log.error(e.getMessage(), e); + e.printStackTrace(); return false; } + } /** @@ -258,55 +121,37 @@ public class RedisUtils { } return true; } catch (Exception e) { - log.error(e.getMessage(), e); + e.printStackTrace(); return false; } } - @Resource - private StringRedisTemplate stringRedisTemplate; + /** - * 普通缓存放入并设置时间(重写) + * 递增 * - * @param key 键 - * @param value 值 - * @param time 时间 - * @param timeUnit 类型 - * @return true成功 false 失败 + * @param key 键 + * @param by 要增加几(大于0) + * @return */ - public boolean setextend(String key, Object value, long time) { - try { - if (time > 0) { - stringRedisTemplate.opsForValue().set(key, value.toString(), time); - } else { - set(key, value); - } - return true; - } catch (Exception e) { - log.error(e.getMessage(), e); - return false; + public long incr(String key, long delta) { + if (delta < 0) { + throw new RuntimeException("递增因子必须大于0"); } + return redisTemplate.opsForValue().increment(key, delta); } + /** - * 普通缓存放入并设置时间 + * 递减 * - * @param key 键 - * @param value 值 - * @param time 时间 - * @param timeUnit 类型 - * @return true成功 false 失败 + * @param key 键 + * @param by 要减少几(小于0) + * @return */ - public boolean set(String key, String value, long time, TimeUnit timeUnit) { - try { - if (time > 0) { - stringRedisTemplate.opsForValue().set(key, value, time, timeUnit); - } else { - set(key, value); - } - return true; - } catch (Exception e) { - log.error(e.getMessage(), e); - return false; + public long decr(String key, long delta) { + if (delta < 0) { + throw new RuntimeException("递减因子必须大于0"); } + return redisTemplate.opsForValue().increment(key, -delta); } // ================================Map================================= @@ -330,7 +175,6 @@ public class RedisUtils { */ public Map hmget(String key) { return redisTemplate.opsForHash().entries(key); - } /** @@ -345,7 +189,7 @@ public class RedisUtils { redisTemplate.opsForHash().putAll(key, map); return true; } catch (Exception e) { - log.error(e.getMessage(), e); + e.printStackTrace(); return false; } } @@ -366,7 +210,7 @@ public class RedisUtils { } return true; } catch (Exception e) { - log.error(e.getMessage(), e); + e.printStackTrace(); return false; } } @@ -384,7 +228,7 @@ public class RedisUtils { redisTemplate.opsForHash().put(key, item, value); return true; } catch (Exception e) { - log.error(e.getMessage(), e); + e.printStackTrace(); return false; } } @@ -406,7 +250,7 @@ public class RedisUtils { } return true; } catch (Exception e) { - log.error(e.getMessage(), e); + e.printStackTrace(); return false; } } @@ -468,7 +312,7 @@ public class RedisUtils { try { return redisTemplate.opsForSet().members(key); } catch (Exception e) { - log.error(e.getMessage(), e); + e.printStackTrace(); return null; } } @@ -484,7 +328,7 @@ public class RedisUtils { try { return redisTemplate.opsForSet().isMember(key, value); } catch (Exception e) { - log.error(e.getMessage(), e); + e.printStackTrace(); return false; } } @@ -500,7 +344,7 @@ public class RedisUtils { try { return redisTemplate.opsForSet().add(key, values); } catch (Exception e) { - log.error(e.getMessage(), e); + e.printStackTrace(); return 0; } } @@ -521,7 +365,7 @@ public class RedisUtils { } return count; } catch (Exception e) { - log.error(e.getMessage(), e); + e.printStackTrace(); return 0; } } @@ -536,7 +380,7 @@ public class RedisUtils { try { return redisTemplate.opsForSet().size(key); } catch (Exception e) { - log.error(e.getMessage(), e); + e.printStackTrace(); return 0; } } @@ -553,11 +397,10 @@ public class RedisUtils { Long count = redisTemplate.opsForSet().remove(key, values); return count; } catch (Exception e) { - log.error(e.getMessage(), e); + e.printStackTrace(); return 0; } } - // ===============================list================================= /** @@ -572,7 +415,7 @@ public class RedisUtils { try { return redisTemplate.opsForList().range(key, start, end); } catch (Exception e) { - log.error(e.getMessage(), e); + e.printStackTrace(); return null; } } @@ -587,7 +430,7 @@ public class RedisUtils { try { return redisTemplate.opsForList().size(key); } catch (Exception e) { - log.error(e.getMessage(), e); + e.printStackTrace(); return 0; } } @@ -603,7 +446,7 @@ public class RedisUtils { try { return redisTemplate.opsForList().index(key, index); } catch (Exception e) { - log.error(e.getMessage(), e); + e.printStackTrace(); return null; } } @@ -613,6 +456,7 @@ public class RedisUtils { * * @param key 键 * @param value 值 + * @param time 时间(秒) * @return */ public boolean lSet(String key, Object value) { @@ -620,7 +464,7 @@ public class RedisUtils { redisTemplate.opsForList().rightPush(key, value); return true; } catch (Exception e) { - log.error(e.getMessage(), e); + e.printStackTrace(); return false; } } @@ -641,7 +485,7 @@ public class RedisUtils { } return true; } catch (Exception e) { - log.error(e.getMessage(), e); + e.printStackTrace(); return false; } } @@ -651,6 +495,7 @@ public class RedisUtils { * * @param key 键 * @param value 值 + * @param time 时间(秒) * @return */ public boolean lSet(String key, List value) { @@ -658,7 +503,7 @@ public class RedisUtils { redisTemplate.opsForList().rightPushAll(key, value); return true; } catch (Exception e) { - log.error(e.getMessage(), e); + e.printStackTrace(); return false; } } @@ -679,7 +524,7 @@ public class RedisUtils { } return true; } catch (Exception e) { - log.error(e.getMessage(), e); + e.printStackTrace(); return false; } } @@ -690,14 +535,14 @@ public class RedisUtils { * @param key 键 * @param index 索引 * @param value 值 - * @return / + * @return */ public boolean lUpdateIndex(String key, long index, Object value) { try { redisTemplate.opsForList().set(key, index, value); return true; } catch (Exception e) { - log.error(e.getMessage(), e); + e.printStackTrace(); return false; } } @@ -712,74 +557,38 @@ public class RedisUtils { */ public long lRemove(String key, long count, Object value) { try { - return redisTemplate.opsForList().remove(key, count, value); + Long remove = redisTemplate.opsForList().remove(key, count, value); + return remove; } catch (Exception e) { - log.error(e.getMessage(), e); + e.printStackTrace(); return 0; } } /** - * @param prefix 前缀 - * @param ids id - */ - public void delByKeys(String prefix, Set ids) { - Set keys = new HashSet<>(); - for (Long id : ids) { - keys.addAll(redisTemplate.keys(new StringBuffer(prefix).append(id).toString())); + * @Description 上锁并设置过期时间 + * @Date 15:09 2023/7/7 + * @Param [key, value, time] + * @return boolean + **/ + public boolean setIfAbsent(String key, Object value, long time) { + try { + return redisTemplate.opsForValue().setIfAbsent(key, value, time, TimeUnit.SECONDS); + } catch (Exception e) { + e.printStackTrace(); + return false; } - long count = redisTemplate.delete(keys); - // 此处提示可自行删除 - log.debug("--------------------------------------------"); - log.debug("成功删除缓存:" + keys.toString()); - log.debug("缓存删除数量:" + count + "个"); - log.debug("--------------------------------------------"); } - String secKillScript = "local userid=KEYS[1];\r\n" + - "local prodid=KEYS[2];\r\n" + - "local qtkey=prodid;\r\n" + - "local usernum=KEYS[3];\r\n" + - "local usersKey='sk:'..prodid..\":usr\";\r\n" + - "local num= redis.call(\"get\" ,qtkey);\r\n" + - "if tonumber(num) redisScript = new DefaultRedisScript<>(); - redisScript.setResultType(Long.class);//返回类型是Long - redisScript.setScriptText(secKillScript); - Object execute = redisTemplate.execute(redisScript, Arrays.asList(uid, key,num), prodid); - String reString = String.valueOf(execute); - return reString; - } - String secAddScript = "local prodid=KEYS[1];\r\n" + - "local usernum=KEYS[2];\r\n" + - "local num= redis.call(\"get\" ,prodid);\r\n" + - " redis.call(\"SET\",prodid,tonumber(usernum)+tonumber(num));\r\n" + - "return 1"; - public String secAdd(String key,String num) { - DefaultRedisScript redisScript = new DefaultRedisScript<>(); - redisScript.setResultType(Long.class);//返回类型是Long - redisScript.setScriptText(secKillScript); - Object execute = redisTemplate.execute(redisScript, Arrays.asList(key,num)); - String reString = String.valueOf(execute); - return reString; - - } public boolean lock(String key, long timeout, TimeUnit timeUnit) { String value = UUID.randomUUID().toString(); Boolean success = redisTemplate.opsForValue().setIfAbsent(key, value, timeout, timeUnit); return success != null && success; } + public void releaseLock(String key) { redisTemplate.delete(key); } -} + +} \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/util/RsaUtil.java b/src/main/java/com/chaozhanggui/system/cashierservice/util/RsaUtil.java index 333fccf..27a2058 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/util/RsaUtil.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/util/RsaUtil.java @@ -1,4 +1,4 @@ -package me.zhengjie.utils; +package com.chaozhanggui.system.cashierservice.util; import org.apache.commons.codec.binary.Base64; import javax.crypto.Cipher; diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/util/StringUtil.java b/src/main/java/com/chaozhanggui/system/cashierservice/util/StringUtil.java index 922be6c..f54a858 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/util/StringUtil.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/util/StringUtil.java @@ -61,4 +61,26 @@ public class StringUtil { return result; } + private static final String CHINESE_CHARS = "你我他她它们这里那里多少是否好坏快慢上下左右前后高低大小长短方圆胖瘦黑白红绿蓝黄紫粉红桔红橙黄棕灰褐"; + + // 生成随机中文昵称 + public static String generateRandomNickname(int length) { + StringBuilder sb = new StringBuilder(); + Random random = new Random(); + for (int i = 0; i < length; i++) { + int index = random.nextInt(CHINESE_CHARS.length()); + char randomChar = CHINESE_CHARS.charAt(index); + sb.append(randomChar); + } + return desensitizeNickname(sb.toString()); + } + + // 对昵称进行脱敏处理 + public static String desensitizeNickname(String nickname) { + if (nickname == null || nickname.length() != 5) { + return nickname; + } + return nickname.charAt(0) + "***" + nickname.charAt(4); + } + } 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 86404fa..02007bc 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/util/TokenUtil.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/util/TokenUtil.java @@ -1,15 +1,12 @@ package com.chaozhanggui.system.cashierservice.util; -import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.ObjectUtil; import com.alibaba.fastjson.JSONObject; import io.jsonwebtoken.Claims; -import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; +import lombok.extern.slf4j.Slf4j; -import java.text.SimpleDateFormat; -import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; @@ -18,50 +15,42 @@ import java.util.Map; * @author admin * @date 2020/8/6 13:04 */ +@Slf4j public class TokenUtil { /** * 设置过期时间 */ - public static final long EXPIRE_DATE=24*60*60*1000*365; + public static final long EXPIRE_DATE=24L*60*60*1000*365; /** * token秘钥 */ private static final String TOKEN_SECRET = "BBDFSDFHFGHSGSRTRESDFSDFS"; - private JwtBuilder jwtBuilder; - - public static final String AUTHORITIES_KEY = "user"; - /** * 初始化生成token的参数 * @param userId * @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)){ claims.put("openId",openId); } - if(ObjectUtil.isNotEmpty(phone)){ claims.put("phone",phone); } - if(ObjectUtil.isNotEmpty(userName)){ claims.put("userName",userName); } - - - return generateToken(claims); } public static String generateJfToken(String openId,String userSign) throws Exception { Map claims = new HashMap<>(1); - claims.put("openId",openId); - claims.put("userSign",userSign); + claims.put("openId",openId); + claims.put("userSign",userSign); @@ -72,7 +61,7 @@ public class TokenUtil { * @param claims * @return String */ - private static String generateToken(Map claims) throws Exception { + private static String generateToken(Map claims) { return Jwts.builder() .setClaims(claims) .setExpiration(new Date(System.currentTimeMillis()+EXPIRE_DATE)) @@ -115,20 +104,27 @@ public class TokenUtil { * @return 用户Id */ public static JSONObject parseParamFromToken(final String token) { - Claims claims = Jwts.parser() - .setSigningKey(TOKEN_SECRET) - .parseClaimsJws(token) - .getBody(); - JSONObject jsonObject = (JSONObject) JSONObject.toJSON(claims); + JSONObject jsonObject=new JSONObject(); + try{ + Claims claims = Jwts.parser() + .setSigningKey(TOKEN_SECRET) + .parseClaimsJws(token) + .getBody(); + jsonObject = (JSONObject) JSONObject.toJSON(claims); + }catch (Exception e){ + jsonObject.put("status","-4"); + jsonObject.put("message","token解析失败了"); + log.info("token解析失败token为:{} Exception:{}",token,e.getMessage()); + } return jsonObject; } - public static void main(String[] args){ - System.out.println(refreshToken("eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE1OTY4Nzc5MjEsInN1YiI6ImRkZGRkIiwiaWF0IjoxNTk2Njk3OTIxfQ.lrg3KF9h9izbmyD2q5onqnZIKBqanWy9xCcroFpjxPKmJz6kz27G9lVlFpVanrL1I4SFf3Dz3q3Xu01DX2T_dw")); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - Calendar cld = Calendar.getInstance(); - cld.setTime(new Date()); - cld.set(Calendar.DATE, cld.get(Calendar.DATE)-1); - System.out.println(sdf.format(cld.getTime())); - } +// public static void main(String[] args) throws Exception { +// System.out.println(refreshToken("eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE1OTY4Nzc5MjEsInN1YiI6ImRkZGRkIiwiaWF0IjoxNTk2Njk3OTIxfQ.lrg3KF9h9izbmyD2q5onqnZIKBqanWy9xCcroFpjxPKmJz6kz27G9lVlFpVanrL1I4SFf3Dz3q3Xu01DX2T_dw")); +// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); +// Calendar cld = Calendar.getInstance(); +// cld.setTime(new Date()); +// cld.set(Calendar.DATE, cld.get(Calendar.DATE)-1); +// System.out.println(sdf.format(cld.getTime())); +// } } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/util/ValidateCodeUtil.java b/src/main/java/com/chaozhanggui/system/cashierservice/util/ValidateCodeUtil.java index 75189f0..d1b2527 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/util/ValidateCodeUtil.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/util/ValidateCodeUtil.java @@ -1,8 +1,5 @@ package com.chaozhanggui.system.cashierservice.util; -import cn.hutool.core.date.DateUtil; -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; import com.aliyun.dysmsapi20170525.Client; import com.aliyun.teaopenapi.models.Config; import com.chaozhanggui.system.cashierservice.sign.Result; @@ -10,11 +7,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.awt.image.BufferedImage; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; import static com.chaozhanggui.system.cashierservice.sign.CodeEnum.SUCCESS; diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml index 5cf8b4d..9d7ee4d 100644 --- a/src/main/resources/application-dev.yml +++ b/src/main/resources/application-dev.yml @@ -1,8 +1,11 @@ spring: datasource: - url: jdbc:mysql://121.40.128.145:3306/fycashier?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useJDBCCompliantTimezoneShift=true&serverTimezone=Asia/Shanghai&useSSL=false - username: root - password: mysqlroot@123 +# url: jdbc:mysql://121.40.128.145:3306/fycashier?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useJDBCCompliantTimezoneShift=true&serverTimezone=Asia/Shanghai&useSSL=false +# username: root +# password: mysqlroot@123 + url: jdbc:mysql://101.37.12.135:3306/fycashier?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useJDBCCompliantTimezoneShift=true&serverTimezone=Asia/Shanghai&useSSL=false&allowMultiQueries=true + username: fycashier + password: Twc6MrzzjBiWSsjh driver-class-name: com.mysql.cj.jdbc.Driver initialSize: 5 minIdle: 5 @@ -13,7 +16,7 @@ spring: com.chaozhanggui.system.openness: info redis: # redis数据库索引(默认为0),我们使用索引为3的数据库,避免和其他数据库冲突 - database: 5 + database: 0 # redis服务器地址(默认为localhost) host: 101.37.12.135 # redis端口(默认为6379) @@ -52,8 +55,16 @@ mybatis: ysk: url: https://gatewaytestapi.sxczgkj.cn/gate-service/ callBackurl: https://p40312246f.goho.co/cashierService/notify/notifyCallBack + callBackGroupurl: https://wxcashiertest.sxczgkj.cn/cashierService/notify/notifyCallBackGroup callBackIn: https://p40312246f.goho.co/cashierService/notify/memberInCallBack default: 18710449883 +thirdPay: + callInBack: https://wxcashiertest.sxczgkj.cn/cashierService/notify/fstmemberInCallBack + callFSTBack: https://wxcashiertest.sxczgkj.cn/cashierService/notify/notifyfstCallBack +server: + port: 9888 +prod: dev1 +queue: cart_queue_putdev1 diff --git a/src/main/resources/application-dev2.yml b/src/main/resources/application-dev2.yml new file mode 100644 index 0000000..73b6469 --- /dev/null +++ b/src/main/resources/application-dev2.yml @@ -0,0 +1,67 @@ +spring: + datasource: + url: jdbc:mysql://121.40.128.145:3306/fycashier?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useJDBCCompliantTimezoneShift=true&serverTimezone=Asia/Shanghai&useSSL=false + username: root + password: mysqlroot@123 + driver-class-name: com.mysql.cj.jdbc.Driver + initialSize: 5 + minIdle: 5 + maxActive: 20 + maxWait: 60000 + logging: + level: + com.chaozhanggui.system.openness: info + redis: + # redis数据库索引(默认为0),我们使用索引为3的数据库,避免和其他数据库冲突 + database: 0 + # redis服务器地址(默认为localhost) + host: 101.37.12.135 + # redis端口(默认为6379) + port: 6379 + # redis访问密码(默认为空) + password: 111111 + # redis连接超时时间(单位为毫秒) + timeout: 1000 + block-when-exhausted: true + # redis连接池配置 + jedis: + pool: + max-active: 8 + max-idle: 1024 + min-idle: 0 + max-wait: -1 + main: + allow-circular-references: true + rabbitmq: + host: 101.37.12.135 + port: 5672 + username: admin + password: Czg666888 +#分页配置 +pagehelper: + supportMethodsArguments: true + reasonable: true + helperDialect: mysql + params: count=countSql + +mybatis: + configuration: + map-underscore-to-camel-case: true + log-impl: org.apache.ibatis.logging.stdout.StdOutImpl + mapper-locations: classpath:mapper/*.xml +ysk: + url: https://gatewaytestapi.sxczgkj.cn/gate-service/ + callBackurl: https://p40312246f.goho.co/cashierService/notify/notifyCallBack + callBackGroupurl: https://wxcashiertest.sxczgkj.cn/cashierService/notify/notifyCallBackGroup + callBackIn: https://p40312246f.goho.co/cashierService/notify/memberInCallBack + default: 18710449883 +thirdPay: + callInBack: https://wxcashiertest.sxczgkj.cn/cashierService/notify/fstmemberInCallBack + callFSTBack: https://wxcashiertest.sxczgkj.cn/cashierService/notify/notifyfstCallBack +server: + port: 9889 +prod: devyhq +queue: cart_queue_putdevyhq + + + diff --git a/src/main/resources/application-hph.yml b/src/main/resources/application-hph.yml index 6861969..4eb52e5 100644 --- a/src/main/resources/application-hph.yml +++ b/src/main/resources/application-hph.yml @@ -1,3 +1,5 @@ +server: + port: 9888 spring: datasource: url: jdbc:mysql://rm-bp1b572nblln4jho2po.mysql.rds.aliyuncs.com/fycashier?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useJDBCCompliantTimezoneShift=true&serverTimezone=Asia/Shanghai&useSSL=false @@ -13,7 +15,7 @@ spring: com.chaozhanggui.system.openness: info redis: # redis数据库索引(默认为0),我们使用索引为3的数据库,避免和其他数据库冲突 - database: 5 + database: 0 # redis服务器地址(默认为localhost) host: 101.37.12.135 # redis端口(默认为6379) @@ -52,6 +54,7 @@ mybatis: ysk: url: https://gatewaytestapi.sxczgkj.cn/gate-service/ callBackurl: https://p40312246f.goho.co/cashierService/notify/notifyCallBack + callBackGroupurl: https://p40312246f.goho.co/cashierService/notify/notifyCallBackGroup callBackIn: https://p40312246f.goho.co/cashierService/notify/memberInCallBack default: 18710449883 diff --git a/src/main/resources/application-prod.yml b/src/main/resources/application-prod.yml index 8bb0b9a..90d838b 100644 --- a/src/main/resources/application-prod.yml +++ b/src/main/resources/application-prod.yml @@ -54,8 +54,14 @@ mybatis: ysk: url: https://gateway.api.sxczgkj.cn/gate-service/ callBackurl: https://cashier.sxczgkj.cn/cashierService/notify/notifyCallBack + callBackGroupurl: https://cashier.sxczgkj.cn/cashierService/notify/notifyCallBackGroup callBackIn: https://cashier.sxczgkj.cn/cashierService/notify/memberInCallBack default: 19191703856 +thirdPay: + callInBack: https://cashier.sxczgkj.cn${server.servlet.context-path}notify/fstmemberInCallBack + callFSTBack: https://cashier.sxczgkj.cn${server.servlet.context-path}notify/notifyfstCallBack +prod: prod1 +queue: cart_queue_putprod1 diff --git a/src/main/resources/application-prod2.yml b/src/main/resources/application-prod2.yml index f8e8e1d..7c8aa90 100644 --- a/src/main/resources/application-prod2.yml +++ b/src/main/resources/application-prod2.yml @@ -1,5 +1,5 @@ server: - port: 9888 + port: 9889 spring: datasource: url: jdbc:mysql://rm-bp1b572nblln4jho2.mysql.rds.aliyuncs.com/fycashier?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useJDBCCompliantTimezoneShift=true&serverTimezone=Asia/Shanghai&useSSL=false @@ -54,8 +54,14 @@ mybatis: ysk: url: https://gatewaytestapi.sxczgkj.cn/gate-service/ callBackurl: https://cashier.sxczgkj.cn/cashierService/notify/notifyCallBack + callBackGroupurl: https://cashier.sxczgkj.cn/cashierService/notify/notifyCallBackGroup callBackIn: https://cashier.sxczgkj.cn/cashierService/notify/memberInCallBack default: 19191703856 +thirdPay: + callInBack: https://cashier.sxczgkj.cn${server.servlet.context-path}notify/fstmemberInCallBack + callFSTBack: https://cashier.sxczgkj.cn${server.servlet.context-path}notify/notifyfstCallBack +prod: prod2 +queue: cart_queue_putprod2 diff --git a/src/main/resources/application-test.yml b/src/main/resources/application-test.yml index 7704195..e7f2d81 100644 --- a/src/main/resources/application-test.yml +++ b/src/main/resources/application-test.yml @@ -13,7 +13,7 @@ spring: com.chaozhanggui.system.openness: info redis: # redis数据库索引(默认为0),我们使用索引为3的数据库,避免和其他数据库冲突 - database: 5 + database: 0 # redis服务器地址(默认为localhost) host: 101.37.12.135 # redis端口(默认为6379) @@ -52,6 +52,7 @@ mybatis: ysk: url: https://gatewaytestapi.sxczgkj.cn/gate-service/ callBackurl: https://cashierapplet.sxczgkj.cn/cashierService/notify/notifyCallBack + callBackGroupurl: https://cashierapplet.sxczgkj.cn/cashierService/notify/notifyCallBackGroup callBackIn: https://cashierapplet.sxczgkj.cn/cashierService/notify/memberInCallBack default: 18710449883 diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 4f818e0..ff32aef 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -1,5 +1,5 @@ server: - port: 9889 +# port: 9889 servlet: context-path: /cashierService/ wx: @@ -10,6 +10,11 @@ wx: custom: appId: wxd88fffa983758a30 secrete: a34a61adc0602118b49400baa8812454 +# appId: wxc2bb94c0ddda1032 +# secrete: 5fe6b30f688ae461561250ed3e3db35b +# 卓尔 +# appId: wx0dcea6001b0a8fb4 +# secrete: ba42423cce61f93f02519ff3030ceb1c # spring: profiles: @@ -20,6 +25,16 @@ websocket: thread: boss: 12 work: 12 + +netty: + server: + port: 9999 + client-port: 9998 + # 接收者的线程数 + parent-group-threads: 10 + # 客户端的线程数 + child-group-threads: 10 + logging: level: # web日志 @@ -50,4 +65,11 @@ logging: #阿里云相关配置 aliyun: keyid: LTAI5tPdEfYSZcqHbjCrtPRD - keysecret: DZjyHBq3nTujF0NMLxnZgsecU8ZCvy \ No newline at end of file + keysecret: DZjyHBq3nTujF0NMLxnZgsecU8ZCvy + oss: + bucketname: cashier-oss + endpoint: oss-cn-beijing.aliyuncs.com + +thirdPay: + payType: fushangtong + url: https://paymentapi.sxczgkj.cn diff --git a/src/main/resources/generator-mapper/generatorConfig.xml b/src/main/resources/generator-mapper/generatorConfig.xml index 6f0944f..a6c8bea 100644 --- a/src/main/resources/generator-mapper/generatorConfig.xml +++ b/src/main/resources/generator-mapper/generatorConfig.xml @@ -19,8 +19,8 @@ - + @@ -52,13 +52,11 @@ -
- - \ No newline at end of file diff --git a/src/main/resources/mapper/SysDictDetailMapper.xml b/src/main/resources/mapper/SysDictDetailMapper.xml deleted file mode 100644 index 4fb74ac..0000000 --- a/src/main/resources/mapper/SysDictDetailMapper.xml +++ /dev/null @@ -1,155 +0,0 @@ - - - - - - - - - - - - - - - - detail_id, dict_id, label, value, dict_sort, create_by, update_by, create_time, update_time - - - - - - - delete from sys_dict_detail - where detail_id = #{detailId,jdbcType=BIGINT} - - - insert into sys_dict_detail (detail_id, dict_id, label, - value, dict_sort, create_by, - update_by, create_time, update_time - ) - values (#{detailId,jdbcType=BIGINT}, #{dictId,jdbcType=BIGINT}, #{label,jdbcType=VARCHAR}, - #{value,jdbcType=VARCHAR}, #{dictSort,jdbcType=INTEGER}, #{createBy,jdbcType=VARCHAR}, - #{updateBy,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP} - ) - - - insert into sys_dict_detail - - - detail_id, - - - dict_id, - - - label, - - - value, - - - dict_sort, - - - create_by, - - - update_by, - - - create_time, - - - update_time, - - - - - #{detailId,jdbcType=BIGINT}, - - - #{dictId,jdbcType=BIGINT}, - - - #{label,jdbcType=VARCHAR}, - - - #{value,jdbcType=VARCHAR}, - - - #{dictSort,jdbcType=INTEGER}, - - - #{createBy,jdbcType=VARCHAR}, - - - #{updateBy,jdbcType=VARCHAR}, - - - #{createTime,jdbcType=TIMESTAMP}, - - - #{updateTime,jdbcType=TIMESTAMP}, - - - - - update sys_dict_detail - - - dict_id = #{dictId,jdbcType=BIGINT}, - - - label = #{label,jdbcType=VARCHAR}, - - - value = #{value,jdbcType=VARCHAR}, - - - dict_sort = #{dictSort,jdbcType=INTEGER}, - - - create_by = #{createBy,jdbcType=VARCHAR}, - - - update_by = #{updateBy,jdbcType=VARCHAR}, - - - create_time = #{createTime,jdbcType=TIMESTAMP}, - - - update_time = #{updateTime,jdbcType=TIMESTAMP}, - - - where detail_id = #{detailId,jdbcType=BIGINT} - - - update sys_dict_detail - set dict_id = #{dictId,jdbcType=BIGINT}, - label = #{label,jdbcType=VARCHAR}, - value = #{value,jdbcType=VARCHAR}, - dict_sort = #{dictSort,jdbcType=INTEGER}, - create_by = #{createBy,jdbcType=VARCHAR}, - update_by = #{updateBy,jdbcType=VARCHAR}, - create_time = #{createTime,jdbcType=TIMESTAMP}, - update_time = #{updateTime,jdbcType=TIMESTAMP} - where detail_id = #{detailId,jdbcType=BIGINT} - - \ No newline at end of file diff --git a/src/main/resources/mapper/SysDictMapper.xml b/src/main/resources/mapper/SysDictMapper.xml index f1d271e..74d7bd5 100644 --- a/src/main/resources/mapper/SysDictMapper.xml +++ b/src/main/resources/mapper/SysDictMapper.xml @@ -1,117 +1,48 @@ - - - - - - - - - - - dict_id, name, description, create_by, update_by, create_time, update_time - - - - delete from sys_dict - where dict_id = #{dictId,jdbcType=BIGINT} - - - insert into sys_dict (dict_id, name, description, - create_by, update_by, create_time, - update_time) - values (#{dictId,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR}, #{description,jdbcType=VARCHAR}, - #{createBy,jdbcType=VARCHAR}, #{updateBy,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, - #{updateTime,jdbcType=TIMESTAMP}) - - - insert into sys_dict - - - dict_id, - - - name, - - - description, - - - create_by, - - - update_by, - - - create_time, - - - update_time, - - - - - #{dictId,jdbcType=BIGINT}, - - - #{name,jdbcType=VARCHAR}, - - - #{description,jdbcType=VARCHAR}, - - - #{createBy,jdbcType=VARCHAR}, - - - #{updateBy,jdbcType=VARCHAR}, - - - #{createTime,jdbcType=TIMESTAMP}, - - - #{updateTime,jdbcType=TIMESTAMP}, - - - - - update sys_dict - - - name = #{name,jdbcType=VARCHAR}, - - - description = #{description,jdbcType=VARCHAR}, - - - create_by = #{createBy,jdbcType=VARCHAR}, - - - update_by = #{updateBy,jdbcType=VARCHAR}, - - - create_time = #{createTime,jdbcType=TIMESTAMP}, - - - update_time = #{updateTime,jdbcType=TIMESTAMP}, - - - where dict_id = #{dictId,jdbcType=BIGINT} - - - update sys_dict - set name = #{name,jdbcType=VARCHAR}, - description = #{description,jdbcType=VARCHAR}, - create_by = #{createBy,jdbcType=VARCHAR}, - update_by = #{updateBy,jdbcType=VARCHAR}, - create_time = #{createTime,jdbcType=TIMESTAMP}, - update_time = #{updateTime,jdbcType=TIMESTAMP} - where dict_id = #{dictId,jdbcType=BIGINT} - + + + + + + + + + dict_id + , dict_name , name, value, is_child + + + dict_id + , dict_name , name, value + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/TagProductDeptsMapper.xml b/src/main/resources/mapper/TagProductDeptsMapper.xml new file mode 100644 index 0000000..3501c77 --- /dev/null +++ b/src/main/resources/mapper/TagProductDeptsMapper.xml @@ -0,0 +1,40 @@ + + + + + + + + + + diff --git a/src/main/resources/mapper/TbActivateMapper.xml b/src/main/resources/mapper/TbActivateMapper.xml new file mode 100644 index 0000000..50d204a --- /dev/null +++ b/src/main/resources/mapper/TbActivateMapper.xml @@ -0,0 +1,125 @@ + + + + + + + + + + + + + + id, shop_id, min_num, max_num, handsel_num, handsel_type, is_del + + + + delete from tb_activate + where id = #{id,jdbcType=INTEGER} + + + insert into tb_activate (id, shop_id, min_num, + max_num, handsel_num, handsel_type, + is_del) + values (#{id,jdbcType=INTEGER}, #{shopId,jdbcType=INTEGER}, #{minNum,jdbcType=INTEGER}, + #{maxNum,jdbcType=INTEGER}, #{handselNum,jdbcType=DECIMAL}, #{handselType,jdbcType=VARCHAR}, + #{isDel,jdbcType=VARCHAR}) + + + insert into tb_activate + + + id, + + + shop_id, + + + min_num, + + + max_num, + + + handsel_num, + + + handsel_type, + + + is_del, + + + + + #{id,jdbcType=INTEGER}, + + + #{shopId,jdbcType=INTEGER}, + + + #{minNum,jdbcType=INTEGER}, + + + #{maxNum,jdbcType=INTEGER}, + + + #{handselNum,jdbcType=DECIMAL}, + + + #{handselType,jdbcType=VARCHAR}, + + + #{isDel,jdbcType=VARCHAR}, + + + + + update tb_activate + + + shop_id = #{shopId,jdbcType=INTEGER}, + + + min_num = #{minNum,jdbcType=INTEGER}, + + + max_num = #{maxNum,jdbcType=INTEGER}, + + + handsel_num = #{handselNum,jdbcType=DECIMAL}, + + + handsel_type = #{handselType,jdbcType=VARCHAR}, + + + is_del = #{isDel,jdbcType=VARCHAR}, + + + where id = #{id,jdbcType=INTEGER} + + + update tb_activate + set shop_id = #{shopId,jdbcType=INTEGER}, + min_num = #{minNum,jdbcType=INTEGER}, + max_num = #{maxNum,jdbcType=INTEGER}, + handsel_num = #{handselNum,jdbcType=DECIMAL}, + handsel_type = #{handselType,jdbcType=VARCHAR}, + is_del = #{isDel,jdbcType=VARCHAR} + where id = #{id,jdbcType=INTEGER} + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/TbCashierCartMapper.xml b/src/main/resources/mapper/TbCashierCartMapper.xml index 0f141c1..0674893 100644 --- a/src/main/resources/mapper/TbCashierCartMapper.xml +++ b/src/main/resources/mapper/TbCashierCartMapper.xml @@ -32,12 +32,12 @@ - + 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} and `status`=#{status} + select * from tb_cashier_cart where order_id=#{orderId} + + and `status`=#{status} + + + \ No newline at end of file diff --git a/src/main/resources/mapper/TbCouponCategoryMapper.xml b/src/main/resources/mapper/TbCouponCategoryMapper.xml new file mode 100644 index 0000000..7ade432 --- /dev/null +++ b/src/main/resources/mapper/TbCouponCategoryMapper.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + id + , name, create_time, update_time, status + + + + + diff --git a/src/main/resources/mapper/TbGroupOrderCouponMapper.xml b/src/main/resources/mapper/TbGroupOrderCouponMapper.xml new file mode 100644 index 0000000..fd5c455 --- /dev/null +++ b/src/main/resources/mapper/TbGroupOrderCouponMapper.xml @@ -0,0 +1,128 @@ + + + + + + + + + + + + + + + + id + , order_id, coupon_no, is_refund, refund_amount, refund_reason, refund_desc + + + + + + + + + + + + + + + + insert into tb_group_order_coupon(order_id, coupon_no, is_refund, refund_amount, refund_reason, refund_desc) + values (#{orderId}, #{couponNo}, #{isRefund}, #{refundAmount}, #{refundReason}, #{refundDesc}) + + + + insert into tb_group_order_coupon(order_id, coupon_no, is_refund, refund_amount, refund_reason, refund_desc) + values + + (#{entity.orderId}, #{entity.couponNo}, #{entity.isRefund}, #{entity.refundAmount}, #{entity.refundReason}, + #{entity.refundDesc}) + + + + + + update tb_group_order_coupon + + + order_id = #{orderId}, + + + coupon_no = #{couponNo}, + + + is_refund = #{isRefund}, + + + refund_amount = #{refundAmount}, + + + refund_reason = #{refundReason}, + + + refund_desc = #{refundDesc}, + + + where id = #{id} + + + + + delete + from tb_group_order_coupon + where id = #{id} + + + + diff --git a/src/main/resources/mapper/TbGroupOrderInfoMapper.xml b/src/main/resources/mapper/TbGroupOrderInfoMapper.xml new file mode 100644 index 0000000..3574fe0 --- /dev/null +++ b/src/main/resources/mapper/TbGroupOrderInfoMapper.xml @@ -0,0 +1,191 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + id + , order_no, merchant_id, shop_id, user_id, pro_id, pro_img, pro_name, exp_date, order_type, pay_type, order_amount, save_amount, pay_amount, refund_amount, refund_number, number, status, remark, phone, pay_time, refund_able, create_time, verifier, update_time, pay_order_no, trade_day, source + + id + , order_no, pro_name,pro_img,order_amount, pay_amount, number, status + + + + + + + + + + + + insert into tb_group_order_info(order_no, merchant_id, shop_id, user_id, pro_id, pro_name, pro_img, + exp_date, order_type, pay_type, order_amount, save_amount, pay_amount, number, + refund_number, status, + remark, phone, pay_time, refund_able, create_time, update_time, pay_order_no, + trade_day, source) + values (#{orderNo}, #{merchantId}, #{shopId}, #{userId}, #{proId}, #{proName}, #{proImg}, + #{expDate}, #{orderType}, #{payType}, #{orderAmount}, #{saveAmount}, #{payAmount}, #{number}, + #{refundNumber}, #{status}, #{remark}, + #{phone}, #{payTime}, #{refundAble}, #{createTime}, #{updateTime}, #{payOrderNo}, #{tradeDay}, + #{source}) + + + + insert into tb_group_order_info(order_no,merchant_id, shop_id, user_id, pro_id, pro_name, pro_img, + exp_date, order_type, pay_type, order_amount, save_amount, pay_amount, number, status, remark, phone, pay_time, + refund_able, create_time, update_time, pay_order_no, trade_day, source) + values + + (#{entity.orderNo},#{entity.merchantId} #{entity.shopId}, #{entity.userId}, #{entity.proId}, + #{entity.proName},#{entity.proImg}, + #{entity.expDate}, #{entity.orderType}, + #{entity.payType}, #{entity.orderAmount}, #{entity.saveAmount}, #{entity.payAmount}, #{entity.number}, + #{entity.status}, + #{entity.remark}, #{entity.phone}, #{entity.payTime}, #{entity.refundAble}, #{entity.createTime}, + #{entity.updateTime}, #{entity.payOrderNo}, #{entity.tradeDay}, #{entity.source}) + + + + + + update tb_group_order_info + + + order_no = #{orderNo}, + + + merchant_id = #{merchantId}, + + + shop_id = #{shopId}, + + + user_id = #{userId}, + + + pro_id = #{proId}, + + + pro_name = #{proName}, + + + pro_img = #{proImg}, + + + exp_date = #{expDate}, + + + order_type = #{orderType}, + + + pay_type = #{payType}, + + + order_amount = #{orderAmount}, + + + save_amount = #{saveAmount}, + + + pay_amount = #{payAmount}, + + + number = #{number}, + + + status = #{status}, + + + remark = #{remark}, + + + phone = #{phone}, + + + pay_time = #{payTime}, + + + refund_able = #{refundAble}, + + + create_time = #{createTime}, + + + update_time = #{updateTime}, + + + pay_order_no = #{payOrderNo}, + + + trade_day = #{tradeDay}, + + + source = #{source}, + + + where id = #{id} + + + diff --git a/src/main/resources/mapper/TbIntegralFlowMapper.xml b/src/main/resources/mapper/TbIntegralFlowMapper.xml new file mode 100644 index 0000000..046f61b --- /dev/null +++ b/src/main/resources/mapper/TbIntegralFlowMapper.xml @@ -0,0 +1,93 @@ + + + + + + + + + + + + id, user_id, num, create_time, update_time + + + + delete from tb_integral_flow + where id = #{id,jdbcType=INTEGER} + + + insert into tb_integral_flow (id, user_id, num, + create_time, update_time) + values (#{id,jdbcType=INTEGER}, #{userId,jdbcType=VARCHAR}, #{num,jdbcType=DECIMAL}, + #{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP}) + + + insert into tb_integral_flow + + + id, + + + user_id, + + + num, + + + create_time, + + + update_time, + + + + + #{id,jdbcType=INTEGER}, + + + #{userId,jdbcType=VARCHAR}, + + + #{num,jdbcType=DECIMAL}, + + + #{createTime,jdbcType=TIMESTAMP}, + + + #{updateTime,jdbcType=TIMESTAMP}, + + + + + update tb_integral_flow + + + user_id = #{userId,jdbcType=VARCHAR}, + + + num = #{num,jdbcType=DECIMAL}, + + + create_time = #{createTime,jdbcType=TIMESTAMP}, + + + update_time = #{updateTime,jdbcType=TIMESTAMP}, + + + where id = #{id,jdbcType=INTEGER} + + + update tb_integral_flow + set user_id = #{userId,jdbcType=VARCHAR}, + num = #{num,jdbcType=DECIMAL}, + create_time = #{createTime,jdbcType=TIMESTAMP}, + update_time = #{updateTime,jdbcType=TIMESTAMP} + where id = #{id,jdbcType=INTEGER} + + \ No newline at end of file diff --git a/src/main/resources/mapper/TbIntegralMapper.xml b/src/main/resources/mapper/TbIntegralMapper.xml new file mode 100644 index 0000000..86c3c68 --- /dev/null +++ b/src/main/resources/mapper/TbIntegralMapper.xml @@ -0,0 +1,109 @@ + + + + + + + + + + + + + id, user_id, num, status, create_time, update_time + + + + + delete from tb_integral + where id = #{id,jdbcType=INTEGER} + + + insert into tb_integral (id, user_id, num, + status, create_time, update_time + ) + values (#{id,jdbcType=INTEGER}, #{userId,jdbcType=VARCHAR}, #{num,jdbcType=DECIMAL}, + #{status,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP} + ) + + + insert into tb_integral + + + id, + + + user_id, + + + num, + + + status, + + + create_time, + + + update_time, + + + + + #{id,jdbcType=INTEGER}, + + + #{userId,jdbcType=VARCHAR}, + + + #{num,jdbcType=DECIMAL}, + + + #{status,jdbcType=VARCHAR}, + + + #{createTime,jdbcType=TIMESTAMP}, + + + #{updateTime,jdbcType=TIMESTAMP}, + + + + + update tb_integral + + + user_id = #{userId,jdbcType=VARCHAR}, + + + num = #{num,jdbcType=DECIMAL}, + + + status = #{status,jdbcType=VARCHAR}, + + + create_time = #{createTime,jdbcType=TIMESTAMP}, + + + update_time = #{updateTime,jdbcType=TIMESTAMP}, + + + where id = #{id,jdbcType=INTEGER} + + + update tb_integral + set user_id = #{userId,jdbcType=VARCHAR}, + num = #{num,jdbcType=DECIMAL}, + status = #{status,jdbcType=VARCHAR}, + create_time = #{createTime,jdbcType=TIMESTAMP}, + update_time = #{updateTime,jdbcType=TIMESTAMP} + where id = #{id,jdbcType=INTEGER} + + \ No newline at end of file diff --git a/src/main/resources/mapper/TbMerchantCouponMapper.xml b/src/main/resources/mapper/TbMerchantCouponMapper.xml index 5dbcdc5..37ceb45 100644 --- a/src/main/resources/mapper/TbMerchantCouponMapper.xml +++ b/src/main/resources/mapper/TbMerchantCouponMapper.xml @@ -12,6 +12,7 @@ + @@ -42,408 +43,12 @@ - - - - - - - - - insert into tb_merchant_coupon(status, title, template_id, shop_id, shop_snap, from_time, to_time, limit_number, number, left_number, amount, limit_amount, is_show, pic, type, ratio, max_ratio_amount, track, class_type, effect_type, effect_days, relation_ids, relation_list, editor, note, created_at, updated_at, furnish_meal, furnish_express, furnish_draw, furnish_vir, disable_distribute, merchant_id) - values (#{status}, #{title}, #{templateId}, #{shopId}, #{shopSnap}, #{fromTime}, #{toTime}, #{limitNumber}, #{number}, #{leftNumber}, #{amount}, #{limitAmount}, #{isShow}, #{pic}, #{type}, #{ratio}, #{maxRatioAmount}, #{track}, #{classType}, #{effectType}, #{effectDays}, #{relationIds}, #{relationList}, #{editor}, #{note}, #{createdAt}, #{updatedAt}, #{furnishMeal}, #{furnishExpress}, #{furnishDraw}, #{furnishVir}, #{disableDistribute}, #{merchantId}) - - - - insert into tb_merchant_coupon(status, title, template_id, shop_id, shop_snap, from_time, to_time, limit_number, number, left_number, amount, limit_amount, is_show, pic, type, ratio, max_ratio_amount, track, class_type, effect_type, effect_days, relation_ids, relation_list, editor, note, created_at, updated_at, furnish_meal, furnish_express, furnish_draw, furnish_vir, disable_distribute, merchant_id) - values - - (#{entity.status}, #{entity.title}, #{entity.templateId}, #{entity.shopId}, #{entity.shopSnap}, #{entity.fromTime}, #{entity.toTime}, #{entity.limitNumber}, #{entity.number}, #{entity.leftNumber}, #{entity.amount}, #{entity.limitAmount}, #{entity.isShow}, #{entity.pic}, #{entity.type}, #{entity.ratio}, #{entity.maxRatioAmount}, #{entity.track}, #{entity.classType}, #{entity.effectType}, #{entity.effectDays}, #{entity.relationIds}, #{entity.relationList}, #{entity.editor}, #{entity.note}, #{entity.createdAt}, #{entity.updatedAt}, #{entity.furnishMeal}, #{entity.furnishExpress}, #{entity.furnishDraw}, #{entity.furnishVir}, #{entity.disableDistribute}, #{entity.merchantId}) - - - - - insert into tb_merchant_coupon(status, title, template_id, shop_id, shop_snap, from_time, to_time, limit_number, number, left_number, amount, limit_amount, is_show, pic, type, ratio, max_ratio_amount, track, class_type, effect_type, effect_days, relation_ids, relation_list, editor, note, created_at, updated_at, furnish_meal, furnish_express, furnish_draw, furnish_vir, disable_distribute, merchant_id) - values - - (#{entity.status}, #{entity.title}, #{entity.templateId}, #{entity.shopId}, #{entity.shopSnap}, #{entity.fromTime}, #{entity.toTime}, #{entity.limitNumber}, #{entity.number}, #{entity.leftNumber}, #{entity.amount}, #{entity.limitAmount}, #{entity.isShow}, #{entity.pic}, #{entity.type}, #{entity.ratio}, #{entity.maxRatioAmount}, #{entity.track}, #{entity.classType}, #{entity.effectType}, #{entity.effectDays}, #{entity.relationIds}, #{entity.relationList}, #{entity.editor}, #{entity.note}, #{entity.createdAt}, #{entity.updatedAt}, #{entity.furnishMeal}, #{entity.furnishExpress}, #{entity.furnishDraw}, #{entity.furnishVir}, #{entity.disableDistribute}, #{entity.merchantId}) - - on duplicate key update - status = values(status), - title = values(title), - template_id = values(template_id), - shop_id = values(shop_id), - shop_snap = values(shop_snap), - from_time = values(from_time), - to_time = values(to_time), - limit_number = values(limit_number), - number = values(number), - left_number = values(left_number), - amount = values(amount), - limit_amount = values(limit_amount), - is_show = values(is_show), - pic = values(pic), - type = values(type), - ratio = values(ratio), - max_ratio_amount = values(max_ratio_amount), - track = values(track), - class_type = values(class_type), - effect_type = values(effect_type), - effect_days = values(effect_days), - relation_ids = values(relation_ids), - relation_list = values(relation_list), - editor = values(editor), - note = values(note), - created_at = values(created_at), - updated_at = values(updated_at), - furnish_meal = values(furnish_meal), - furnish_express = values(furnish_express), - furnish_draw = values(furnish_draw), - furnish_vir = values(furnish_vir), - disable_distribute = values(disable_distribute), - merchant_id = values(merchant_id) - - - - - update tb_merchant_coupon - - - status = #{status}, - - - title = #{title}, - - - template_id = #{templateId}, - - - shop_id = #{shopId}, - - - shop_snap = #{shopSnap}, - - - from_time = #{fromTime}, - - - to_time = #{toTime}, - - - limit_number = #{limitNumber}, - - - number = #{number}, - - - left_number = #{leftNumber}, - - - amount = #{amount}, - - - limit_amount = #{limitAmount}, - - - is_show = #{isShow}, - - - pic = #{pic}, - - - type = #{type}, - - - ratio = #{ratio}, - - - max_ratio_amount = #{maxRatioAmount}, - - - track = #{track}, - - - class_type = #{classType}, - - - effect_type = #{effectType}, - - - effect_days = #{effectDays}, - - - relation_ids = #{relationIds}, - - - relation_list = #{relationList}, - - - editor = #{editor}, - - - note = #{note}, - - - created_at = #{createdAt}, - - - updated_at = #{updatedAt}, - - - furnish_meal = #{furnishMeal}, - - - furnish_express = #{furnishExpress}, - - - furnish_draw = #{furnishDraw}, - - - furnish_vir = #{furnishVir}, - - - disable_distribute = #{disableDistribute}, - - - merchant_id = #{merchantId}, - - - where id = #{id} - - - - - delete from tb_merchant_coupon where id = #{id} - diff --git a/src/main/resources/mapper/TbMerchantThirdApplyMapper.xml b/src/main/resources/mapper/TbMerchantThirdApplyMapper.xml index d9782c3..619e306 100644 --- a/src/main/resources/mapper/TbMerchantThirdApplyMapper.xml +++ b/src/main/resources/mapper/TbMerchantThirdApplyMapper.xml @@ -10,12 +10,14 @@ + + - id, type, app_id, status, pay_password, applyment_state, created_at, updated_at + id, type, app_id, status, pay_password, applyment_state, created_at, updated_at,small_appid,store_id app_token diff --git a/src/main/resources/mapper/TbOrderInfoMapper.xml b/src/main/resources/mapper/TbOrderInfoMapper.xml index eaa9bc4..5ee9c7d 100644 --- a/src/main/resources/mapper/TbOrderInfoMapper.xml +++ b/src/main/resources/mapper/TbOrderInfoMapper.xml @@ -46,6 +46,9 @@ + + + id, order_no, settlement_amount, pack_fee, origin_amount, product_amount, amount, @@ -53,7 +56,8 @@ discount_amount, table_id, small_change, send_type, order_type, product_type, status, billing_id, merchant_id, shop_id, is_vip, member_id, user_id, product_score, deduct_score, user_coupon_id, user_coupon_amount, refund_able, paid_time, is_effect, is_group, - updated_at, `system_time`, created_at, is_accepted, pay_order_no,trade_day,`source`,remark,master_id,`table_name` + updated_at, `system_time`, created_at, is_accepted, pay_order_no,trade_day,`source`, + remark,master_id,`table_name`,is_buy_coupon,is_use_coupon,out_number + + \ No newline at end of file diff --git a/src/main/resources/mapper/TbParamsMapper.xml b/src/main/resources/mapper/TbParamsMapper.xml new file mode 100644 index 0000000..9696d6d --- /dev/null +++ b/src/main/resources/mapper/TbParamsMapper.xml @@ -0,0 +1,71 @@ + + + + + + + + + + id, integral_ratio, trade_ratio + + + + delete from tb_params + where id = #{id,jdbcType=INTEGER} + + + insert into tb_params (id, integral_ratio, trade_ratio + ) + values (#{id,jdbcType=INTEGER}, #{integralRatio,jdbcType=DECIMAL}, #{tradeRatio,jdbcType=DECIMAL} + ) + + + insert into tb_params + + + id, + + + integral_ratio, + + + trade_ratio, + + + + + #{id,jdbcType=INTEGER}, + + + #{integralRatio,jdbcType=DECIMAL}, + + + #{tradeRatio,jdbcType=DECIMAL}, + + + + + update tb_params + + + integral_ratio = #{integralRatio,jdbcType=DECIMAL}, + + + trade_ratio = #{tradeRatio,jdbcType=DECIMAL}, + + + where id = #{id,jdbcType=INTEGER} + + + update tb_params + set integral_ratio = #{integralRatio,jdbcType=DECIMAL}, + trade_ratio = #{tradeRatio,jdbcType=DECIMAL} + where id = #{id,jdbcType=INTEGER} + + \ No newline at end of file diff --git a/src/main/resources/mapper/TbPlatformDictMapper.xml b/src/main/resources/mapper/TbPlatformDictMapper.xml index bac90db..f31aa24 100644 --- a/src/main/resources/mapper/TbPlatformDictMapper.xml +++ b/src/main/resources/mapper/TbPlatformDictMapper.xml @@ -4,13 +4,16 @@ + + + + - - + @@ -23,121 +26,26 @@ - - select - id, name, type, cover_img, share_img, video, video_cover_img, rel_url, abs_url, created_at, updated_at, is_show_cash, is_show_mall, is_show_app, sort + id, name,value, type, font_color, back_color, cover_img, share_img, video, video_cover_img, jump_type, abs_url, created_at, updated_at, is_show_cash, is_show_mall, is_show_app, sort from tb_platform_dict - - - and id = #{id} - - - and name = #{name} - - - and type = #{type} - - - and cover_img = #{coverImg} - - - and share_img = #{shareImg} - - - and video = #{video} - - - and video_cover_img = #{videoCoverImg} - - - and rel_url = #{relUrl} - - - and abs_url = #{absUrl} - - - and created_at = #{createdAt} - - - and updated_at = #{updatedAt} - - - and is_show_cash = #{isShowCash} - - - and is_show_mall = #{isShowMall} - - - and is_show_app = #{isShowApp} - - - and sort = #{sort} - - - limit #{pageable.offset}, #{pageable.pageSize} + where id IN + + #{id} + + order by sort - - - - - insert into tb_platform_dict(name, type, cover_img, share_img, video, video_cover_img, rel_url, abs_url, created_at, updated_at, is_show_cash, is_show_mall, is_show_app, sort) - values (#{name}, #{type}, #{coverImg}, #{shareImg}, #{video}, #{videoCoverImg}, #{relUrl}, #{absUrl}, #{createdAt}, #{updatedAt}, #{isShowCash}, #{isShowMall}, #{isShowApp}, #{sort}) - - - - insert into tb_platform_dict(name, type, cover_img, share_img, video, video_cover_img, rel_url, abs_url, created_at, updated_at, is_show_cash, is_show_mall, is_show_app, sort) - values - - (#{entity.name}, #{entity.type}, #{entity.coverImg}, #{entity.shareImg}, #{entity.video}, #{entity.videoCoverImg}, #{entity.relUrl}, #{entity.absUrl}, #{entity.createdAt}, #{entity.updatedAt}, #{entity.isShowCash}, #{entity.isShowMall}, #{entity.isShowApp}, #{entity.sort}) - - - - - insert into tb_platform_dict(name, type, cover_img, share_img, video, video_cover_img, rel_url, abs_url, created_at, updated_at, is_show_cash, is_show_mall, is_show_app, sort) - values - - (#{entity.name}, #{entity.type}, #{entity.coverImg}, #{entity.shareImg}, #{entity.video}, #{entity.videoCoverImg}, #{entity.relUrl}, #{entity.absUrl}, #{entity.createdAt}, #{entity.updatedAt}, #{entity.isShowCash}, #{entity.isShowMall}, #{entity.isShowApp}, #{entity.sort}) - - on duplicate key update - name = values(name), - type = values(type), - cover_img = values(cover_img), - share_img = values(share_img), - video = values(video), - video_cover_img = values(video_cover_img), - rel_url = values(rel_url), - abs_url = values(abs_url), - created_at = values(created_at), - updated_at = values(updated_at), - is_show_cash = values(is_show_cash), - is_show_mall = values(is_show_mall), - is_show_app = values(is_show_app), - sort = values(sort) - - - - - update tb_platform_dict - - - name = #{name}, + diff --git a/src/main/resources/mapper/TbProductGroupMapper.xml b/src/main/resources/mapper/TbProductGroupMapper.xml index bc1758d..a9bb7b2 100644 --- a/src/main/resources/mapper/TbProductGroupMapper.xml +++ b/src/main/resources/mapper/TbProductGroupMapper.xml @@ -222,4 +222,16 @@ order by g.sort asc + + \ No newline at end of file diff --git a/src/main/resources/mapper/TbProductMapper.xml b/src/main/resources/mapper/TbProductMapper.xml index 3940301..de28bdf 100644 --- a/src/main/resources/mapper/TbProductMapper.xml +++ b/src/main/resources/mapper/TbProductMapper.xml @@ -62,6 +62,7 @@ + @@ -73,14 +74,14 @@ id, category_id, spec_id, source_path, brand_id, merchant_id, shop_id, name, short_title, - type, pack_fee, low_price, low_member_price, unit_id, unit_snap, cover_img, share_img, + type, pack_fee, low_price, low_member_price, unit_id, unit_snap, cover_img, share_img, images, video_cover_img, sort, limit_number, product_score, status, fail_msg, is_recommend, is_hot, is_new, is_on_sale, is_show, type_enum, is_distribute, is_del, is_stock, is_pause_sale, is_free_freight, freight_id, strategy_type, strategy_id, is_vip, is_delete, created_at, updated_at, base_sales_number, real_sales_number, sales_number, thumb_count, store_count, furnish_meal, furnish_express, furnish_draw, furnish_vir, is_combo, is_show_cash, is_show_mall, is_need_examine, show_on_mall_status, show_on_mall_time, - show_on_mall_error_msg, enable_label, tax_config_id, spec_table_headers + show_on_mall_error_msg, enable_label, tax_config_id, spec_table_headers,group_category_id images, video, notice, group_snap, spec_info, select_spec @@ -881,11 +882,16 @@ spec_table_headers = #{specTableHeaders,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} + + update tb_product + set real_sales_number = real_sales_number + #{number,jdbcType=INTEGER} + where id = #{id,jdbcType=INTEGER} + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/TbProductSkuMapper.xml b/src/main/resources/mapper/TbProductSkuMapper.xml index 2f30e56..c928a35 100644 --- a/src/main/resources/mapper/TbProductSkuMapper.xml +++ b/src/main/resources/mapper/TbProductSkuMapper.xml @@ -381,17 +381,28 @@ GROUP BY product_id + + select + + + from tb_purchase_notice + where id = #{id} + + + + + + + diff --git a/src/main/resources/mapper/TbReleaseFlowMapper.xml b/src/main/resources/mapper/TbReleaseFlowMapper.xml new file mode 100644 index 0000000..4d7f97b --- /dev/null +++ b/src/main/resources/mapper/TbReleaseFlowMapper.xml @@ -0,0 +1,125 @@ + + + + + + + + + + + + + + + id, user_id, num, type, remark, from_source, create_time,operation_type + + + + + + delete from tb_release_flow + where id = #{id,jdbcType=INTEGER} + + + insert into tb_release_flow (id, user_id, num, + type, remark, from_source, + create_time,operation_type) + values (#{id,jdbcType=INTEGER}, #{userId,jdbcType=VARCHAR}, #{num,jdbcType=DECIMAL}, + #{type,jdbcType=VARCHAR}, #{remark,jdbcType=VARCHAR}, #{fromSource,jdbcType=VARCHAR}, + #{createTime,jdbcType=TIMESTAMP}, #{operationType,jdbcType=VARCHAR}) + + + insert into tb_release_flow + + + id, + + + user_id, + + + num, + + + type, + + + remark, + + + from_source, + + + create_time, + + + + + #{id,jdbcType=INTEGER}, + + + #{userId,jdbcType=VARCHAR}, + + + #{num,jdbcType=DECIMAL}, + + + #{type,jdbcType=VARCHAR}, + + + #{remark,jdbcType=VARCHAR}, + + + #{fromSource,jdbcType=VARCHAR}, + + + #{createTime,jdbcType=TIMESTAMP}, + + + + + update tb_release_flow + + + user_id = #{userId,jdbcType=VARCHAR}, + + + num = #{num,jdbcType=DECIMAL}, + + + type = #{type,jdbcType=VARCHAR}, + + + remark = #{remark,jdbcType=VARCHAR}, + + + from_source = #{fromSource,jdbcType=VARCHAR}, + + + create_time = #{createTime,jdbcType=TIMESTAMP}, + + + where id = #{id,jdbcType=INTEGER} + + + update tb_release_flow + set user_id = #{userId,jdbcType=VARCHAR}, + num = #{num,jdbcType=DECIMAL}, + type = #{type,jdbcType=VARCHAR}, + remark = #{remark,jdbcType=VARCHAR}, + from_source = #{fromSource,jdbcType=VARCHAR}, + create_time = #{createTime,jdbcType=TIMESTAMP} + where id = #{id,jdbcType=INTEGER} + + \ No newline at end of file diff --git a/src/main/resources/mapper/TbShopInfoMapper.xml b/src/main/resources/mapper/TbShopInfoMapper.xml index a16fbc7..47dc761 100644 --- a/src/main/resources/mapper/TbShopInfoMapper.xml +++ b/src/main/resources/mapper/TbShopInfoMapper.xml @@ -1,661 +1,696 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - id, account, shop_code, sub_title, merchant_id, shop_name, chain_name, back_img, + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + id + , account, shop_code, sub_title, merchant_id, shop_name, chain_name, back_img, front_img, contact_name, phone, logo, is_deposit, is_supply, cover_img, share_img, detail, lat, lng, mch_id, register_type, is_wx_ma_independent, address, city, type, - industry, industry_name, business_time, post_time, post_amount_line, on_sale, settle_type, - settle_time, enter_at, expire_at, status, average, order_wait_pay_minute, support_device_number, - distribute_level, created_at, updated_at, proxy_id - - - view - - - - - - - delete from tb_shop_info - where id = #{id,jdbcType=INTEGER} - - - insert into tb_shop_info (id, account, shop_code, - sub_title, merchant_id, shop_name, - chain_name, back_img, front_img, - contact_name, phone, logo, - is_deposit, is_supply, cover_img, - share_img, detail, lat, - lng, mch_id, register_type, - is_wx_ma_independent, address, city, - type, industry, industry_name, - business_time, post_time, post_amount_line, - on_sale, settle_type, settle_time, - enter_at, expire_at, status, - average, order_wait_pay_minute, support_device_number, - distribute_level, created_at, updated_at, - proxy_id, view) - values (#{id,jdbcType=INTEGER}, #{account,jdbcType=VARCHAR}, #{shopCode,jdbcType=VARCHAR}, - #{subTitle,jdbcType=VARCHAR}, #{merchantId,jdbcType=VARCHAR}, #{shopName,jdbcType=VARCHAR}, - #{chainName,jdbcType=VARCHAR}, #{backImg,jdbcType=VARCHAR}, #{frontImg,jdbcType=VARCHAR}, - #{contactName,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR}, #{logo,jdbcType=VARCHAR}, - #{isDeposit,jdbcType=TINYINT}, #{isSupply,jdbcType=TINYINT}, #{coverImg,jdbcType=VARCHAR}, - #{shareImg,jdbcType=VARCHAR}, #{detail,jdbcType=VARCHAR}, #{lat,jdbcType=VARCHAR}, - #{lng,jdbcType=VARCHAR}, #{mchId,jdbcType=VARCHAR}, #{registerType,jdbcType=VARCHAR}, - #{isWxMaIndependent,jdbcType=TINYINT}, #{address,jdbcType=VARCHAR}, #{city,jdbcType=VARCHAR}, - #{type,jdbcType=VARCHAR}, #{industry,jdbcType=VARCHAR}, #{industryName,jdbcType=VARCHAR}, - #{businessTime,jdbcType=VARCHAR}, #{postTime,jdbcType=VARCHAR}, #{postAmountLine,jdbcType=DECIMAL}, - #{onSale,jdbcType=TINYINT}, #{settleType,jdbcType=TINYINT}, #{settleTime,jdbcType=VARCHAR}, - #{enterAt,jdbcType=INTEGER}, #{expireAt,jdbcType=BIGINT}, #{status,jdbcType=TINYINT}, - #{average,jdbcType=REAL}, #{orderWaitPayMinute,jdbcType=INTEGER}, #{supportDeviceNumber,jdbcType=INTEGER}, - #{distributeLevel,jdbcType=TINYINT}, #{createdAt,jdbcType=BIGINT}, #{updatedAt,jdbcType=BIGINT}, - #{proxyId,jdbcType=VARCHAR}, #{view,jdbcType=LONGVARCHAR}) - - - insert into tb_shop_info - - - id, - - - account, - - - shop_code, - - - sub_title, - - - merchant_id, - - - shop_name, - - - chain_name, - - - back_img, - - - front_img, - - - contact_name, - - - phone, - - - logo, - - - is_deposit, - - - is_supply, - - - cover_img, - - - share_img, - - - detail, - - - lat, - - - lng, - - - mch_id, - - - register_type, - - - is_wx_ma_independent, - - - address, - - - city, - - - type, - - - industry, - - - industry_name, - - - business_time, - - - post_time, - - - post_amount_line, - - - on_sale, - - - settle_type, - - - settle_time, - - - enter_at, - - - expire_at, - - - status, - - - average, - - - order_wait_pay_minute, - - - support_device_number, - - - distribute_level, - - - created_at, - - - updated_at, - - - proxy_id, - - - view, - - - - - #{id,jdbcType=INTEGER}, - - - #{account,jdbcType=VARCHAR}, - - - #{shopCode,jdbcType=VARCHAR}, - - - #{subTitle,jdbcType=VARCHAR}, - - - #{merchantId,jdbcType=VARCHAR}, - - - #{shopName,jdbcType=VARCHAR}, - - - #{chainName,jdbcType=VARCHAR}, - - - #{backImg,jdbcType=VARCHAR}, - - - #{frontImg,jdbcType=VARCHAR}, - - - #{contactName,jdbcType=VARCHAR}, - - - #{phone,jdbcType=VARCHAR}, - - - #{logo,jdbcType=VARCHAR}, - - - #{isDeposit,jdbcType=TINYINT}, - - - #{isSupply,jdbcType=TINYINT}, - - - #{coverImg,jdbcType=VARCHAR}, - - - #{shareImg,jdbcType=VARCHAR}, - - - #{detail,jdbcType=VARCHAR}, - - - #{lat,jdbcType=VARCHAR}, - - - #{lng,jdbcType=VARCHAR}, - - - #{mchId,jdbcType=VARCHAR}, - - - #{registerType,jdbcType=VARCHAR}, - - - #{isWxMaIndependent,jdbcType=TINYINT}, - - - #{address,jdbcType=VARCHAR}, - - - #{city,jdbcType=VARCHAR}, - - - #{type,jdbcType=VARCHAR}, - - - #{industry,jdbcType=VARCHAR}, - - - #{industryName,jdbcType=VARCHAR}, - - - #{businessTime,jdbcType=VARCHAR}, - - - #{postTime,jdbcType=VARCHAR}, - - - #{postAmountLine,jdbcType=DECIMAL}, - - - #{onSale,jdbcType=TINYINT}, - - - #{settleType,jdbcType=TINYINT}, - - - #{settleTime,jdbcType=VARCHAR}, - - - #{enterAt,jdbcType=INTEGER}, - - - #{expireAt,jdbcType=BIGINT}, - - - #{status,jdbcType=TINYINT}, - - - #{average,jdbcType=REAL}, - - - #{orderWaitPayMinute,jdbcType=INTEGER}, - - - #{supportDeviceNumber,jdbcType=INTEGER}, - - - #{distributeLevel,jdbcType=TINYINT}, - - - #{createdAt,jdbcType=BIGINT}, - - - #{updatedAt,jdbcType=BIGINT}, - - - #{proxyId,jdbcType=VARCHAR}, - - - #{view,jdbcType=LONGVARCHAR}, - - - - - update tb_shop_info - - - account = #{account,jdbcType=VARCHAR}, - - - shop_code = #{shopCode,jdbcType=VARCHAR}, - - - sub_title = #{subTitle,jdbcType=VARCHAR}, - - - merchant_id = #{merchantId,jdbcType=VARCHAR}, - - - shop_name = #{shopName,jdbcType=VARCHAR}, - - - chain_name = #{chainName,jdbcType=VARCHAR}, - - - back_img = #{backImg,jdbcType=VARCHAR}, - - - front_img = #{frontImg,jdbcType=VARCHAR}, - - - contact_name = #{contactName,jdbcType=VARCHAR}, - - - phone = #{phone,jdbcType=VARCHAR}, - - - logo = #{logo,jdbcType=VARCHAR}, - - - is_deposit = #{isDeposit,jdbcType=TINYINT}, - - - is_supply = #{isSupply,jdbcType=TINYINT}, - - - cover_img = #{coverImg,jdbcType=VARCHAR}, - - - share_img = #{shareImg,jdbcType=VARCHAR}, - - - detail = #{detail,jdbcType=VARCHAR}, - - - lat = #{lat,jdbcType=VARCHAR}, - - - lng = #{lng,jdbcType=VARCHAR}, - - - mch_id = #{mchId,jdbcType=VARCHAR}, - - - register_type = #{registerType,jdbcType=VARCHAR}, - - - is_wx_ma_independent = #{isWxMaIndependent,jdbcType=TINYINT}, - - - address = #{address,jdbcType=VARCHAR}, - - - city = #{city,jdbcType=VARCHAR}, - - - type = #{type,jdbcType=VARCHAR}, - - - industry = #{industry,jdbcType=VARCHAR}, - - - industry_name = #{industryName,jdbcType=VARCHAR}, - - - business_time = #{businessTime,jdbcType=VARCHAR}, - - - post_time = #{postTime,jdbcType=VARCHAR}, - - - post_amount_line = #{postAmountLine,jdbcType=DECIMAL}, - - - on_sale = #{onSale,jdbcType=TINYINT}, - - - settle_type = #{settleType,jdbcType=TINYINT}, - - - settle_time = #{settleTime,jdbcType=VARCHAR}, - - - enter_at = #{enterAt,jdbcType=INTEGER}, - - - expire_at = #{expireAt,jdbcType=BIGINT}, - - - status = #{status,jdbcType=TINYINT}, - - - average = #{average,jdbcType=REAL}, - - - order_wait_pay_minute = #{orderWaitPayMinute,jdbcType=INTEGER}, - - - support_device_number = #{supportDeviceNumber,jdbcType=INTEGER}, - - - distribute_level = #{distributeLevel,jdbcType=TINYINT}, - - - created_at = #{createdAt,jdbcType=BIGINT}, - - - updated_at = #{updatedAt,jdbcType=BIGINT}, - - - proxy_id = #{proxyId,jdbcType=VARCHAR}, - - - view = #{view,jdbcType=LONGVARCHAR}, - - - where id = #{id,jdbcType=INTEGER} - - - update tb_shop_info - set account = #{account,jdbcType=VARCHAR}, - shop_code = #{shopCode,jdbcType=VARCHAR}, - sub_title = #{subTitle,jdbcType=VARCHAR}, - merchant_id = #{merchantId,jdbcType=VARCHAR}, - shop_name = #{shopName,jdbcType=VARCHAR}, - chain_name = #{chainName,jdbcType=VARCHAR}, - back_img = #{backImg,jdbcType=VARCHAR}, - front_img = #{frontImg,jdbcType=VARCHAR}, - contact_name = #{contactName,jdbcType=VARCHAR}, - phone = #{phone,jdbcType=VARCHAR}, - logo = #{logo,jdbcType=VARCHAR}, - is_deposit = #{isDeposit,jdbcType=TINYINT}, - is_supply = #{isSupply,jdbcType=TINYINT}, - cover_img = #{coverImg,jdbcType=VARCHAR}, - share_img = #{shareImg,jdbcType=VARCHAR}, - detail = #{detail,jdbcType=VARCHAR}, - lat = #{lat,jdbcType=VARCHAR}, - lng = #{lng,jdbcType=VARCHAR}, - mch_id = #{mchId,jdbcType=VARCHAR}, - register_type = #{registerType,jdbcType=VARCHAR}, - is_wx_ma_independent = #{isWxMaIndependent,jdbcType=TINYINT}, - address = #{address,jdbcType=VARCHAR}, - city = #{city,jdbcType=VARCHAR}, - type = #{type,jdbcType=VARCHAR}, - industry = #{industry,jdbcType=VARCHAR}, - industry_name = #{industryName,jdbcType=VARCHAR}, - business_time = #{businessTime,jdbcType=VARCHAR}, - post_time = #{postTime,jdbcType=VARCHAR}, - post_amount_line = #{postAmountLine,jdbcType=DECIMAL}, - on_sale = #{onSale,jdbcType=TINYINT}, - settle_type = #{settleType,jdbcType=TINYINT}, - settle_time = #{settleTime,jdbcType=VARCHAR}, - enter_at = #{enterAt,jdbcType=INTEGER}, - expire_at = #{expireAt,jdbcType=BIGINT}, - status = #{status,jdbcType=TINYINT}, - average = #{average,jdbcType=REAL}, - order_wait_pay_minute = #{orderWaitPayMinute,jdbcType=INTEGER}, - support_device_number = #{supportDeviceNumber,jdbcType=INTEGER}, - distribute_level = #{distributeLevel,jdbcType=TINYINT}, - created_at = #{createdAt,jdbcType=BIGINT}, - updated_at = #{updatedAt,jdbcType=BIGINT}, - proxy_id = #{proxyId,jdbcType=VARCHAR}, - view = #{view,jdbcType=LONGVARCHAR} - where id = #{id,jdbcType=INTEGER} - - - update tb_shop_info - set account = #{account,jdbcType=VARCHAR}, - shop_code = #{shopCode,jdbcType=VARCHAR}, - sub_title = #{subTitle,jdbcType=VARCHAR}, - merchant_id = #{merchantId,jdbcType=VARCHAR}, - shop_name = #{shopName,jdbcType=VARCHAR}, - chain_name = #{chainName,jdbcType=VARCHAR}, - back_img = #{backImg,jdbcType=VARCHAR}, - front_img = #{frontImg,jdbcType=VARCHAR}, - contact_name = #{contactName,jdbcType=VARCHAR}, - phone = #{phone,jdbcType=VARCHAR}, - logo = #{logo,jdbcType=VARCHAR}, - is_deposit = #{isDeposit,jdbcType=TINYINT}, - is_supply = #{isSupply,jdbcType=TINYINT}, - cover_img = #{coverImg,jdbcType=VARCHAR}, - share_img = #{shareImg,jdbcType=VARCHAR}, - detail = #{detail,jdbcType=VARCHAR}, - lat = #{lat,jdbcType=VARCHAR}, - lng = #{lng,jdbcType=VARCHAR}, - mch_id = #{mchId,jdbcType=VARCHAR}, - register_type = #{registerType,jdbcType=VARCHAR}, - is_wx_ma_independent = #{isWxMaIndependent,jdbcType=TINYINT}, - address = #{address,jdbcType=VARCHAR}, - city = #{city,jdbcType=VARCHAR}, - type = #{type,jdbcType=VARCHAR}, - industry = #{industry,jdbcType=VARCHAR}, - industry_name = #{industryName,jdbcType=VARCHAR}, - business_time = #{businessTime,jdbcType=VARCHAR}, - post_time = #{postTime,jdbcType=VARCHAR}, - post_amount_line = #{postAmountLine,jdbcType=DECIMAL}, - on_sale = #{onSale,jdbcType=TINYINT}, - settle_type = #{settleType,jdbcType=TINYINT}, - settle_time = #{settleTime,jdbcType=VARCHAR}, - enter_at = #{enterAt,jdbcType=INTEGER}, - expire_at = #{expireAt,jdbcType=BIGINT}, - status = #{status,jdbcType=TINYINT}, - average = #{average,jdbcType=REAL}, - order_wait_pay_minute = #{orderWaitPayMinute,jdbcType=INTEGER}, - support_device_number = #{supportDeviceNumber,jdbcType=INTEGER}, - distribute_level = #{distributeLevel,jdbcType=TINYINT}, - created_at = #{createdAt,jdbcType=BIGINT}, - updated_at = #{updatedAt,jdbcType=BIGINT}, - proxy_id = #{proxyId,jdbcType=VARCHAR} - where id = #{id,jdbcType=INTEGER} - - - + select + + , + + from tb_shop_info + where id = #{id,jdbcType=INTEGER} - - - - + + + + + + + + delete + from tb_shop_info + where id = #{id,jdbcType=INTEGER} + + + insert into tb_shop_info (id, account, shop_code, + sub_title, merchant_id, shop_name, + chain_name, back_img, front_img, + contact_name, phone, logo, + is_deposit, is_supply, cover_img, + share_img, detail, lat, + lng, mch_id, register_type, + is_wx_ma_independent, address, city, + type, industry, industry_name, + business_time, post_time, post_amount_line, + on_sale, settle_type, settle_time, + enter_at, expire_at, status, + average, order_wait_pay_minute, support_device_number, + distribute_level, created_at, updated_at, + proxy_id, view) + values (#{id,jdbcType=INTEGER}, #{account,jdbcType=VARCHAR}, #{shopCode,jdbcType=VARCHAR}, + #{subTitle,jdbcType=VARCHAR}, #{merchantId,jdbcType=VARCHAR}, #{shopName,jdbcType=VARCHAR}, + #{chainName,jdbcType=VARCHAR}, #{backImg,jdbcType=VARCHAR}, #{frontImg,jdbcType=VARCHAR}, + #{contactName,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR}, #{logo,jdbcType=VARCHAR}, + #{isDeposit,jdbcType=TINYINT}, #{isSupply,jdbcType=TINYINT}, #{coverImg,jdbcType=VARCHAR}, + #{shareImg,jdbcType=VARCHAR}, #{detail,jdbcType=VARCHAR}, #{lat,jdbcType=VARCHAR}, + #{lng,jdbcType=VARCHAR}, #{mchId,jdbcType=VARCHAR}, #{registerType,jdbcType=VARCHAR}, + #{isWxMaIndependent,jdbcType=TINYINT}, #{address,jdbcType=VARCHAR}, #{city,jdbcType=VARCHAR}, + #{type,jdbcType=VARCHAR}, #{industry,jdbcType=VARCHAR}, #{industryName,jdbcType=VARCHAR}, + #{businessTime,jdbcType=VARCHAR}, #{postTime,jdbcType=VARCHAR}, #{postAmountLine,jdbcType=DECIMAL}, + #{onSale,jdbcType=TINYINT}, #{settleType,jdbcType=TINYINT}, #{settleTime,jdbcType=VARCHAR}, + #{enterAt,jdbcType=INTEGER}, #{expireAt,jdbcType=BIGINT}, #{status,jdbcType=TINYINT}, + #{average,jdbcType=REAL}, #{orderWaitPayMinute,jdbcType=INTEGER}, + #{supportDeviceNumber,jdbcType=INTEGER}, + #{distributeLevel,jdbcType=TINYINT}, #{createdAt,jdbcType=BIGINT}, #{updatedAt,jdbcType=BIGINT}, + #{proxyId,jdbcType=VARCHAR}, #{view,jdbcType=LONGVARCHAR}) + + + insert into tb_shop_info + + + id, + + + account, + + + shop_code, + + + sub_title, + + + merchant_id, + + + shop_name, + + + chain_name, + + + back_img, + + + front_img, + + + contact_name, + + + phone, + + + logo, + + + is_deposit, + + + is_supply, + + + cover_img, + + + share_img, + + + detail, + + + lat, + + + lng, + + + mch_id, + + + register_type, + + + is_wx_ma_independent, + + + address, + + + city, + + + type, + + + industry, + + + industry_name, + + + business_time, + + + post_time, + + + post_amount_line, + + + on_sale, + + + settle_type, + + + settle_time, + + + enter_at, + + + expire_at, + + + status, + + + average, + + + order_wait_pay_minute, + + + support_device_number, + + + distribute_level, + + + created_at, + + + updated_at, + + + proxy_id, + + + view, + + + + + #{id,jdbcType=INTEGER}, + + + #{account,jdbcType=VARCHAR}, + + + #{shopCode,jdbcType=VARCHAR}, + + + #{subTitle,jdbcType=VARCHAR}, + + + #{merchantId,jdbcType=VARCHAR}, + + + #{shopName,jdbcType=VARCHAR}, + + + #{chainName,jdbcType=VARCHAR}, + + + #{backImg,jdbcType=VARCHAR}, + + + #{frontImg,jdbcType=VARCHAR}, + + + #{contactName,jdbcType=VARCHAR}, + + + #{phone,jdbcType=VARCHAR}, + + + #{logo,jdbcType=VARCHAR}, + + + #{isDeposit,jdbcType=TINYINT}, + + + #{isSupply,jdbcType=TINYINT}, + + + #{coverImg,jdbcType=VARCHAR}, + + + #{shareImg,jdbcType=VARCHAR}, + + + #{detail,jdbcType=VARCHAR}, + + + #{lat,jdbcType=VARCHAR}, + + + #{lng,jdbcType=VARCHAR}, + + + #{mchId,jdbcType=VARCHAR}, + + + #{registerType,jdbcType=VARCHAR}, + + + #{isWxMaIndependent,jdbcType=TINYINT}, + + + #{address,jdbcType=VARCHAR}, + + + #{city,jdbcType=VARCHAR}, + + + #{type,jdbcType=VARCHAR}, + + + #{industry,jdbcType=VARCHAR}, + + + #{industryName,jdbcType=VARCHAR}, + + + #{businessTime,jdbcType=VARCHAR}, + + + #{postTime,jdbcType=VARCHAR}, + + + #{postAmountLine,jdbcType=DECIMAL}, + + + #{onSale,jdbcType=TINYINT}, + + + #{settleType,jdbcType=TINYINT}, + + + #{settleTime,jdbcType=VARCHAR}, + + + #{enterAt,jdbcType=INTEGER}, + + + #{expireAt,jdbcType=BIGINT}, + + + #{status,jdbcType=TINYINT}, + + + #{average,jdbcType=REAL}, + + + #{orderWaitPayMinute,jdbcType=INTEGER}, + + + #{supportDeviceNumber,jdbcType=INTEGER}, + + + #{distributeLevel,jdbcType=TINYINT}, + + + #{createdAt,jdbcType=BIGINT}, + + + #{updatedAt,jdbcType=BIGINT}, + + + #{proxyId,jdbcType=VARCHAR}, + + + #{view,jdbcType=LONGVARCHAR}, + + + + + update tb_shop_info + + + account = #{account,jdbcType=VARCHAR}, + + + shop_code = #{shopCode,jdbcType=VARCHAR}, + + + sub_title = #{subTitle,jdbcType=VARCHAR}, + + + merchant_id = #{merchantId,jdbcType=VARCHAR}, + + + shop_name = #{shopName,jdbcType=VARCHAR}, + + + chain_name = #{chainName,jdbcType=VARCHAR}, + + + back_img = #{backImg,jdbcType=VARCHAR}, + + + front_img = #{frontImg,jdbcType=VARCHAR}, + + + contact_name = #{contactName,jdbcType=VARCHAR}, + + + phone = #{phone,jdbcType=VARCHAR}, + + + logo = #{logo,jdbcType=VARCHAR}, + + + is_deposit = #{isDeposit,jdbcType=TINYINT}, + + + is_supply = #{isSupply,jdbcType=TINYINT}, + + + cover_img = #{coverImg,jdbcType=VARCHAR}, + + + share_img = #{shareImg,jdbcType=VARCHAR}, + + + detail = #{detail,jdbcType=VARCHAR}, + + + lat = #{lat,jdbcType=VARCHAR}, + + + lng = #{lng,jdbcType=VARCHAR}, + + + mch_id = #{mchId,jdbcType=VARCHAR}, + + + register_type = #{registerType,jdbcType=VARCHAR}, + + + is_wx_ma_independent = #{isWxMaIndependent,jdbcType=TINYINT}, + + + address = #{address,jdbcType=VARCHAR}, + + + city = #{city,jdbcType=VARCHAR}, + + + type = #{type,jdbcType=VARCHAR}, + + + industry = #{industry,jdbcType=VARCHAR}, + + + industry_name = #{industryName,jdbcType=VARCHAR}, + + + business_time = #{businessTime,jdbcType=VARCHAR}, + + + post_time = #{postTime,jdbcType=VARCHAR}, + + + post_amount_line = #{postAmountLine,jdbcType=DECIMAL}, + + + on_sale = #{onSale,jdbcType=TINYINT}, + + + settle_type = #{settleType,jdbcType=TINYINT}, + + + settle_time = #{settleTime,jdbcType=VARCHAR}, + + + enter_at = #{enterAt,jdbcType=INTEGER}, + + + expire_at = #{expireAt,jdbcType=BIGINT}, + + + status = #{status,jdbcType=TINYINT}, + + + average = #{average,jdbcType=REAL}, + + + order_wait_pay_minute = #{orderWaitPayMinute,jdbcType=INTEGER}, + + + support_device_number = #{supportDeviceNumber,jdbcType=INTEGER}, + + + distribute_level = #{distributeLevel,jdbcType=TINYINT}, + + + created_at = #{createdAt,jdbcType=BIGINT}, + + + updated_at = #{updatedAt,jdbcType=BIGINT}, + + + proxy_id = #{proxyId,jdbcType=VARCHAR}, + + + view = #{view,jdbcType=LONGVARCHAR}, + + + where id = #{id,jdbcType=INTEGER} + + + update tb_shop_info + set account = #{account,jdbcType=VARCHAR}, + shop_code = #{shopCode,jdbcType=VARCHAR}, + sub_title = #{subTitle,jdbcType=VARCHAR}, + merchant_id = #{merchantId,jdbcType=VARCHAR}, + shop_name = #{shopName,jdbcType=VARCHAR}, + chain_name = #{chainName,jdbcType=VARCHAR}, + back_img = #{backImg,jdbcType=VARCHAR}, + front_img = #{frontImg,jdbcType=VARCHAR}, + contact_name = #{contactName,jdbcType=VARCHAR}, + phone = #{phone,jdbcType=VARCHAR}, + logo = #{logo,jdbcType=VARCHAR}, + is_deposit = #{isDeposit,jdbcType=TINYINT}, + is_supply = #{isSupply,jdbcType=TINYINT}, + cover_img = #{coverImg,jdbcType=VARCHAR}, + share_img = #{shareImg,jdbcType=VARCHAR}, + detail = #{detail,jdbcType=VARCHAR}, + lat = #{lat,jdbcType=VARCHAR}, + lng = #{lng,jdbcType=VARCHAR}, + mch_id = #{mchId,jdbcType=VARCHAR}, + register_type = #{registerType,jdbcType=VARCHAR}, + is_wx_ma_independent = #{isWxMaIndependent,jdbcType=TINYINT}, + address = #{address,jdbcType=VARCHAR}, + city = #{city,jdbcType=VARCHAR}, + type = #{type,jdbcType=VARCHAR}, + industry = #{industry,jdbcType=VARCHAR}, + industry_name = #{industryName,jdbcType=VARCHAR}, + business_time = #{businessTime,jdbcType=VARCHAR}, + post_time = #{postTime,jdbcType=VARCHAR}, + post_amount_line = #{postAmountLine,jdbcType=DECIMAL}, + on_sale = #{onSale,jdbcType=TINYINT}, + settle_type = #{settleType,jdbcType=TINYINT}, + settle_time = #{settleTime,jdbcType=VARCHAR}, + enter_at = #{enterAt,jdbcType=INTEGER}, + expire_at = #{expireAt,jdbcType=BIGINT}, + status = #{status,jdbcType=TINYINT}, + average = #{average,jdbcType=REAL}, + order_wait_pay_minute = #{orderWaitPayMinute,jdbcType=INTEGER}, + support_device_number = #{supportDeviceNumber,jdbcType=INTEGER}, + distribute_level = #{distributeLevel,jdbcType=TINYINT}, + created_at = #{createdAt,jdbcType=BIGINT}, + updated_at = #{updatedAt,jdbcType=BIGINT}, + proxy_id = #{proxyId,jdbcType=VARCHAR}, + view = #{view,jdbcType=LONGVARCHAR} + where id = #{id,jdbcType=INTEGER} + + + update tb_shop_info + set account = #{account,jdbcType=VARCHAR}, + shop_code = #{shopCode,jdbcType=VARCHAR}, + sub_title = #{subTitle,jdbcType=VARCHAR}, + merchant_id = #{merchantId,jdbcType=VARCHAR}, + shop_name = #{shopName,jdbcType=VARCHAR}, + chain_name = #{chainName,jdbcType=VARCHAR}, + back_img = #{backImg,jdbcType=VARCHAR}, + front_img = #{frontImg,jdbcType=VARCHAR}, + contact_name = #{contactName,jdbcType=VARCHAR}, + phone = #{phone,jdbcType=VARCHAR}, + logo = #{logo,jdbcType=VARCHAR}, + is_deposit = #{isDeposit,jdbcType=TINYINT}, + is_supply = #{isSupply,jdbcType=TINYINT}, + cover_img = #{coverImg,jdbcType=VARCHAR}, + share_img = #{shareImg,jdbcType=VARCHAR}, + detail = #{detail,jdbcType=VARCHAR}, + lat = #{lat,jdbcType=VARCHAR}, + lng = #{lng,jdbcType=VARCHAR}, + mch_id = #{mchId,jdbcType=VARCHAR}, + register_type = #{registerType,jdbcType=VARCHAR}, + is_wx_ma_independent = #{isWxMaIndependent,jdbcType=TINYINT}, + address = #{address,jdbcType=VARCHAR}, + city = #{city,jdbcType=VARCHAR}, + type = #{type,jdbcType=VARCHAR}, + industry = #{industry,jdbcType=VARCHAR}, + industry_name = #{industryName,jdbcType=VARCHAR}, + business_time = #{businessTime,jdbcType=VARCHAR}, + post_time = #{postTime,jdbcType=VARCHAR}, + post_amount_line = #{postAmountLine,jdbcType=DECIMAL}, + on_sale = #{onSale,jdbcType=TINYINT}, + settle_type = #{settleType,jdbcType=TINYINT}, + settle_time = #{settleTime,jdbcType=VARCHAR}, + enter_at = #{enterAt,jdbcType=INTEGER}, + expire_at = #{expireAt,jdbcType=BIGINT}, + status = #{status,jdbcType=TINYINT}, + average = #{average,jdbcType=REAL}, + order_wait_pay_minute = #{orderWaitPayMinute,jdbcType=INTEGER}, + support_device_number = #{supportDeviceNumber,jdbcType=INTEGER}, + distribute_level = #{distributeLevel,jdbcType=TINYINT}, + created_at = #{createdAt,jdbcType=BIGINT}, + updated_at = #{updatedAt,jdbcType=BIGINT}, + proxy_id = #{proxyId,jdbcType=VARCHAR} + where id = #{id,jdbcType=INTEGER} + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/TbShopPayTypeMapper.xml b/src/main/resources/mapper/TbShopPayTypeMapper.xml index 9b2c36c..10527de 100644 --- a/src/main/resources/mapper/TbShopPayTypeMapper.xml +++ b/src/main/resources/mapper/TbShopPayTypeMapper.xml @@ -185,4 +185,9 @@ updated_at = #{updatedAt,jdbcType=BIGINT} where id = #{id,jdbcType=INTEGER} + + \ No newline at end of file diff --git a/src/main/resources/mapper/TbShopTableMapper.xml b/src/main/resources/mapper/TbShopTableMapper.xml index c7b6d68..e4abfc3 100644 --- a/src/main/resources/mapper/TbShopTableMapper.xml +++ b/src/main/resources/mapper/TbShopTableMapper.xml @@ -35,6 +35,15 @@ from tb_shop_table where qrcode = #{qrcode} + + + select @@ -26,10 +27,10 @@ insert into tb_shop_user_flow (id, shop_user_id, amount, balance, biz_code, biz_name, - create_time) + create_time, type) values (#{id,jdbcType=INTEGER}, #{shopUserId,jdbcType=INTEGER}, #{amount,jdbcType=DECIMAL}, #{balance,jdbcType=DECIMAL}, #{bizCode,jdbcType=VARCHAR}, #{bizName,jdbcType=VARCHAR}, - #{createTime,jdbcType=TIMESTAMP}) + #{createTime,jdbcType=TIMESTAMP}, #{type,jdbcType=VARCHAR}) insert into tb_shop_user_flow @@ -55,6 +56,9 @@ create_time, + + type, + @@ -78,6 +82,9 @@ #{createTime,jdbcType=TIMESTAMP}, + + #{type,jdbcType=VARCHAR}, + @@ -101,6 +108,9 @@ create_time = #{createTime,jdbcType=TIMESTAMP}, + + type = #{type,jdbcType=VARCHAR}, + where id = #{id,jdbcType=INTEGER} @@ -111,17 +121,23 @@ balance = #{balance,jdbcType=DECIMAL}, biz_code = #{bizCode,jdbcType=VARCHAR}, biz_name = #{bizName,jdbcType=VARCHAR}, - create_time = #{createTime,jdbcType=TIMESTAMP} + create_time = #{createTime,jdbcType=TIMESTAMP}, + type = #{type,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} \ No newline at end of file diff --git a/src/main/resources/mapper/TbShopUserMapper.xml b/src/main/resources/mapper/TbShopUserMapper.xml index 690c5ac..0feb3d9 100644 --- a/src/main/resources/mapper/TbShopUserMapper.xml +++ b/src/main/resources/mapper/TbShopUserMapper.xml @@ -21,6 +21,7 @@ + @@ -35,7 +36,7 @@ id, amount, credit_amount, consume_amount, consume_number, level_consume, status, merchant_id, shop_id, user_id, parent_id, parent_level, name, head_img, sex, birth_day, telephone, is_vip, code, is_attention, attention_at, is_shareholder, level, distribute_type, - sort, created_at, updated_at, mini_open_id + sort, created_at, updated_at, mini_open_id,dynamic_code + + delete from tb_shop_user where id = #{id,jdbcType=VARCHAR} @@ -301,6 +309,15 @@ code = #{code,jdbcType=VARCHAR}, + + + + dynamic_code = #{dynamicCode,jdbcType=VARCHAR}, + + + dynamic_code = #{dynamicCode,jdbcType=VARCHAR}, + + is_attention = #{isAttention,jdbcType=TINYINT}, @@ -363,11 +380,53 @@ where id = #{id,jdbcType=VARCHAR} + + + update tb_shop_user + set + user_id = #{userId,jdbcType=VARCHAR}, + updated_at = #{updatedAt,jdbcType=BIGINT} + where id = #{id,jdbcType=VARCHAR} + + - + select * from tb_shop_user where telephone=#{phone} and shop_id=#{shopId} + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/TbShopVideoMapper.xml b/src/main/resources/mapper/TbShopVideoMapper.xml new file mode 100644 index 0000000..bf6fc25 --- /dev/null +++ b/src/main/resources/mapper/TbShopVideoMapper.xml @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + id + , shop_id, type, name, channel_id, source_id, source_url, status ,created_time, update_time + + + + + + + + + diff --git a/src/main/resources/mapper/TbSplitAccountsMapper.xml b/src/main/resources/mapper/TbSplitAccountsMapper.xml new file mode 100644 index 0000000..3fa0c72 --- /dev/null +++ b/src/main/resources/mapper/TbSplitAccountsMapper.xml @@ -0,0 +1,154 @@ + + + + + + + + + + + + + + + + + + id, merchant_id, shop_id, coupons_price, conpons_amount, is_split, order_amount, + create_time, split_time, trade_day,origin_amount + + + + delete from tb_split_accounts + where id = #{id,jdbcType=INTEGER} + + + insert into tb_split_accounts (id, merchant_id, shop_id, + coupons_price, conpons_amount, is_split, + order_amount, create_time, split_time, + trade_day,origin_amount) + values (#{id,jdbcType=INTEGER}, #{merchantId,jdbcType=INTEGER}, #{shopId,jdbcType=INTEGER}, + #{couponsPrice,jdbcType=DECIMAL}, #{conponsAmount,jdbcType=DECIMAL}, #{isSplit,jdbcType=VARCHAR}, + #{orderAmount,jdbcType=DECIMAL}, #{createTime,jdbcType=TIMESTAMP}, #{splitTime,jdbcType=TIMESTAMP}, + #{tradeDay,jdbcType=VARCHAR},#{originAmount,jdbcType=DECIMAL}) + + + insert into tb_split_accounts + + + id, + + + merchant_id, + + + shop_id, + + + coupons_price, + + + conpons_amount, + + + is_split, + + + order_amount, + + + create_time, + + + split_time, + + + trade_day, + + + + + #{id,jdbcType=INTEGER}, + + + #{merchantId,jdbcType=INTEGER}, + + + #{shopId,jdbcType=INTEGER}, + + + #{couponsPrice,jdbcType=DECIMAL}, + + + #{conponsAmount,jdbcType=DECIMAL}, + + + #{isSplit,jdbcType=VARCHAR}, + + + #{orderAmount,jdbcType=DECIMAL}, + + + #{createTime,jdbcType=TIMESTAMP}, + + + #{splitTime,jdbcType=TIMESTAMP}, + + + #{tradeDay,jdbcType=VARCHAR}, + + + + + update tb_split_accounts + + + merchant_id = #{merchantId,jdbcType=INTEGER}, + + + shop_id = #{shopId,jdbcType=INTEGER}, + + + coupons_price = #{couponsPrice,jdbcType=DECIMAL}, + + + conpons_amount = #{conponsAmount,jdbcType=DECIMAL}, + + + is_split = #{isSplit,jdbcType=VARCHAR}, + + + order_amount = #{orderAmount,jdbcType=DECIMAL}, + + + create_time = #{createTime,jdbcType=TIMESTAMP}, + + + split_time = #{splitTime,jdbcType=TIMESTAMP}, + + + trade_day = #{tradeDay,jdbcType=VARCHAR}, + + + where id = #{id,jdbcType=INTEGER} + + + update tb_split_accounts + set merchant_id = #{merchantId,jdbcType=INTEGER}, + shop_id = #{shopId,jdbcType=INTEGER}, + coupons_price = #{couponsPrice,jdbcType=DECIMAL}, + conpons_amount = #{conponsAmount,jdbcType=DECIMAL}, + is_split = #{isSplit,jdbcType=VARCHAR}, + order_amount = #{orderAmount,jdbcType=DECIMAL}, + create_time = #{createTime,jdbcType=TIMESTAMP}, + split_time = #{splitTime,jdbcType=TIMESTAMP}, + trade_day = #{tradeDay,jdbcType=VARCHAR} + where id = #{id,jdbcType=INTEGER} + + \ No newline at end of file diff --git a/src/main/resources/mapper/TbSystemCouponsMapper.xml b/src/main/resources/mapper/TbSystemCouponsMapper.xml new file mode 100644 index 0000000..115e91f --- /dev/null +++ b/src/main/resources/mapper/TbSystemCouponsMapper.xml @@ -0,0 +1,135 @@ + + + + + + + + + + + + + + + + id, name, coupons_price, coupons_amount, status, create_time, update_time, end_time,type_name + + + + + + delete from tb_system_coupons + where id = #{id,jdbcType=INTEGER} + + + insert into tb_system_coupons (id, name, coupons_price, + coupons_amount, status, create_time, + update_time, end_time,type_name) + values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{couponsPrice,jdbcType=DECIMAL}, + #{couponsAmount,jdbcType=DECIMAL}, #{status,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, + #{updateTime,jdbcType=TIMESTAMP}, #{endTime,jdbcType=TIMESTAMP}, #{typeName,jdbcType=VARCHAR}) + + + insert into tb_system_coupons + + + id, + + + name, + + + coupons_price, + + + coupons_amount, + + + status, + + + create_time, + + + update_time, + + + end_time, + + + + + #{id,jdbcType=INTEGER}, + + + #{name,jdbcType=VARCHAR}, + + + #{couponsPrice,jdbcType=DECIMAL}, + + + #{couponsAmount,jdbcType=DECIMAL}, + + + #{status,jdbcType=VARCHAR}, + + + #{createTime,jdbcType=TIMESTAMP}, + + + #{updateTime,jdbcType=TIMESTAMP}, + + + #{endTime,jdbcType=TIMESTAMP}, + + + + + update tb_system_coupons + + + name = #{name,jdbcType=VARCHAR}, + + + coupons_price = #{couponsPrice,jdbcType=DECIMAL}, + + + coupons_amount = #{couponsAmount,jdbcType=DECIMAL}, + + + status = #{status,jdbcType=VARCHAR}, + + + create_time = #{createTime,jdbcType=TIMESTAMP}, + + + update_time = #{updateTime,jdbcType=TIMESTAMP}, + + + end_time = #{endTime,jdbcType=TIMESTAMP}, + + + where id = #{id,jdbcType=INTEGER} + + + update tb_system_coupons + set name = #{name,jdbcType=VARCHAR}, + coupons_price = #{couponsPrice,jdbcType=DECIMAL}, + coupons_amount = #{couponsAmount,jdbcType=DECIMAL}, + status = #{status,jdbcType=VARCHAR}, + create_time = #{createTime,jdbcType=TIMESTAMP}, + update_time = #{updateTime,jdbcType=TIMESTAMP}, + end_time = #{endTime,jdbcType=TIMESTAMP} + where id = #{id,jdbcType=INTEGER} + + \ No newline at end of file diff --git a/src/main/resources/mapper/TbUserCouponsMapper.xml b/src/main/resources/mapper/TbUserCouponsMapper.xml new file mode 100644 index 0000000..b746d3c --- /dev/null +++ b/src/main/resources/mapper/TbUserCouponsMapper.xml @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + id, user_id, coupons_price, coupons_amount, status, create_time, update_time, end_time,is_double + + + + + + + delete from tb_user_coupons + where id = #{id,jdbcType=INTEGER} + + + insert into tb_user_coupons (id, user_id, coupons_price, + coupons_amount, status, create_time, + update_time, end_time,is_double) + values (#{id,jdbcType=INTEGER}, #{userId,jdbcType=VARCHAR}, #{couponsPrice,jdbcType=DECIMAL}, + #{couponsAmount,jdbcType=DECIMAL}, #{status,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, + #{updateTime,jdbcType=TIMESTAMP}, #{endTime,jdbcType=TIMESTAMP}, #{isDouble,jdbcType=VARCHAR}) + + + insert into tb_user_coupons + + + id, + + + user_id, + + + coupons_price, + + + coupons_amount, + + + status, + + + create_time, + + + update_time, + + + end_time, + + + + + #{id,jdbcType=INTEGER}, + + + #{userId,jdbcType=VARCHAR}, + + + #{couponsPrice,jdbcType=DECIMAL}, + + + #{couponsAmount,jdbcType=DECIMAL}, + + + #{status,jdbcType=VARCHAR}, + + + #{createTime,jdbcType=TIMESTAMP}, + + + #{updateTime,jdbcType=TIMESTAMP}, + + + #{endTime,jdbcType=TIMESTAMP}, + + + + + update tb_user_coupons + + + user_id = #{userId,jdbcType=VARCHAR}, + + + coupons_price = #{couponsPrice,jdbcType=DECIMAL}, + + + coupons_amount = #{couponsAmount,jdbcType=DECIMAL}, + + + status = #{status,jdbcType=VARCHAR}, + + + create_time = #{createTime,jdbcType=TIMESTAMP}, + + + update_time = #{updateTime,jdbcType=TIMESTAMP}, + + + end_time = #{endTime,jdbcType=TIMESTAMP}, + + + where id = #{id,jdbcType=INTEGER} + + + update tb_user_coupons + set user_id = #{userId,jdbcType=VARCHAR}, + coupons_price = #{couponsPrice,jdbcType=DECIMAL}, + coupons_amount = #{couponsAmount,jdbcType=DECIMAL}, + status = #{status,jdbcType=VARCHAR}, + create_time = #{createTime,jdbcType=TIMESTAMP}, + update_time = #{updateTime,jdbcType=TIMESTAMP}, + end_time = #{endTime,jdbcType=TIMESTAMP} + where id = #{id,jdbcType=INTEGER} + + \ No newline at end of file diff --git a/src/main/resources/mapper/TbUserInfoMapper.xml b/src/main/resources/mapper/TbUserInfoMapper.xml index 4e494b9..b6340e1 100644 --- a/src/main/resources/mapper/TbUserInfoMapper.xml +++ b/src/main/resources/mapper/TbUserInfoMapper.xml @@ -3,7 +3,6 @@ - @@ -49,15 +48,17 @@ + + - id,user_id, amount, charge_amount, line_of_credit, consume_amount, consume_number, total_score, + id, amount, charge_amount, line_of_credit, consume_amount, consume_number, total_score, lock_score, card_no, card_password, level_id, head_img, nick_name, telephone, wx_ma_app_id, birth_day, sex, mini_app_open_id, open_id, union_id, code, type, identify, status, parent_id, parent_level, parent_type, project_id, merchant_id, is_resource, is_online, is_vip, vip_effect_at, tips, source_path, is_sales_person, is_attention_mp, city, search_word, last_log_in_at, last_leave_at, created_at, updated_at, bind_parent_at, - grand_parent_id,password + grand_parent_id,password,is_pwd,pwd - - + \ No newline at end of file diff --git a/src/main/resources/mapper/TbWiningParamsMapper.xml b/src/main/resources/mapper/TbWiningParamsMapper.xml new file mode 100644 index 0000000..00f9f38 --- /dev/null +++ b/src/main/resources/mapper/TbWiningParamsMapper.xml @@ -0,0 +1,97 @@ + + + + + + + + + + + + + id, min_price, max_price, wining_num, wining_user_num,status + + + + + delete from tb_wining_params + where id = #{id,jdbcType=INTEGER} + + + insert into tb_wining_params (id, min_price, max_price, + wining_num, wining_user_num) + values (#{id,jdbcType=INTEGER}, #{minPrice,jdbcType=DECIMAL}, #{maxPrice,jdbcType=DECIMAL}, + #{winingNum,jdbcType=INTEGER}, #{winingUserNum,jdbcType=INTEGER}) + + + insert into tb_wining_params + + + id, + + + min_price, + + + max_price, + + + wining_num, + + + wining_user_num, + + + + + #{id,jdbcType=INTEGER}, + + + #{minPrice,jdbcType=DECIMAL}, + + + #{maxPrice,jdbcType=DECIMAL}, + + + #{winingNum,jdbcType=INTEGER}, + + + #{winingUserNum,jdbcType=INTEGER}, + + + + + update tb_wining_params + + + min_price = #{minPrice,jdbcType=DECIMAL}, + + + max_price = #{maxPrice,jdbcType=DECIMAL}, + + + wining_num = #{winingNum,jdbcType=INTEGER}, + + + wining_user_num = #{winingUserNum,jdbcType=INTEGER}, + + + where id = #{id,jdbcType=INTEGER} + + + update tb_wining_params + set min_price = #{minPrice,jdbcType=DECIMAL}, + max_price = #{maxPrice,jdbcType=DECIMAL}, + wining_num = #{winingNum,jdbcType=INTEGER}, + wining_user_num = #{winingUserNum,jdbcType=INTEGER} + where id = #{id,jdbcType=INTEGER} + + \ No newline at end of file diff --git a/src/main/resources/mapper/TbWiningUserMapper.xml b/src/main/resources/mapper/TbWiningUserMapper.xml new file mode 100644 index 0000000..99bc24d --- /dev/null +++ b/src/main/resources/mapper/TbWiningUserMapper.xml @@ -0,0 +1,180 @@ + + + + + + + + + + + + + + + + + + + id, user_name, order_no, order_amount, is_user, create_time, is_refund, refund_amount, + refund_no, refund_pay_type, trade_day, refund_time + + + + delete from tb_wining_user + where id = #{id,jdbcType=INTEGER} + + + insert into tb_wining_user (id, user_name, order_no, + order_amount, is_user, create_time, + is_refund, refund_amount, refund_no, + refund_pay_type, trade_day, refund_time + ) + values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{orderNo,jdbcType=VARCHAR}, + #{orderAmount,jdbcType=DECIMAL}, #{isUser,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, + #{isRefund,jdbcType=VARCHAR}, #{refundAmount,jdbcType=DECIMAL}, #{refundNo,jdbcType=VARCHAR}, + #{refundPayType,jdbcType=VARCHAR}, #{tradeDay,jdbcType=VARCHAR}, #{refundTime,jdbcType=TIMESTAMP} + ) + + + insert into tb_wining_user + + + id, + + + user_name, + + + order_no, + + + order_amount, + + + is_user, + + + create_time, + + + is_refund, + + + refund_amount, + + + refund_no, + + + refund_pay_type, + + + trade_day, + + + refund_time, + + + + + #{id,jdbcType=INTEGER}, + + + #{userName,jdbcType=VARCHAR}, + + + #{orderNo,jdbcType=VARCHAR}, + + + #{orderAmount,jdbcType=DECIMAL}, + + + #{isUser,jdbcType=VARCHAR}, + + + #{createTime,jdbcType=TIMESTAMP}, + + + #{isRefund,jdbcType=VARCHAR}, + + + #{refundAmount,jdbcType=DECIMAL}, + + + #{refundNo,jdbcType=VARCHAR}, + + + #{refundPayType,jdbcType=VARCHAR}, + + + #{tradeDay,jdbcType=VARCHAR}, + + + #{refundTime,jdbcType=TIMESTAMP}, + + + + + update tb_wining_user + + + user_name = #{userName,jdbcType=VARCHAR}, + + + order_no = #{orderNo,jdbcType=VARCHAR}, + + + order_amount = #{orderAmount,jdbcType=DECIMAL}, + + + is_user = #{isUser,jdbcType=VARCHAR}, + + + create_time = #{createTime,jdbcType=TIMESTAMP}, + + + is_refund = #{isRefund,jdbcType=VARCHAR}, + + + refund_amount = #{refundAmount,jdbcType=DECIMAL}, + + + refund_no = #{refundNo,jdbcType=VARCHAR}, + + + refund_pay_type = #{refundPayType,jdbcType=VARCHAR}, + + + trade_day = #{tradeDay,jdbcType=VARCHAR}, + + + refund_time = #{refundTime,jdbcType=TIMESTAMP}, + + + where id = #{id,jdbcType=INTEGER} + + + update tb_wining_user + set user_name = #{userName,jdbcType=VARCHAR}, + order_no = #{orderNo,jdbcType=VARCHAR}, + order_amount = #{orderAmount,jdbcType=DECIMAL}, + is_user = #{isUser,jdbcType=VARCHAR}, + create_time = #{createTime,jdbcType=TIMESTAMP}, + is_refund = #{isRefund,jdbcType=VARCHAR}, + refund_amount = #{refundAmount,jdbcType=DECIMAL}, + refund_no = #{refundNo,jdbcType=VARCHAR}, + refund_pay_type = #{refundPayType,jdbcType=VARCHAR}, + trade_day = #{tradeDay,jdbcType=VARCHAR}, + refund_time = #{refundTime,jdbcType=TIMESTAMP} + where id = #{id,jdbcType=INTEGER} + + + \ No newline at end of file diff --git a/src/main/resources/mapper/TbYhqParamsMapper.xml b/src/main/resources/mapper/TbYhqParamsMapper.xml new file mode 100644 index 0000000..6636929 --- /dev/null +++ b/src/main/resources/mapper/TbYhqParamsMapper.xml @@ -0,0 +1,96 @@ + + + + + + + + + + + + id, name, min_price, max_price, status + + + + + delete from tb_yhq_params + where id = #{id,jdbcType=INTEGER} + + + insert into tb_yhq_params (id, name, min_price, + max_price, status) + values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{minPrice,jdbcType=DECIMAL}, + #{maxPrice,jdbcType=DECIMAL}, #{status,jdbcType=VARCHAR}) + + + insert into tb_yhq_params + + + id, + + + name, + + + min_price, + + + max_price, + + + status, + + + + + #{id,jdbcType=INTEGER}, + + + #{name,jdbcType=VARCHAR}, + + + #{minPrice,jdbcType=DECIMAL}, + + + #{maxPrice,jdbcType=DECIMAL}, + + + #{status,jdbcType=VARCHAR}, + + + + + update tb_yhq_params + + + name = #{name,jdbcType=VARCHAR}, + + + min_price = #{minPrice,jdbcType=DECIMAL}, + + + max_price = #{maxPrice,jdbcType=DECIMAL}, + + + status = #{status,jdbcType=VARCHAR}, + + + where id = #{id,jdbcType=INTEGER} + + + update tb_yhq_params + set name = #{name,jdbcType=VARCHAR}, + min_price = #{minPrice,jdbcType=DECIMAL}, + max_price = #{maxPrice,jdbcType=DECIMAL}, + status = #{status,jdbcType=VARCHAR} + where id = #{id,jdbcType=INTEGER} + + \ No newline at end of file