Merge remote-tracking branch 'origin/yhq' into lyf

# Conflicts:
#	src/main/java/com/chaozhanggui/system/cashierservice/entity/TbShopInfo.java
#	src/main/java/com/chaozhanggui/system/cashierservice/entity/TbSystemCoupons.java
#	src/main/java/com/chaozhanggui/system/cashierservice/rabbit/RabbitConfig.java
#	src/main/java/com/chaozhanggui/system/cashierservice/rabbit/RabbitProducer.java
#	src/main/java/com/chaozhanggui/system/cashierservice/service/LoginService.java
#	src/main/java/com/chaozhanggui/system/cashierservice/util/RandomUtil.java
#	src/main/resources/application-dev.yml
#	src/main/resources/application-dev2.yml
#	src/main/resources/application-prod.yml
#	src/main/resources/application-prod2.yml
#	src/main/resources/mapper/TbShopInfoMapper.xml
This commit is contained in:
2024-04-15 14:51:15 +08:00
73 changed files with 3810 additions and 563 deletions

View File

@@ -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
@@ -50,4 +51,44 @@ 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) throws IOException {
return orderService.mineCoupons(userId,status,page,size);
}
@GetMapping("/findCoupons")
private Result findCoupons(@RequestHeader String token,@RequestParam 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("/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("/testPay")
// private Result testPay(@RequestParam Integer orderId){
// return orderService.testPay(orderId);
// }
}

View File

@@ -0,0 +1,101 @@
package com.chaozhanggui.system.cashierservice.controller;
import cn.binarywang.wx.miniapp.util.crypt.WxMaCryptUtils;
import cn.hutool.core.util.ObjectUtil;
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.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.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;
}
@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");
}
}

View File

@@ -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);
}

View File

@@ -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<TbIntegral> selectAllByUserId(String userId);
}

View File

@@ -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
@@ -32,5 +33,5 @@ public interface TbOrderInfoMapper {
@Param("size")Integer size, @Param("status") String status);
List<TbOrderInfo> selectByTradeDay(@Param("day") String day,@Param("minPrice") BigDecimal minPrice,@Param("maxPrice") BigDecimal maxPrice);
}

View File

@@ -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);
}

View File

@@ -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<TbReleaseFlow> selectByUserId(@Param("userId") String userId);
List<TbReleaseFlow> selectAll();
}

View File

@@ -1,5 +1,6 @@
package com.chaozhanggui.system.cashierservice.dao;
import com.chaozhanggui.system.cashierservice.entity.TbParams;
import com.chaozhanggui.system.cashierservice.entity.TbShopUser;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@@ -25,4 +26,8 @@ public interface TbShopUserMapper {
TbShopUser selectByUserId(@Param("userId") String userId);
TbShopUser selectByOpenId(@Param("openId") String openId);
TbParams selectParams();
}

View File

@@ -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);
}

View File

@@ -0,0 +1,22 @@
package com.chaozhanggui.system.cashierservice.dao;
import com.chaozhanggui.system.cashierservice.entity.TbSystemCoupons;
import org.apache.ibatis.annotations.Param;
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<TbSystemCoupons> selectAll(@Param("type") String type);
}

View File

@@ -0,0 +1,28 @@
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.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<TbUserCoupons> selectByUserId(@Param("userId") String userId,@Param("status") String status);
TbUserCoupons selectByOrderId(@Param("orderId") Integer orderId);
}

View File

@@ -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 {
@@ -38,4 +40,5 @@ public interface TbUserInfoMapper {
TbUserInfo selectByPhone(String phone);
List<TbUserInfo> selectAll();
}

View File

@@ -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<TbWiningParams> selectAll();
}

View File

@@ -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<TbWiningUser> selectAllByTrade(@Param("day") String day);
}

View File

@@ -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<TbYhqParams> selectAll();
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -95,6 +95,8 @@ 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<TbOrderDetail> detailList;

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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;
@@ -95,378 +99,10 @@ public class TbShopInfo implements Serializable {
* 商家二维码
*/
private String shopQrcode;
private String isOpenYhq;
/**
* 商户标签
*/
private String tag;
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getShopQrcode() {
return shopQrcode;
}
public void setShopQrcode(String shopQrcode) {
this.shopQrcode = shopQrcode;
}
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();
}
}

View File

@@ -0,0 +1,33 @@
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;
private Integer shopId;
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;
}

View File

@@ -1,107 +1,30 @@
package com.chaozhanggui.system.cashierservice.entity;
import java.util.Date;
import java.io.Serializable;
import lombok.Data;
/**
* (TbSystemCoupons)实体类
*
* @author lyf
* @since 2024-04-09 18:27:08
*/
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
@Data
public class TbSystemCoupons implements Serializable {
private static final long serialVersionUID = -42549701370854624L;
private Integer id;
private String name;
private Double couponsPrice;
private Double couponsAmount;
private BigDecimal couponsPrice;
private BigDecimal couponsAmount;
private String status;
private String typeName;
private Date createTime;
private Date updateTime;
private Date endTime;
private Integer dayNum;
private Date endTime;
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 Double getCouponsPrice() {
return couponsPrice;
}
public void setCouponsPrice(Double couponsPrice) {
this.couponsPrice = couponsPrice;
}
public Double getCouponsAmount() {
return couponsAmount;
}
public void setCouponsAmount(Double couponsAmount) {
this.couponsAmount = couponsAmount;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
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 Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public Integer getDayNum() {
return dayNum;
}
public void setDayNum(Integer dayNum) {
this.dayNum = dayNum;
}
}
private static final long serialVersionUID = 1L;
}

View File

@@ -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 TbUserCoupons implements Serializable {
private Integer id;
private String userId;
private Integer orderId;
private BigDecimal couponsPrice;
private BigDecimal couponsAmount;
private String status;
private String isDouble;
private Date createTime;
private Date updateTime;
private Date endTime;
private static final long serialVersionUID = 1L;
}

View File

@@ -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;
}

View File

@@ -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 = "false";
this.refundAmount = BigDecimal.ZERO;
this.refundPayType = "WX";
}
}

View File

@@ -0,0 +1,58 @@
package com.chaozhanggui.system.cashierservice.entity;
import java.io.Serializable;
import java.math.BigDecimal;
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;
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 == null ? null : name.trim();
}
public BigDecimal getMinPrice() {
return minPrice;
}
public void setMinPrice(BigDecimal minPrice) {
this.minPrice = minPrice;
}
public BigDecimal getMaxPrice() {
return maxPrice;
}
public void setMaxPrice(BigDecimal maxPrice) {
this.maxPrice = maxPrice;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status == null ? null : status.trim();
}
}

View File

@@ -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;
}

View File

@@ -0,0 +1,19 @@
package com.chaozhanggui.system.cashierservice.entity.vo;
import com.chaozhanggui.system.cashierservice.entity.TbOrderDetail;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
/**
* @author lyf
*/
@Data
public class IntegralVo {
private String openId;
private BigDecimal num;
private String type;
private String sign;
}

View File

@@ -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;
}
}

View File

@@ -0,0 +1,155 @@
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<ObjectError> 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<ConstraintViolation<?>> 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.failure(DefaultError.BUSINESS_ERROR);
response.setMsg(e.getMessage());
return new ResponseEntity<>(response, HttpStatus.OK);
}
}

View File

@@ -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);
}

View File

@@ -1,6 +1,7 @@
package com.chaozhanggui.system.cashierservice.interceptor;
import ch.qos.logback.classic.turbo.TurboFilter;
import com.chaozhanggui.system.cashierservice.exception.MsgException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

View File

@@ -0,0 +1,41 @@
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.exception.MsgException;
import com.chaozhanggui.system.cashierservice.redis.RedisCst;
import com.chaozhanggui.system.cashierservice.redis.RedisUtil;
import com.chaozhanggui.system.cashierservice.service.CartService;
import com.chaozhanggui.system.cashierservice.service.IntegralService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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();
}
}
}

View File

@@ -62,7 +62,20 @@ public class RabbitConfig {
public Binding bindingPut_Register() {
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);
}

View File

@@ -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";
}

View File

@@ -17,7 +17,6 @@ public class RabbitProducer implements RabbitTemplate.ConfirmCallback {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private RabbitTemplate rabbitTemplate;
@Value("${prod}")
private String prod;
@Autowired
@@ -39,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);

View File

@@ -15,5 +15,6 @@ public class RedisCst {
public static final String TABLE_CART = "TABLE:CART:";
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";
}

View File

@@ -1,5 +1,7 @@
package com.chaozhanggui.system.cashierservice.redis;
import com.chaozhanggui.system.cashierservice.socket.AppWebSocketServer;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
@@ -7,6 +9,7 @@ import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.io.*;
import java.util.*;
/**
@@ -17,7 +20,7 @@ import java.util.*;
* @Description redis工具类
*/
@Component
public class RedisUtil {
public class RedisUtil{
// 成功标识
private static final int REDIS_SUCCESS = 1;
// 失败标识
@@ -480,4 +483,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 <T> List<AppWebSocketServer> deserializeJson(String json, Class<T> 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<String> getSet(String key ){
Jedis jedis = null ;
Set<String> 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 ;
}
}

View File

@@ -16,6 +16,7 @@ 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.N;
import com.chaozhanggui.system.cashierservice.util.SnowFlakeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
@@ -54,7 +55,10 @@ public class CartService {
private TbOrderDetailMapper orderDetailMapper;
@Autowired
private TbShopTableMapper shopTableMapper;
@Autowired
private TbUserCouponsMapper userCouponsMapper;
@Autowired
private TbSystemCouponsMapper systemCouponsMapper;
// @Transactional(rollbackFor = Exception.class)
public void createCart(JSONObject jsonObject) throws Exception {
@@ -202,23 +206,35 @@ public class CartService {
@Transactional(rollbackFor = Exception.class)
public void createOrder(JSONObject jsonObject) throws IOException {
try {
String shopId = jsonObject.getString("shopId");
JSONArray array = JSON.parseArray(redisUtil.getMessage(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId))));
//总金额
List<Integer> ids = new ArrayList<>();
BigDecimal totalAmount = BigDecimal.ZERO;
BigDecimal packAMount = BigDecimal.ZERO;
BigDecimal originAmount = BigDecimal.ZERO;
BigDecimal saleAmount = BigDecimal.ZERO;
String couponId = "";
BigDecimal couponAmount = BigDecimal.ZERO;
Map<Integer, TbProductSku> skuMap = new HashMap<>();
List<TbOrderDetail> orderDetails = new ArrayList<>();
Integer orderId = 0;
TbMerchantAccount tbMerchantAccount = merchantAccountMapper.selectByShopId(jsonObject.getString("shopId"));
if (tbMerchantAccount == null) {
throw new MsgException("生成订单错误");
}
String userId = jsonObject.getString("userId");
TbUserInfo tbUserInfo = userInfoMapper.selectByPrimaryKey(Integer.valueOf(userId));
if (tbUserInfo == null) {
throw new MsgException("生成订单失败");
}
for (int i = 0; i < array.size(); i++) {
JSONObject object = array.getJSONObject(i);
TbCashierCart cashierCart = JSONUtil.parseJSONStr2T(object.toJSONString(), TbCashierCart.class);
TbProductSkuWithBLOBs tbProduct = productSkuMapper.selectByPrimaryKey(Integer.valueOf(cashierCart.getSkuId()));
totalAmount = totalAmount.add(cashierCart.getTotalAmount());
packAMount = packAMount.add(cashierCart.getPackFee());
originAmount = originAmount.add(cashierCart.getTotalAmount());
if (Objects.nonNull(tbProduct)) {
saleAmount = saleAmount.add(tbProduct.getSalePrice());
}
@@ -249,19 +265,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", "");
AppWebSocketServer.AppSendInfo(jsonObject1, jsonObject.getString("userId"), true);
log.info("消息推送");
return;
}
if (N.gt(systemCoupons.getCouponsAmount(), totalAmount)) {
log.info("开始处理订单");
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("status", "fail");
jsonObject1.put("msg", "订单金额小于优惠价金额");
jsonObject1.put("type", jsonObject.getString("type"));
jsonObject1.put("data", "");
AppWebSocketServer.AppSendInfo(jsonObject1, jsonObject.getString("userId"), true);
log.info("消息推送");
return;
}
totalAmount = totalAmount.add(systemCoupons.getCouponsPrice()).subtract(systemCoupons.getCouponsAmount());
originAmount = originAmount.add(systemCoupons.getCouponsPrice());
couponAmount = systemCoupons.getCouponsAmount();
systemCoupons.setStatus("1");
systemCouponsMapper.updateByPrimaryKeySelective(systemCoupons);
TbUserCoupons userCoupons = new TbUserCoupons();
userCoupons.setEndTime(DateUtils.getNewDate(new Date(), 3, systemCoupons.getDayNum()));
userCoupons.setCouponsAmount(systemCoupons.getCouponsAmount());
userCoupons.setCouponsPrice(systemCoupons.getCouponsPrice());
userCoupons.setStatus("1");
userCoupons.setUserId(userId);
userCoupons.setCreateTime(new Date());
userCouponsMapper.insert(userCoupons);
couponId = userCoupons.getId() + "";
couponAmount = userCoupons.getCouponsAmount();
} else {
TbUserCoupons userCoupons = userCouponsMapper.selectByPrimaryKey(couponsId);
if (Objects.isNull(userCoupons) || !userCoupons.getStatus().equals("0")) {
log.info("开始处理订单");
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("status", "fail");
jsonObject1.put("msg", "优惠券已使用");
jsonObject1.put("type", jsonObject.getString("type"));
jsonObject1.put("data", "");
AppWebSocketServer.AppSendInfo(jsonObject1, jsonObject.getString("userId"), true);
log.info("消息推送");
return;
}
if (N.gt(userCoupons.getCouponsAmount(), totalAmount)) {
log.info("开始处理订单");
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("status", "fail");
jsonObject1.put("msg", "订单金额小于优惠价金额");
jsonObject1.put("type", jsonObject.getString("type"));
jsonObject1.put("data", "");
AppWebSocketServer.AppSendInfo(jsonObject1, 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())) {
@@ -279,40 +364,24 @@ 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);
orderInfoMapper.insert(orderInfo);
orderId = orderInfo.getId();
}
@@ -351,12 +420,45 @@ public class CartService {
e.getMessage();
}
}
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) throws IOException {
String shopId = jsonObject.getString("shopId");
if (redisUtil.exists(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId)))) {

View File

@@ -0,0 +1,111 @@
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 TbCashierCartMapper cashierCartMapper;
@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);
}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.getPayAmount().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);
}
}
}

View File

@@ -3,17 +3,25 @@ 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.DateUtils;
import com.chaozhanggui.system.cashierservice.util.N;
import com.chaozhanggui.system.cashierservice.util.RedisUtils;
import com.chaozhanggui.system.cashierservice.util.SnowFlakeUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -22,9 +30,13 @@ import javax.annotation.Resource;
import java.awt.print.Pageable;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
* @author 12847
@@ -33,7 +45,7 @@ import java.util.List;
public class OrderService {
@Resource
private TbCashierCartMapper cashierCartMapper;
private RabbitProducer producer;
@Resource
private TbOrderInfoMapper orderInfoMapper;
@@ -48,18 +60,35 @@ 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;
/**
* 创建订单
*
* @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<CashierCarVo> cashierCarVoList = cashierCartMapper.selectByTableIdOpen(tableId);
// if (cashierCarVoList.isEmpty()){
@@ -139,26 +168,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<TbOrderDetail> details= tbOrderDetailMapper.selectAllByOrderId(orderId);
if(ObjectUtil.isEmpty(details)||details.size()<=0){
List<TbOrderDetail> details = tbOrderDetailMapper.selectAllByOrderId(orderId);
if (ObjectUtil.isEmpty(details) || details.size() <= 0) {
return Result.fail("未找到订单");
}
@@ -171,37 +199,37 @@ public class OrderService {
orderVo.setOrderNo(orderInfo.getOrderNo());
orderVo.setTime(orderInfo.getCreatedAt());
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());
return Result.success(CodeEnum.ENCRYPT,orderVo);
return Result.success(CodeEnum.ENCRYPT, orderVo);
}
public Result orderList(Integer userId,Integer page,Integer size,String status){
public Result orderList(Integer userId, Integer page, Integer size, String status) {
TbUserInfo tbUserInfo = userInfoMapper.selectByPrimaryKey(userId);
if (tbUserInfo == null){
if (tbUserInfo == null) {
return Result.fail("生成订单失败");
}
//获取页码号
int beginNo;
if(page <=0){
if (page <= 0) {
beginNo = 0;
}else{
} else {
beginNo = (page - 1) * size;
}
List<TbOrderInfo> tbOrderInfos = orderInfoMapper.selectByUserId(userId, beginNo, size,status);
List<TbOrderInfo> tbOrderInfos = orderInfoMapper.selectByUserId(userId, beginNo, size, status);
for (TbOrderInfo orderInfo:tbOrderInfos){
List<TbOrderDetail> 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) {
List<TbOrderDetail> 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, tbOrderInfos);
}
@@ -225,10 +253,149 @@ public class OrderService {
// redisUtil.seckill(tableId,message);
// AppWebSocketServer.onClosed(tableId);
List<TbProductSku> 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(), productSku.getStockNumber().intValue() + "");
}
}
@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<TbYhqParams> 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 status, Integer page, Integer size) {
PageHelper.startPage(page, size);
List<TbUserCoupons> list = userCouponsMapper.selectByUserId(userId,status);
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<TbSystemCoupons> list = systemCouponsMapper.selectAll(type);
PageInfo pageInfo = new PageInfo(list);
return Result.success(CodeEnum.SUCCESS, pageInfo);
}
public Result findWiningUser() {
String day = DateUtils.getDay();
List<TbWiningUser> list = tbWiningUserMapper.selectAllByTrade(day);
return Result.success(CodeEnum.SUCCESS, list);
}
public Result getYhqPara() {
List<TbYhqParams> 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);
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);
}
}
}

View File

@@ -246,7 +246,11 @@ public class PayService {
log.info("发送打印数据");
producer.printMechine(orderInfo.getId() + "");
log.info("发送赠送购物券");
JSONObject coupons = new JSONObject();
coupons.put("type","buy");
coupons.put("orderId",orderId);
producer.printCoupons(coupons.toJSONString());
return Result.success(CodeEnum.SUCCESS,orderId);
case "2": //退款成功
cartStatus="refund";

View File

@@ -0,0 +1,221 @@
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
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<TbReleaseFlow> 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<TbReleaseFlow> 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<TbUserInfo> 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;
}
}

View File

@@ -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;
@@ -143,4 +144,12 @@ public class Result {
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;
}
}

View File

@@ -23,7 +23,7 @@ import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@@ -105,6 +105,7 @@ public class AppWebSocketServer {
if (webSocketMap.containsKey(tableId + "-" + shopId)) {
List<AppWebSocketServer> serverList = webSocketMap.get(tableId + "-" + shopId);
serverList.add(this);
} else {
List<AppWebSocketServer> serverList = new ArrayList<>();
serverList.add(this);
@@ -311,4 +312,26 @@ public class AppWebSocketServer {
public static synchronized ConcurrentHashMap<String, List<JSONObject>> getRecordMap() {
return AppWebSocketServer.recordMap;
}
private byte[] serialize(Object obj) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private Object deserialize(byte[] bytes) {
try {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
return ois.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
}

View File

@@ -0,0 +1,311 @@
//package com.chaozhanggui.system.cashierservice.socket;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONObject;
//import com.chaozhanggui.system.cashierservice.config.WebSocketCustomEncoding;
//import com.chaozhanggui.system.cashierservice.dao.TbShopTableMapper;
//import com.chaozhanggui.system.cashierservice.entity.TbShopTable;
//import com.chaozhanggui.system.cashierservice.rabbit.RabbitProducer;
//import com.chaozhanggui.system.cashierservice.redis.RedisCst;
//import com.chaozhanggui.system.cashierservice.redis.RedisUtil;
//import com.chaozhanggui.system.cashierservice.util.SpringUtils;
//import lombok.Data;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.PostConstruct;
//import javax.annotation.Resource;
//import javax.websocket.*;
//import javax.websocket.server.PathParam;
//import javax.websocket.server.ServerEndpoint;
//import java.io.IOException;
//import java.math.BigDecimal;
//import java.util.*;
//import java.util.concurrent.ConcurrentHashMap;
//import java.util.concurrent.atomic.AtomicBoolean;
//
//@ServerEndpoint(value = "/websocket/table/{tableId}/{shopId}/{userId}", encoders = WebSocketCustomEncoding.class)
//@Component
//@Slf4j
//@Data
//public class AppWebSocketServerCopy {
//
//
// @Resource
// private RabbitProducer a;
//
// //注入为空
// public static RabbitProducer rabbitProducer;
//
// @PostConstruct
// public void b() {
// rabbitProducer = this.a;
// }
//
//
// private RedisUtil redisUtils = SpringUtils.getBean(RedisUtil.class);
// private TbShopTableMapper shopTableMapper = SpringUtils.getBean(TbShopTableMapper.class);
// /**
// * concurrent包的线程安全Set用来存放每个客户端对应的MyWebSocket对象。
// */
// //一个 AppWebSocketServer 就是一个用户一个tableId下有一个 List<AppWebSocketServer> 也就是多个用户
// private static ConcurrentHashMap<String, List<AppWebSocketServerCopy>> webSocketMap = new ConcurrentHashMap<>();
// public static ConcurrentHashMap<String, Set<String>> userMap = new ConcurrentHashMap<>();
// private static ConcurrentHashMap<String, AppWebSocketServerCopy> userSocketMap = new ConcurrentHashMap<>();
// //购物车的记录,用于第一次扫码的人同步购物车
// private static ConcurrentHashMap<String, List<JSONObject>> recordMap = new ConcurrentHashMap<>();
// private static ConcurrentHashMap<String, Session> 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<AppWebSocketServerCopy> serverList = webSocketMap.get(tableId + "-" + shopId);
// serverList.add(this);
// } else {
// List<AppWebSocketServerCopy> serverList = new ArrayList<>();
// serverList.add(this);
// webSocketMap.put(tableId + "-" + shopId, serverList);
// }
// if (userMap.containsKey(tableId + "-" + shopId)) {
// Set<String> userSet = userMap.get(tableId + "-" + shopId);
// userSet.add(userId);
// } else {
// Set<String> 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<AppWebSocketServerCopy> serverList = webSocketMap.get(tableId + "-" + shopId);
// if (serverList.isEmpty()) {
// webSocketMap.remove(tableId + "-" + shopId);
// }
// serverList.remove(this);
//
// }
// if (userMap.containsKey(tableId + "-" + shopId)){
// Set<String> userSet = userMap.get(tableId + "-" + shopId);
// if (userSet.isEmpty()){
// userMap.remove(tableId + "-" + shopId);
// }
// userSet.remove(userId);
// }
// }
// public static void onClosed(String user) throws IOException {
// Session session1 = sessionMap.get(user);
// session1.close();
// }
// /**
// * 收到客户端消息后调用的方法
// *
// * @param message 客户端发送过来的消息
// */
// @OnMessage
// public void onMessage(String message, Session session) {
//
// System.out.println(message);
// //可以群发消息
// //消息保存到数据库、redis
// if (StringUtils.isNotBlank(message) && !message.equals("undefined")) {
// try {
// //解析发送的报文
// JSONObject jsonObject = new JSONObject();
// if (StringUtils.isNotEmpty(message)) {
// jsonObject = JSONObject.parseObject(message);
// }
// //追加发送人(防止串改)
// jsonObject.put("tableId", this.tableId);
// jsonObject.put("shopId", this.shopId);
//
// //这里采用责任链模式,每一个处理器对应一个前段发过来的请,这里还可以用工厂模式来生成对象
//// ChangeHandler changeHandler = new ChangeHandler();
//// CreateOrderHandler createOrderHandler = new CreateOrderHandler();
//// SyncHandler syncHandler = new SyncHandler();
//// ClearHandler clearHandler = new ClearHandler();
//// OtherHandler otherHandler = new OtherHandler();
////
//// changeHandler.addNextHandler(syncHandler).addNextHandler(createOrderHandler).addNextHandler(clearHandler).addNextHandler(otherHandler);
//// changeHandler.handleRequest(webSocketMap,jsonObject,recordMap,this);
// if ("sku".equals(jsonObject.getString("type"))){
// boolean exist = redisUtils.exists(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId)));
// Integer num = 0;
// if (exist){
// JSONArray array = JSON.parseArray(redisUtils.getMessage(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId").concat("-").concat(shopId))));
// for (int i = 0; i < array.size(); i++) {
// JSONObject object = array.getJSONObject(i);
// if (object.getString("skuId").equals(jsonObject.getString("skuId"))) {
// num = object.getIntValue("totalNumber");
// break;
// }
// }
// }
// JSONObject jsonObject1 = new JSONObject();
// jsonObject1.put("status", "success");
// jsonObject1.put("msg", "成功");
// jsonObject1.put("type", "sku");
// jsonObject1.put("data", new ArrayList<>());
// jsonObject1.put("amount", num);
// sendMessage(jsonObject1);
// }else {
// rabbitProducer.putCart(jsonObject.toJSONString());
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// }
//
// /**
// * 发生错误时候
// *
// * @param session
// * @param error
// */
// @OnError
// public void onError(Session session, Throwable error) {
// log.error("用户错误:" + this.tableId + ",原因:" + error.getMessage());
// error.printStackTrace();
// }
//
// /**
// * 实现服务器主动推送
// */
// public void sendMessage(Object message) throws IOException {
// //加入线程锁
// synchronized (session) {
// try {
// //同步发送信息
// this.session.getBasicRemote().sendObject(message);
// } catch (Exception e) {
// log.error("服务器推送失败:" + e.getMessage());
// }
// }
// }
//
//
// /**
// * 发送自定义消息
// * */
// /**
// * 发送自定义消息
// *
// * @param message 发送的信息
// * @param tableId 如果为null默认发送所有
// * @throws IOException
// */
// public static void AppSendInfo(Object message, String tableId, boolean userFlag) throws IOException {
// if (userFlag) {
// if (userSocketMap.containsKey(tableId)) {
// AppWebSocketServerCopy server = userSocketMap.get(tableId);
// server.sendMessage(message);
// } else {
// log.error("请求的userId:" + tableId + "不在该服务器上");
// }
// } else {
// if (StringUtils.isEmpty(tableId)) {
// // 向所有用户发送信息
// for (List<AppWebSocketServerCopy> serverList : webSocketMap.values()) {
// for (AppWebSocketServerCopy server : serverList) {
// server.sendMessage(message);
// }
// }
// } else if (webSocketMap.containsKey(tableId)) {
// // 发送给指定用户信息
// List<AppWebSocketServerCopy> serverList = webSocketMap.get(tableId);
// for (AppWebSocketServerCopy server : serverList) {
// server.sendMessage(message);
// }
// } else {
// log.error("请求的tableId:" + tableId + "不在该服务器上");
// }
// }
//
// }
//
//
// public static synchronized ConcurrentHashMap<String, List<AppWebSocketServerCopy>> getWebSocketMap() {
// return AppWebSocketServerCopy.webSocketMap;
// }
//
// public static synchronized ConcurrentHashMap<String, List<JSONObject>> getRecordMap() {
// return AppWebSocketServerCopy.recordMap;
// }
//}

View File

@@ -0,0 +1,14 @@
package com.chaozhanggui.system.cashierservice.socket;
import lombok.Data;
import javax.websocket.Session;
import java.io.Serializable;
@Data
public class SocketSession implements Serializable {
private Session session;
private String tableId ;
private String shopId ;
private String userId ;
}

View File

@@ -0,0 +1,151 @@
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;
//更新订单状态
// @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(fixedRate = 200000)
public void winningUser() {
String day = DateUtils.getDay();
List<TbWiningParams> list = winingParamsMapper.selectAll();
ThreadPoolExecutor es = new ThreadPoolExecutor(5, 10, 60L, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(), 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<TbOrderInfo> list = orderInfoMapper.selectByTradeDay(day, winingParams.getMinPrice(), winingParams.getMaxPrice());
int num = winingParams.getWiningUserNum();
List<TbOrderInfo> newList = new ArrayList<>();
Map<Integer, Integer> 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.getTimes(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);
}
} 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;
}
}

View File

@@ -0,0 +1,14 @@
package com.chaozhanggui.system.cashierservice.util;
import java.util.HashMap;
import java.util.Map;
public interface CacheMap {
Map<String,String> map = new HashMap(){{
put("sign","1");
}};
Map<String,String> notOpenMap = new HashMap(){{
put("sign","1");
put("openId","1");
}};
}

View File

@@ -105,7 +105,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)

View File

@@ -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;
}
}

View File

@@ -1,6 +1,10 @@
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
@@ -33,4 +37,24 @@ public class RandomUtil {
return random.nextInt(46) + 1;
}
//获取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<TbOrderInfo> list, Map<Integer,Integer> 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); // 返回对应索引的用户
}
}