Merge remote-tracking branch 'origin/test' into test

# Conflicts:
#	src/main/java/com/chaozhanggui/system/cashierservice/entity/TbShopUser.java
#	src/main/java/com/chaozhanggui/system/cashierservice/service/ProductService.java
This commit is contained in:
GYJ
2024-11-01 10:18:53 +08:00
248 changed files with 11179 additions and 9714 deletions

View File

@@ -1,156 +0,0 @@
//package com.chaozhanggui.system.cashierservice.service;
//
//import com.chaozhanggui.system.cashierservice.dao.TbCashierCartMapper;
//import com.chaozhanggui.system.cashierservice.dao.TbProductMapper;
//import com.chaozhanggui.system.cashierservice.dao.TbProductSkuMapper;
//import com.chaozhanggui.system.cashierservice.entity.TbCashierCart;
//import com.chaozhanggui.system.cashierservice.entity.TbProduct;
//import com.chaozhanggui.system.cashierservice.entity.TbProductSku;
//import com.chaozhanggui.system.cashierservice.entity.dto.ProductCartDto;
//import com.chaozhanggui.system.cashierservice.entity.vo.CashierCarVo;
//import com.chaozhanggui.system.cashierservice.exception.MsgException;
//import com.chaozhanggui.system.cashierservice.sign.CodeEnum;
//import com.chaozhanggui.system.cashierservice.sign.Result;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.BeanUtils;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import javax.annotation.Resource;
//import java.math.BigDecimal;
//import java.time.Instant;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//
///**
// * @author lyf
// */
//@Service
//@Slf4j
//public class CashierCartService {
// @Resource
// private TbCashierCartMapper cashierCartMapper;
// @Resource
// private TbProductMapper productMapper;
// @Resource
// private TbProductSkuMapper productSkuMapper;
//
// /**
// * 增加购物车
// * @param productCartDto
// * @return
// */
// @Transactional(rollbackFor = Exception.class)
// public Result batchAdd(ProductCartDto productCartDto){
// //首先确认金额
// TbProduct tbProduct = productMapper.selectById(Integer.valueOf(productCartDto.getProductId()));
// if (tbProduct == null){
// return Result.fail("商品信息不存在");
// }
//
// TbCashierCart cashierCart = cashierCartMapper.selectByProduct(productCartDto.getProductId(), productCartDto.getTableId());
// if (cashierCart != null){
// if ("add".equals(productCartDto.getType())){
// TbCashierCart cashierCartNow = new TbCashierCart();
// cashierCartNow.setNumber(cashierCart.getNumber()+1F);
// cashierCartNow.setId(cashierCart.getId());
// cashierCartMapper.updateByPrimaryKeySelective(cashierCartNow);
// return Result.success(CodeEnum.ENCRYPT);
// }else if ("minus".equals(productCartDto.getType())){
// TbCashierCart cashierCartNow = new TbCashierCart();
// cashierCartNow.setNumber(cashierCart.getNumber()-1F);
// cashierCartNow.setId(cashierCart.getId());
// if (cashierCartNow.getNumber() == 0F){
// cashierCartNow.setStatus("clear");
// cashierCartMapper.updateByPrimaryKeySelective(cashierCartNow);
// return Result.success(CodeEnum.ENCRYPT);
// }
// cashierCartMapper.updateByPrimaryKeySelective(cashierCartNow);
// return Result.success(CodeEnum.ENCRYPT);
// }else {
// throw new MsgException("添加购物车失败");
// }
// }
// //增加新的购物车
// TbCashierCart tbCashierCart = new TbCashierCart();
// BeanUtils.copyProperties(productCartDto,tbCashierCart);
// tbCashierCart.setSalePrice(tbProduct.getLowPrice());
// tbCashierCart.setCreatedAt(Instant.now().toEpochMilli());
// tbCashierCart.setUpdatedAt(Instant.now().toEpochMilli());
// tbCashierCart.setTotalNumber(0.00F);
// tbCashierCart.setRefundNumber(0.00F);
// tbCashierCart.setType((byte) 0);
// tbCashierCart.setSkuId(productCartDto.getSkuInfo());
// //购物车状态打开
// tbCashierCart.setStatus("open");
//
// int insert = cashierCartMapper.insertSelective(tbCashierCart);
// if (insert>0){
// return Result.success(CodeEnum.SUCCESS);
// }
// throw new MsgException("添加购物车失败");
// }
//
//
// public Result cartList(Integer tableId){
// HashMap<String, Object> map = new HashMap<>();
// List<TbCashierCart> tbCashierCarts = cashierCartMapper.selectByTableId(tableId);
// BigDecimal total = new BigDecimal("0.00");
// for (TbCashierCart date :tbCashierCarts) {
// Float number = date.getNumber();
// BigDecimal bigDecimalValue = new BigDecimal(number.toString());
// total=total.add(bigDecimalValue.multiply(date.getSalePrice()));
// }
//
// map.put("cartList",tbCashierCarts);
// map.put("total",total);
//
// return Result.success(CodeEnum.ENCRYPT,map);
//
// }
// @Transactional(rollbackFor = Exception.class)
// public Result updateNumber(Integer tableId,String type){
// TbCashierCart cashierCart = cashierCartMapper.selectByPrimaryKey(tableId);
// if (cashierCart == null){
// return Result.fail("商品不存在");
// }
// if ("add".equals(type)){
// TbCashierCart cashierCartNow = new TbCashierCart();
// cashierCartNow.setNumber(cashierCart.getNumber()+1F);
// cashierCartNow.setId(cashierCart.getId());
// cashierCartMapper.updateByPrimaryKeySelective(cashierCartNow);
// return Result.success(CodeEnum.ENCRYPT);
// }else if ("minus".equals(type)){
// TbCashierCart cashierCartNow = new TbCashierCart();
// cashierCartNow.setNumber(cashierCart.getNumber()-1F);
// cashierCartNow.setId(cashierCart.getId());
// if (cashierCartNow.getNumber() == 0F){
// cashierCartNow.setStatus("clear");
// cashierCartMapper.updateByPrimaryKeySelective(cashierCartNow);
// return Result.success(CodeEnum.ENCRYPT);
// }
// cashierCartMapper.updateByPrimaryKeySelective(cashierCartNow);
// return Result.success(CodeEnum.ENCRYPT);
// }else {
// throw new MsgException("更改商品失败");
// }
//
// }
// @Transactional(rollbackFor = Exception.class)
// public Result clearCart(Integer tableId){
// List<CashierCarVo> cashierCarVos = cashierCartMapper.selectByTableIdOpen(tableId);
// if (cashierCarVos.isEmpty()){
// return Result.fail("购物车内无商品");
// }
// List<Integer> ids = new ArrayList<>();
// for (CashierCarVo date :cashierCarVos) {
// ids.add(date.getId());
// }
// int i = cashierCartMapper.updateByIdsStatus(ids, Instant.now().toEpochMilli());
// if (i != ids.size()){
// throw new MsgException("清空购物车失败");
// }
// return Result.success(CodeEnum.ENCRYPT);
// }
//}

View File

@@ -2,7 +2,7 @@ package com.chaozhanggui.system.cashierservice.service;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import cn.hutool.core.util.StrUtil;
import com.chaozhanggui.system.cashierservice.dao.*;
import com.chaozhanggui.system.cashierservice.entity.*;
import com.chaozhanggui.system.cashierservice.model.CategoryInfo;
@@ -46,9 +46,7 @@ public class CloudPrinterService {
private TbOrderDetailMapper tbOrderDetailMapper;
public Result printReceipt(String type,String orderId,Boolean ispre){
public Result printReceipt(String type, String orderId, Boolean ispre) {
try {
@@ -71,7 +69,7 @@ public class CloudPrinterService {
return Result.fail("此店铺没有对应的打印机设备");
}
list.parallelStream().forEach(tbPrintMachineWithBLOBs->{
list.parallelStream().forEach(tbPrintMachineWithBLOBs -> {
if (!"network".equals(tbPrintMachineWithBLOBs.getConnectionType())) {
log.error("非网络打印机");
return;
@@ -82,29 +80,25 @@ public class CloudPrinterService {
return;
}
JSONObject config = JSONObject.parseObject(tbPrintMachineWithBLOBs.getConfig());
String model = config.getString("model");
String printerNum = config.getString("printerNum");
String model = tbPrintMachineWithBLOBs.getPrintMethod();
String feet = config.getString("feet");
String printerNum = StrUtil.isEmpty(tbPrintMachineWithBLOBs.getPrintQty()) ? "1" : tbPrintMachineWithBLOBs.getPrintQty().split("\\^")[1];
String autoCut = config.getString("autoCut");
List<CategoryInfo> categoryInfos = JSONUtil.parseJSONStr2TList(StrUtil.emptyToDefault(tbPrintMachineWithBLOBs.getCategoryList(), "[]"), CategoryInfo.class);
List<CategoryInfo> categoryInfos=JSONUtil.parseJSONStr2TList(config.getJSONArray("categoryList").toString(),CategoryInfo.class);
switch (tbPrintMachineWithBLOBs.getContentType()){
switch (tbPrintMachineWithBLOBs.getContentType()) {
case "yxyPrinter":
yxyPrinter(tbPrintMachineWithBLOBs,model,orderInfo,shopInfo,printerNum,categoryInfos);
yxyPrinter(tbPrintMachineWithBLOBs, model, orderInfo, shopInfo, printerNum, categoryInfos);
break;
case "fePrinter":
fePrinter(tbPrintMachineWithBLOBs,model,orderInfo,shopInfo,printerNum,categoryInfos);
fePrinter(tbPrintMachineWithBLOBs, model, orderInfo, shopInfo, printerNum, categoryInfos);
break;
}
});
return Result.success(CodeEnum.SUCCESS);
}catch (Exception e){
} catch (Exception e) {
e.printStackTrace();
}
@@ -112,145 +106,285 @@ public class CloudPrinterService {
}
/**
* 仅打印结算单「前台」
*/
private void onlyFrontDeskForYxy(String orderId, TbPrintMachineWithBLOBs tbPrintMachineWithBLOBs, String model, TbOrderInfo orderInfo, TbShopInfo shopInfo, String printerNum, List<CategoryInfo> categoryInfos) {
List<TbCashierCart> cashierCarts = tbCashierCartMapper.selectByOrderId(orderInfo.getId().toString(), "final");
if (ObjectUtil.isNotEmpty(cashierCarts) && cashierCarts.size() > 0) {
List<OrderDetailPO.Detail> detailList = new ArrayList<>();
cashierCarts.parallelStream().forEach(it -> {
String categoryId;
if (ObjectUtil.isEmpty(it.getCategoryId())) {
categoryId = tbProductMapper.selectByPrimaryKey(Integer.valueOf(it.getProductId())).getCategoryId();
} else {
categoryId = it.getCategoryId();
}
Long count = categoryInfos.stream().filter(c ->
c.getId().toString().equals(categoryId)
).count();
if (count > 0) {
TbProductSkuWithBLOBs tbProductSkuWithBLOBs = tbProductSkuMapper.selectByPrimaryKey(Integer.valueOf(it.getSkuId()));
String remark = "";
if (ObjectUtil.isNotEmpty(tbProductSkuWithBLOBs) && ObjectUtil.isNotEmpty(tbProductSkuWithBLOBs.getSpecSnap())) {
remark = tbProductSkuWithBLOBs.getSpecSnap();
}
OrderDetailPO.Detail detail = new OrderDetailPO.Detail(it.getName(), it.getNumber().toString(), it.getTotalAmount().toPlainString(), remark);
detailList.add(detail);
}
});
String balance = "0";
if ("deposit".equals(orderInfo.getPayType())) {
TbShopUser user = tbShopUserMapper.selectByPrimaryKey(orderInfo.getMemberId());
if (ObjectUtil.isNotEmpty(user) && ObjectUtil.isNotEmpty(user.getAmount())) {
balance = user.getAmount().toPlainString();
}
}
if (ObjectUtil.isNotEmpty(detailList) && detailList.size() > 0) {
OrderDetailPO detailPO = new OrderDetailPO(shopInfo.getShopName(), "普通打印", orderInfo.getTableName(), orderInfo.getOrderNo(), DateUtils.getTime(new Date(orderInfo.getCreatedAt())), "【POS-1】001", orderInfo.getOrderAmount().toPlainString(), balance, orderInfo.getPayType(), "0", detailList, orderInfo.getRemark());
String data = PrinterUtils.getCashPrintData(detailPO, "结算单");
PrinterUtils.printTickets(1, Integer.valueOf(printerNum), tbPrintMachineWithBLOBs.getAddress(), data);
}
}
}
/**
* 仅打印制作单「厨房」
*/
private void onlyKitchenForYxy(String orderId, TbPrintMachineWithBLOBs tbPrintMachineWithBLOBs, String model, TbOrderInfo orderInfo, TbShopInfo shopInfo, String printerNum, List<CategoryInfo> categoryInfos) {
List<TbCashierCart> cashierCarts = tbCashierCartMapper.selectByOrderId(orderId, "final");
if (ObjectUtil.isNotEmpty(cashierCarts) && cashierCarts.size() > 0) {
cashierCarts.parallelStream().forEach(it -> {
String categoryId;
if (ObjectUtil.isEmpty(it.getCategoryId())) {
categoryId = tbProductMapper.selectByPrimaryKey(Integer.valueOf(it.getProductId())).getCategoryId();
} else {
categoryId = it.getCategoryId();
}
Long count = categoryInfos.stream().filter(c ->
c.getId().toString().equals(categoryId)
).count();
if (count > 0) {
TbProductSkuWithBLOBs tbProductSkuWithBLOBs = tbProductSkuMapper.selectByPrimaryKey(Integer.valueOf(it.getSkuId()));
String remark = "";
if (ObjectUtil.isNotEmpty(tbProductSkuWithBLOBs) && ObjectUtil.isNotEmpty(tbProductSkuWithBLOBs.getSpecSnap())) {
remark = tbProductSkuWithBLOBs.getSpecSnap();
}
String data = PrinterUtils.getPrintData(orderInfo.getTableName(), DateUtils.getTime(new Date(orderInfo.getCreatedAt())), it.getName(), it.getNumber(), remark);
PrinterUtils.printTickets(1, Integer.valueOf(printerNum), tbPrintMachineWithBLOBs.getAddress(), data);
}
});
}
}
/**
* 博时结云打印机
* 博时结云打印机
*
* @param tbPrintMachineWithBLOBs
* @param model
* @param orderInfo
* @param shopInfo
* @param printerNum
*/
private void yxyPrinter(TbPrintMachineWithBLOBs tbPrintMachineWithBLOBs,String model,TbOrderInfo orderInfo,TbShopInfo shopInfo,String printerNum, List<CategoryInfo> categoryInfos){
String orderId=orderInfo.getId().toString();
private void yxyPrinter(TbPrintMachineWithBLOBs tbPrintMachineWithBLOBs, String model, TbOrderInfo orderInfo, TbShopInfo shopInfo, String printerNum, List<CategoryInfo> categoryInfos) {
String orderId = orderInfo.getId().toString();
switch (tbPrintMachineWithBLOBs.getSubType()) {
case "label": //标签打印机
break;
case "cash": //小票打印机
switch (model) {
case "normal": //普通出单
List<TbCashierCart> cashierCarts = tbCashierCartMapper.selectByOrderId(orderInfo.getId().toString(),"final");
if (ObjectUtil.isNotEmpty(cashierCarts) && cashierCarts.size() > 0) {
List<OrderDetailPO.Detail> detailList = new ArrayList<>();
cashierCarts.parallelStream().forEach(it -> {
String categoryId;
if(ObjectUtil.isEmpty(it.getCategoryId())){
categoryId= tbProductMapper.selectByPrimaryKey(Integer.valueOf(it.getProductId())).getCategoryId();
} else {
categoryId = it.getCategoryId();
}
Long count= categoryInfos.stream().filter(c->
c.getId().toString().equals(categoryId)
).count();
if(count>0){
TbProductSkuWithBLOBs tbProductSkuWithBLOBs = tbProductSkuMapper.selectByPrimaryKey(Integer.valueOf(it.getSkuId()));
String remark = "";
if (ObjectUtil.isNotEmpty(tbProductSkuWithBLOBs) && ObjectUtil.isNotEmpty(tbProductSkuWithBLOBs.getSpecSnap())) {
remark = tbProductSkuWithBLOBs.getSpecSnap();
}
OrderDetailPO.Detail detail = new OrderDetailPO.Detail(it.getName(), it.getNumber().toString(), it.getTotalAmount().toPlainString(), remark);
detailList.add(detail);
}
});
String balance = "0";
if ("deposit".equals(orderInfo.getPayType())) {
TbShopUser user = tbShopUserMapper.selectByPrimaryKey(orderInfo.getMemberId());
if (ObjectUtil.isNotEmpty(user) && ObjectUtil.isNotEmpty(user.getAmount())) {
balance = user.getAmount().toPlainString();
}
}
if(ObjectUtil.isNotEmpty(detailList)&&detailList.size()>0){
OrderDetailPO detailPO = new OrderDetailPO(shopInfo.getShopName(), "普通打印", orderInfo.getTableName(), orderInfo.getOrderNo(), DateUtils.getTime(new Date(orderInfo.getCreatedAt())), "【POS-1】001", orderInfo.getOrderAmount().toPlainString(), balance, orderInfo.getPayType(), "0", detailList,orderInfo.getRemark());
String data= PrinterUtils.getCashPrintData(detailPO,"结算单");
PrinterUtils.printTickets(1, Integer.valueOf(printerNum), tbPrintMachineWithBLOBs.getAddress(), data);
}
}
break;
case "one": //一菜一品
cashierCarts = tbCashierCartMapper.selectByOrderId(orderId,"final");
if (ObjectUtil.isNotEmpty(cashierCarts) && cashierCarts.size() > 0) {
cashierCarts.parallelStream().forEach(it -> {
String categoryId;
if(ObjectUtil.isEmpty(it.getCategoryId())){
categoryId= tbProductMapper.selectByPrimaryKey(Integer.valueOf(it.getProductId())).getCategoryId();
} else {
categoryId = it.getCategoryId();
}
Long count= categoryInfos.stream().filter(c->
c.getId().toString().equals(categoryId)
).count();
if(count>0){
TbProductSkuWithBLOBs tbProductSkuWithBLOBs = tbProductSkuMapper.selectByPrimaryKey(Integer.valueOf(it.getSkuId()));
String remark = "";
if (ObjectUtil.isNotEmpty(tbProductSkuWithBLOBs) && ObjectUtil.isNotEmpty(tbProductSkuWithBLOBs.getSpecSnap())) {
remark = tbProductSkuWithBLOBs.getSpecSnap();
}
String data = PrinterUtils.getPrintData(orderInfo.getTableName(), DateUtils.getTime(new Date(orderInfo.getCreatedAt())), it.getName(), it.getNumber(), remark);
PrinterUtils.printTickets(1, Integer.valueOf(printerNum), tbPrintMachineWithBLOBs.getAddress(), data);
}
});
}
break;
case "category": //分类出单
break;
if ("normal".equals(model)) {
onlyFrontDeskForYxy(orderId, tbPrintMachineWithBLOBs, model, orderInfo, shopInfo, printerNum, categoryInfos);
} else if ("one".equals(model)) {
onlyKitchenForYxy(orderId, tbPrintMachineWithBLOBs, model, orderInfo, shopInfo, printerNum, categoryInfos);
} else if ("all".equals(model)) {
onlyFrontDeskForYxy(orderId, tbPrintMachineWithBLOBs, model, orderInfo, shopInfo, printerNum, categoryInfos);
onlyKitchenForYxy(orderId, tbPrintMachineWithBLOBs, model, orderInfo, shopInfo, printerNum, categoryInfos);
}
break;
case "kitchen": //出品打印机
break;
}
}
/**
* 仅打印结算单「前台」
*/
private void onlyFrontDeskForFe(String orderId, TbPrintMachineWithBLOBs tbPrintMachineWithBLOBs, String model, TbOrderInfo orderInfo, TbShopInfo shopInfo, String printerNum, List<CategoryInfo> categoryInfos) {
if ("return".equals(orderInfo.getOrderType())) {
List<TbOrderDetail> tbOrderDetails = tbOrderDetailMapper.selectAllByOrderId(Integer.valueOf(orderId));
if (ObjectUtil.isNotEmpty(tbOrderDetails) && tbOrderDetails.size() > 0) {
List<OrderDetailPO.Detail> detailList = new ArrayList<>();
tbOrderDetails.parallelStream().forEach(it -> {
String categoryId = tbProductMapper.selectByPrimaryKey(Integer.valueOf(it.getProductId())).getCategoryId();
Long count = categoryInfos.stream().filter(c ->
c.getId().toString().equals(categoryId)
).count();
log.info("获取当前类别是否未打印类别:{}", count);
TbProductSkuWithBLOBs tbProductSkuWithBLOBs = tbProductSkuMapper.selectByPrimaryKey(Integer.valueOf(it.getProductSkuId()));
String remark = "";
if (ObjectUtil.isNotEmpty(tbProductSkuWithBLOBs) && ObjectUtil.isNotEmpty(tbProductSkuWithBLOBs.getSpecSnap())) {
remark = tbProductSkuWithBLOBs.getSpecSnap();
}
OrderDetailPO.Detail detail = new OrderDetailPO.Detail(it.getProductName(), it.getNum().toString(), it.getPriceAmount().toPlainString(), remark);
detailList.add(detail);
private void fePrinter(TbPrintMachineWithBLOBs tbPrintMachineWithBLOBs,String model,TbOrderInfo orderInfo,TbShopInfo shopInfo,String printerNum, List<CategoryInfo> categoryInfos){
String orderId=orderInfo.getId().toString();
});
String balance = "0";
if ("deposit".equals(orderInfo.getPayType())) {
TbShopUser user = tbShopUserMapper.selectByPrimaryKey(orderInfo.getMemberId());
if (ObjectUtil.isNotEmpty(user) && ObjectUtil.isNotEmpty(user.getAmount())) {
balance = user.getAmount().toPlainString();
}
}
if (ObjectUtil.isNotEmpty(detailList) && detailList.size() > 0) {
// OrderDetailPO detailPO = new OrderDetailPO(shopInfo.getShopName(), "普通打印", orderInfo.getMasterId(), orderInfo.getOrderNo(), DateUtils.getTime(new Date(orderInfo.getCreatedAt())), "【POS-1】001", orderInfo.getOrderAmount().toPlainString(), balance, orderInfo.getPayType(), "0", detailList);
OrderDetailPO detailPO = new OrderDetailPO(shopInfo.getShopName(), "普通打印", ObjectUtil.isEmpty(orderInfo.getMasterId()) || ObjectUtil.isNull(orderInfo.getMasterId()) ? orderInfo.getTableName() : orderInfo.getMasterId(), orderInfo.getOrderNo(), DateUtils.getTime(new Date(orderInfo.getCreatedAt())), "【POS-1】001", orderInfo.getOrderAmount().toPlainString(), balance, orderInfo.getPayType(), "0", detailList, orderInfo.getRemark());
String printType = "退款单";
String data = PrinterUtils.getCashPrintData(detailPO, printType);
PrinterUtils.printTickets(1, Integer.valueOf(printerNum), tbPrintMachineWithBLOBs.getAddress(), data);
}
}
} else {
List<TbCashierCart> cashierCarts = tbCashierCartMapper.selectByOrderId(orderInfo.getId().toString(), "final");
if (ObjectUtil.isNotEmpty(cashierCarts) && cashierCarts.size() > 0) {
List<OrderDetailPO.Detail> detailList = new ArrayList<>();
cashierCarts.parallelStream().forEach(it -> {
String categoryId;
if (ObjectUtil.isEmpty(it.getCategoryId())) {
categoryId = tbProductMapper.selectByPrimaryKey(Integer.valueOf(it.getProductId())).getCategoryId();
} else {
categoryId = it.getCategoryId();
}
Long count = categoryInfos.stream().filter(c ->
c.getId().toString().equals(categoryId)
).count();
if (count > 0) {
TbProductSkuWithBLOBs tbProductSkuWithBLOBs = tbProductSkuMapper.selectByPrimaryKey(Integer.valueOf(it.getSkuId()));
String remark = "";
if (ObjectUtil.isNotEmpty(tbProductSkuWithBLOBs) && ObjectUtil.isNotEmpty(tbProductSkuWithBLOBs.getSpecSnap())) {
remark = tbProductSkuWithBLOBs.getSpecSnap();
}
OrderDetailPO.Detail detail = new OrderDetailPO.Detail(it.getName(), it.getNumber().toString(), it.getTotalAmount().toPlainString(), remark);
detailList.add(detail);
}
});
String balance = "0";
if ("deposit".equals(orderInfo.getPayType())) {
TbShopUser user = tbShopUserMapper.selectByPrimaryKey(orderInfo.getMemberId());
if (ObjectUtil.isNotEmpty(user) && ObjectUtil.isNotEmpty(user.getAmount())) {
balance = user.getAmount().toPlainString();
}
}
if (ObjectUtil.isNotEmpty(detailList) && detailList.size() > 0) {
OrderDetailPO detailPO = new OrderDetailPO(shopInfo.getShopName(), "普通打印", orderInfo.getOrderType().equals("miniapp") ? orderInfo.getTableName() : orderInfo.getMasterId(), orderInfo.getOrderNo(), DateUtils.getTime(new Date(orderInfo.getCreatedAt())), "【POS-1】001", orderInfo.getOrderAmount().toPlainString(), balance, (ObjectUtil.isEmpty(orderInfo.getPayType()) || ObjectUtil.isNull(orderInfo.getPayType()) ? "" : orderInfo.getPayType()), "0", detailList, orderInfo.getRemark());
String printType = "结算单";
if ("return".equals(orderInfo.getOrderType())) {
printType = "退款单";
}
FeieyunPrintUtil.getCashPrintData(detailPO, tbPrintMachineWithBLOBs.getAddress(), printType, printType);
}
}
}
}
/**
* 仅打印制作单「厨房」
*/
private void onlyKitchenForFe(String orderId, TbPrintMachineWithBLOBs tbPrintMachineWithBLOBs, String model, TbOrderInfo orderInfo, TbShopInfo shopInfo, String printerNum, List<CategoryInfo> categoryInfos) {
List<TbCashierCart> cashierCarts = tbCashierCartMapper.selectByOrderId(orderId, "final");
if (ObjectUtil.isNotEmpty(cashierCarts) && cashierCarts.size() > 0) {
cashierCarts.parallelStream().forEach(it -> {
String categoryId;
if (ObjectUtil.isEmpty(it.getCategoryId())) {
categoryId = tbProductMapper.selectByPrimaryKey(Integer.valueOf(it.getProductId())).getCategoryId();
} else {
categoryId = it.getCategoryId();
}
Long count = categoryInfos.stream().filter(c ->
c.getId().toString().equals(categoryId)
).count();
if (count > 0) {
TbProductSkuWithBLOBs tbProductSkuWithBLOBs = tbProductSkuMapper.selectByPrimaryKey(Integer.valueOf(it.getSkuId()));
String remark = "";
if (ObjectUtil.isNotEmpty(tbProductSkuWithBLOBs) && ObjectUtil.isNotEmpty(tbProductSkuWithBLOBs.getSpecSnap())) {
remark = tbProductSkuWithBLOBs.getSpecSnap();
}
FeieyunPrintUtil.getPrintData(tbPrintMachineWithBLOBs.getAddress(), orderInfo.getTableName(), DateUtils.getTime(new Date(orderInfo.getCreatedAt())), it.getName(), it.getNumber(), remark);
}
});
}
}
private void fePrinter(TbPrintMachineWithBLOBs tbPrintMachineWithBLOBs, String model, TbOrderInfo orderInfo, TbShopInfo shopInfo, String printerNum, List<CategoryInfo> categoryInfos) {
String orderId = orderInfo.getId().toString();
switch (tbPrintMachineWithBLOBs.getSubType()) {
case "label": //标签打印机
List<TbCashierCart> cashierCarts = tbCashierCartMapper.selectByOrderId(orderInfo.getId().toString(),"final");
List<TbCashierCart> cashierCarts = tbCashierCartMapper.selectByOrderId(orderInfo.getId().toString(), "final");
if (ObjectUtil.isNotEmpty(cashierCarts) && cashierCarts.size() > 0) {
cashierCarts.parallelStream().forEach(it->{
cashierCarts.parallelStream().forEach(it -> {
String categoryId;
if(ObjectUtil.isEmpty(it.getCategoryId())){
categoryId= tbProductMapper.selectByPrimaryKey(Integer.valueOf(it.getProductId())).getCategoryId();
if (ObjectUtil.isEmpty(it.getCategoryId())) {
categoryId = tbProductMapper.selectByPrimaryKey(Integer.valueOf(it.getProductId())).getCategoryId();
} else {
categoryId = it.getCategoryId();
}
Long count= categoryInfos.stream().filter(c->
Long count = categoryInfos.stream().filter(c ->
c.getId().toString().equals(categoryId)
).count();
if(count>0) {
if (count > 0) {
TbProductSkuWithBLOBs tbProductSkuWithBLOBs = tbProductSkuMapper.selectByPrimaryKey(Integer.valueOf(it.getSkuId()));
String remark = "";
if (ObjectUtil.isNotEmpty(tbProductSkuWithBLOBs) && ObjectUtil.isNotEmpty(tbProductSkuWithBLOBs.getSpecSnap())) {
remark = tbProductSkuWithBLOBs.getSpecSnap();
}
for(int i=0;i<it.getNumber();i++){
for (int i = 0; i < it.getNumber(); i++) {
FeieyunPrintUtil.printLabelMsg(tbPrintMachineWithBLOBs.getAddress(), orderInfo.getTableName(), it.getName(), 1, DateUtils.getTimes(new Date(orderInfo.getCreatedAt())), it.getSalePrice().toPlainString(), remark);
}
@@ -260,136 +394,13 @@ public class CloudPrinterService {
break;
case "cash": //小票打印机
switch (model) {
case "normal": //普通出单
if ("return".equals(orderInfo.getOrderType())) {
List<TbOrderDetail> tbOrderDetails = tbOrderDetailMapper.selectAllByOrderId(Integer.valueOf(orderId));
if (ObjectUtil.isNotEmpty(tbOrderDetails) && tbOrderDetails.size() > 0) {
List<OrderDetailPO.Detail> detailList = new ArrayList<>();
tbOrderDetails.parallelStream().forEach(it -> {
String categoryId = tbProductMapper.selectByPrimaryKey(Integer.valueOf(it.getProductId())).getCategoryId();
Long count = categoryInfos.stream().filter(c ->
c.getId().toString().equals(categoryId)
).count();
log.info("获取当前类别是否未打印类别:{}", count);
TbProductSkuWithBLOBs tbProductSkuWithBLOBs = tbProductSkuMapper.selectByPrimaryKey(Integer.valueOf(it.getProductSkuId()));
String remark = "";
if (ObjectUtil.isNotEmpty(tbProductSkuWithBLOBs) && ObjectUtil.isNotEmpty(tbProductSkuWithBLOBs.getSpecSnap())) {
remark = tbProductSkuWithBLOBs.getSpecSnap();
}
OrderDetailPO.Detail detail = new OrderDetailPO.Detail(it.getProductName(), it.getNum().toString(), it.getPriceAmount().toPlainString(), remark);
detailList.add(detail);
});
String balance = "0";
if ("deposit".equals(orderInfo.getPayType())) {
TbShopUser user = tbShopUserMapper.selectByPrimaryKey(orderInfo.getMemberId());
if (ObjectUtil.isNotEmpty(user) && ObjectUtil.isNotEmpty(user.getAmount())) {
balance = user.getAmount().toPlainString();
}
}
if (ObjectUtil.isNotEmpty(detailList) && detailList.size() > 0) {
// OrderDetailPO detailPO = new OrderDetailPO(shopInfo.getShopName(), "普通打印", orderInfo.getMasterId(), orderInfo.getOrderNo(), DateUtils.getTime(new Date(orderInfo.getCreatedAt())), "【POS-1】001", orderInfo.getOrderAmount().toPlainString(), balance, orderInfo.getPayType(), "0", detailList);
OrderDetailPO detailPO = new OrderDetailPO(shopInfo.getShopName(), "普通打印", ObjectUtil.isEmpty(orderInfo.getMasterId()) || ObjectUtil.isNull(orderInfo.getMasterId()) ? orderInfo.getTableName() : orderInfo.getMasterId(), orderInfo.getOrderNo(), DateUtils.getTime(new Date(orderInfo.getCreatedAt())), "【POS-1】001", orderInfo.getOrderAmount().toPlainString(), balance, orderInfo.getPayType(), "0", detailList, orderInfo.getRemark());
String printType = "退款单";
String data = PrinterUtils.getCashPrintData(detailPO, printType);
PrinterUtils.printTickets(1, Integer.valueOf(printerNum), tbPrintMachineWithBLOBs.getAddress(), data);
}
}
} else {
cashierCarts = cashierCarts = tbCashierCartMapper.selectByOrderId(orderInfo.getId().toString(), "final");
if (ObjectUtil.isNotEmpty(cashierCarts) && cashierCarts.size() > 0) {
List<OrderDetailPO.Detail> detailList = new ArrayList<>();
cashierCarts.parallelStream().forEach(it -> {
String categoryId;
if (ObjectUtil.isEmpty(it.getCategoryId())) {
categoryId = tbProductMapper.selectByPrimaryKey(Integer.valueOf(it.getProductId())).getCategoryId();
} else {
categoryId = it.getCategoryId();
}
Long count = categoryInfos.stream().filter(c ->
c.getId().toString().equals(categoryId)
).count();
if (count > 0) {
TbProductSkuWithBLOBs tbProductSkuWithBLOBs = tbProductSkuMapper.selectByPrimaryKey(Integer.valueOf(it.getSkuId()));
String remark = "";
if (ObjectUtil.isNotEmpty(tbProductSkuWithBLOBs) && ObjectUtil.isNotEmpty(tbProductSkuWithBLOBs.getSpecSnap())) {
remark = tbProductSkuWithBLOBs.getSpecSnap();
}
OrderDetailPO.Detail detail = new OrderDetailPO.Detail(it.getName(), it.getNumber().toString(), it.getTotalAmount().toPlainString(), remark);
detailList.add(detail);
}
});
String balance = "0";
if ("deposit".equals(orderInfo.getPayType())) {
TbShopUser user = tbShopUserMapper.selectByPrimaryKey(orderInfo.getMemberId());
if (ObjectUtil.isNotEmpty(user) && ObjectUtil.isNotEmpty(user.getAmount())) {
balance = user.getAmount().toPlainString();
}
}
if (ObjectUtil.isNotEmpty(detailList) && detailList.size() > 0) {
OrderDetailPO detailPO = new OrderDetailPO(shopInfo.getShopName(), "普通打印", orderInfo.getOrderType().equals("miniapp") ? orderInfo.getTableName() : orderInfo.getMasterId(), orderInfo.getOrderNo(), DateUtils.getTime(new Date(orderInfo.getCreatedAt())), "【POS-1】001", orderInfo.getOrderAmount().toPlainString(), balance, (ObjectUtil.isEmpty(orderInfo.getPayType()) || ObjectUtil.isNull(orderInfo.getPayType()) ? "" : orderInfo.getPayType()), "0", detailList, orderInfo.getRemark());
String printType = "结算单";
if ("return".equals(orderInfo.getOrderType())) {
printType = "退款单";
}
FeieyunPrintUtil.getCashPrintData(detailPO, tbPrintMachineWithBLOBs.getAddress(), printType, printType);
}
}
}
break;
case "one": //一菜一品
cashierCarts = tbCashierCartMapper.selectByOrderId(orderId, "final");
if (ObjectUtil.isNotEmpty(cashierCarts) && cashierCarts.size() > 0) {
cashierCarts.parallelStream().forEach(it -> {
String categoryId;
if (ObjectUtil.isEmpty(it.getCategoryId())) {
categoryId = tbProductMapper.selectByPrimaryKey(Integer.valueOf(it.getProductId())).getCategoryId();
} else {
categoryId = it.getCategoryId();
}
Long count = categoryInfos.stream().filter(c ->
c.getId().toString().equals(categoryId)
).count();
if (count > 0) {
TbProductSkuWithBLOBs tbProductSkuWithBLOBs = tbProductSkuMapper.selectByPrimaryKey(Integer.valueOf(it.getSkuId()));
String remark = "";
if (ObjectUtil.isNotEmpty(tbProductSkuWithBLOBs) && ObjectUtil.isNotEmpty(tbProductSkuWithBLOBs.getSpecSnap())) {
remark = tbProductSkuWithBLOBs.getSpecSnap();
}
FeieyunPrintUtil.getPrintData(tbPrintMachineWithBLOBs.getAddress(), orderInfo.getTableName(), DateUtils.getTime(new Date(orderInfo.getCreatedAt())), it.getName(), it.getNumber(), remark);
}
});
}
if ("normal".equals(model)) {
onlyFrontDeskForFe(orderId, tbPrintMachineWithBLOBs, model, orderInfo, shopInfo, printerNum, categoryInfos);
} else if ("one".equals(model)) {
onlyKitchenForFe(orderId, tbPrintMachineWithBLOBs, model, orderInfo, shopInfo, printerNum, categoryInfos);
} else if ("all".equals(model)) {
onlyFrontDeskForFe(orderId, tbPrintMachineWithBLOBs, model, orderInfo, shopInfo, printerNum, categoryInfos);
onlyKitchenForFe(orderId, tbPrintMachineWithBLOBs, model, orderInfo, shopInfo, printerNum, categoryInfos);
}
break;
case "kitchen": //出品打印机
@@ -398,6 +409,4 @@ public class CloudPrinterService {
}
}

View File

@@ -1,117 +0,0 @@
package com.chaozhanggui.system.cashierservice.service;
import com.alibaba.fastjson.JSONObject;
import com.chaozhanggui.system.cashierservice.dao.*;
import com.chaozhanggui.system.cashierservice.entity.*;
import com.chaozhanggui.system.cashierservice.exception.MsgException;
import com.chaozhanggui.system.cashierservice.redis.RedisUtil;
import com.chaozhanggui.system.cashierservice.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
/**
* @author lyf
*/
@Service
@Slf4j
public class IntegralService {
@Autowired
private RedisUtil redisUtil;
@Autowired
private TbOrderInfoMapper orderInfoMapper;
@Autowired
private TbUserInfoMapper userInfoMapper;
@Autowired
private TbProductMapper productMapper;
@Autowired
private TbProductSkuMapper productSkuMapper;
@Autowired
private TbShopInfoMapper shopInfoMapper;
@Autowired
private TbShopUserMapper tbShopUserMapper;
@Resource
private TbReleaseFlowMapper integralFlowMapper;
@Autowired
private TbUserCouponsMapper userCouponsMapper;
@Autowired
private TbSplitAccountsMapper splitAccountsMapper;
@Transactional(rollbackFor = Exception.class)
public void integralAdd(JSONObject jsonObject) throws ParseException {
String type = jsonObject.getString("type");
if (type.equals("trade")){
//优惠券兑换积分
Integer integralId = jsonObject.getInteger("integralId");
TbUserCoupons userCoupons = userCouponsMapper.selectByPrimaryKey(integralId);
if (Objects.isNull(userCoupons) || !"0".equals(userCoupons.getStatus())){
throw new MsgException("优惠券已被使用");
}
userCoupons.setStatus("trade");
userCoupons.setUpdateTime(new Date());
userCouponsMapper.updateByPrimaryKeySelective(userCoupons);
TbParams params = tbShopUserMapper.selectParams();
TbReleaseFlow integralFlow = new TbReleaseFlow();
integralFlow.setNum(userCoupons.getCouponsAmount().multiply(params.getTradeRatio()));
integralFlow.setCreateTime(new Date());
integralFlow.setFromSource(userCoupons.getId()+"");
integralFlow.setType("TRADEADD");
integralFlow.setUserId(userCoupons.getUserId());
integralFlowMapper.insert(integralFlow);
TbUserInfo userInfo = userInfoMapper.selectByPrimaryKey(Integer.valueOf(userCoupons.getUserId()));
if (Objects.nonNull(userInfo)){
userInfo.setTotalScore(userInfo.getTotalScore() + integralFlow.getNum().intValue());
userInfoMapper.updateByPrimaryKeySelective(userInfo);
}
}else {
Integer orderId = jsonObject.getInteger("orderId");
TbOrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId);
if (StringUtils.isNotBlank(orderInfo.getUserCouponId())){
TbUserCoupons userCoupons = userCouponsMapper.selectByPrimaryKey(Integer.valueOf(orderInfo.getUserCouponId()));
if (Objects.nonNull(userCoupons)){
TbShopInfo shopInfo = shopInfoMapper.selectByPrimaryKey(Integer.valueOf(orderInfo.getShopId()));
TbSplitAccounts splitAccounts = new TbSplitAccounts();
splitAccounts.setConponsAmount(userCoupons.getCouponsAmount());
splitAccounts.setCreateTime(new Date());
splitAccounts.setIsSplit("false");
splitAccounts.setMerchantId(Integer.valueOf(shopInfo.getMerchantId()));
splitAccounts.setShopId(shopInfo.getId());
splitAccounts.setOrderAmount(orderInfo.getPayAmount());
splitAccounts.setTradeDay(DateUtils.getDay());
splitAccounts.setOriginAmount(orderInfo.getOriginAmount());
splitAccountsMapper.insert(splitAccounts);
}
}
if (Objects.isNull(orderInfo)) {
log.error("该订单不存在");
return;
}
TbShopInfo shopInfo = shopInfoMapper.selectByPrimaryKey(Integer.valueOf(orderInfo.getShopId()));
if (Objects.isNull(shopInfo) || !"true".equals(shopInfo.getIsOpenYhq())){
log.error("该店铺未开启优惠券功能");
return;
}
TbParams params = tbShopUserMapper.selectParams();
TbUserCoupons userCoupons = new TbUserCoupons();
userCoupons.setUserId(orderInfo.getUserId());
userCoupons.setCouponsAmount(orderInfo.getOrderAmount().subtract(orderInfo.getUserCouponAmount()).multiply(params.getIntegralRatio()));
userCoupons.setStatus("0");
userCoupons.setOrderId(orderId);
userCoupons.setCouponsPrice(userCoupons.getCouponsAmount().multiply(new BigDecimal("0.5")));
userCoupons.setCreateTime(new Date());
userCoupons.setEndTime(DateUtils.getNewDate(new Date(),3,30));
//执行插入方法
userCouponsMapper.insert(userCoupons);
}
}
}

View File

@@ -1,14 +1,14 @@
package com.chaozhanggui.system.cashierservice.service;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.chaozhanggui.system.cashierservice.dao.*;
import com.chaozhanggui.system.cashierservice.entity.*;
import com.chaozhanggui.system.cashierservice.exception.MsgException;
import com.chaozhanggui.system.cashierservice.entity.TbShopOpenId;
import com.chaozhanggui.system.cashierservice.entity.TbShopUser;
import com.chaozhanggui.system.cashierservice.entity.TbUserInfo;
import com.chaozhanggui.system.cashierservice.entity.TbUserShopMsg;
import com.chaozhanggui.system.cashierservice.redis.RedisCst;
import com.chaozhanggui.system.cashierservice.redis.RedisUtil;
import com.chaozhanggui.system.cashierservice.sign.CodeEnum;
@@ -24,6 +24,7 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
@Service
@@ -37,6 +38,9 @@ public class LoginService {
@Autowired
private TbShopUserMapper tbShopUserMapper;
@Autowired
private TbActivateInRecordMapper inRecordMapper;
@Autowired
private TbShopTableMapper tbShopTableMapper;
@@ -141,34 +145,72 @@ public class LoginService {
}
private void buildNewUserInfo(TbUserInfo userInfo) {
userInfo = new TbUserInfo();
userInfo.setAmount(BigDecimal.ZERO);
userInfo.setChargeAmount(BigDecimal.ZERO);
userInfo.setLineOfCredit(BigDecimal.ZERO);
userInfo.setConsumeNumber(0);
userInfo.setConsumeAmount(BigDecimal.ZERO);
userInfo.setTotalScore(0);
userInfo.setLockScore(0);
userInfo.setHeadImg("");
userInfo.setNickName("");
userInfo.setTelephone("");
userInfo.setStatus(Byte.parseByte("1"));
userInfo.setParentType("PERSON");
userInfo.setIsResource(Byte.parseByte("0"));
userInfo.setIsOnline(Byte.parseByte("0"));
userInfo.setIsVip(Byte.parseByte("0"));
userInfo.setIsAttentionMp(Byte.parseByte("0"));
userInfo.setIsPwd("0");
userInfo.setPwd(MD5Utils.md5("123456"));
userInfo.setCreatedAt(System.currentTimeMillis());
userInfo.setLastLogInAt(System.currentTimeMillis());
userInfo.setUpdatedAt(System.currentTimeMillis());
}
public Result wxCustomLogin(String openId, String headImage, String nickName, String telephone, String ip) {
TbUserInfo userInfo = tbUserInfoMapper.selectByOpenId(openId);
if (ObjectUtil.isNull(userInfo)) {
userInfo = new TbUserInfo();
userInfo.setAmount(BigDecimal.ZERO);
userInfo.setChargeAmount(BigDecimal.ZERO);
userInfo.setLineOfCredit(BigDecimal.ZERO);
userInfo.setConsumeNumber(0);
userInfo.setConsumeAmount(BigDecimal.ZERO);
userInfo.setTotalScore(0);
userInfo.setLockScore(0);
buildNewUserInfo(userInfo);
userInfo.setHeadImg(ObjectUtil.isNotNull(headImage) ? headImage : "");
userInfo.setNickName(ObjectUtil.isNotNull(nickName) ? nickName : "微信用户");
userInfo.setTelephone(ObjectUtil.isNotNull(telephone) ? telephone : "");
userInfo.setMiniAppOpenId(openId);
userInfo.setStatus(Byte.parseByte("1"));
userInfo.setParentType("PERSON");
userInfo.setIsResource(Byte.parseByte("0"));
userInfo.setIsOnline(Byte.parseByte("0"));
userInfo.setIsVip(Byte.parseByte("0"));
userInfo.setSourcePath("WECHAT-APP");
userInfo.setIsAttentionMp(Byte.parseByte("0"));
userInfo.setSearchWord("||微信用户");
userInfo.setIsPwd("0");
userInfo.setPwd(MD5Utils.md5("123456"));
userInfo.setCreatedAt(System.currentTimeMillis());
userInfo.setLastLogInAt(System.currentTimeMillis());
userInfo.setMiniAppOpenId(openId);
tbUserInfoMapper.insert(userInfo);
} else {
userInfo.setUpdatedAt(System.currentTimeMillis());
userInfo.setLastLogInAt(System.currentTimeMillis());
tbUserInfoMapper.updateByPrimaryKeySelective(userInfo);
}
//生成token 信息
String token = TokenUtil.generateToken(userInfo.getId(), userInfo.getMiniAppOpenId(), userInfo.getTelephone(), userInfo.getNickName());
Map<String, Object> map = new HashMap<>();
map.put("token", token);
map.put("userInfo", userInfo);
redisUtil.saveMessage(RedisCst.ONLINE_USER.concat(openId), JSON.toJSONString(map), 60 * 60 * 24 * 30L);
log.info("登录传参 结果:" + JSONUtil.toJSONString(map));
return Result.success(CodeEnum.SUCCESS, map);
}
/**
* 支付宝用户登录
* @param openId
* @return
*/
public Result alipayCustomLogin(String openId) {
TbUserInfo userInfo = tbUserInfoMapper.selectByOpenId(openId);
if (ObjectUtil.isNull(userInfo)) {
userInfo = new TbUserInfo();
buildNewUserInfo(userInfo);
userInfo.setNickName("支付宝用户");
userInfo.setSourcePath("ALIPAY-APP");
userInfo.setSearchWord("||支付宝用户");
userInfo.setMiniAppOpenId(openId);
tbUserInfoMapper.insert(userInfo);
} else {
userInfo.setUpdatedAt(System.currentTimeMillis());
@@ -460,6 +502,9 @@ public class LoginService {
if (tbUserInfo == null) {
return Result.success(CodeEnum.ENCRYPT, new ArrayList());
}
tbUserInfo.setBalanceAll(tbShopUserMapper.countAmount(userId));
tbUserInfo.setCouponAll(inRecordMapper.countCouponNum(userId));
return Result.success(CodeEnum.ENCRYPT, tbUserInfo);
}
@@ -477,6 +522,7 @@ public class LoginService {
TbShopUser tbShopUserSM = tbShopUserMapper.selectByUserIdAndShopId(userInfo.getId().toString(), shopId);
if (tbShopUserSM != null) {
tbShopUserSM.setIsVip(Byte.parseByte("1"));
tbShopUserSM.setJoinTime(new Timestamp(System.currentTimeMillis()));
tbShopUserSM.setTelephone(phone);
tbShopUserSM.setUpdatedAt(System.currentTimeMillis());
tbShopUserMapper.updateByPrimaryKey(tbShopUserSM);
@@ -499,6 +545,7 @@ public class LoginService {
shopUser.setTelephone(userInfo.getTelephone());
shopUser.setAmount(BigDecimal.ZERO);
shopUser.setIsVip(Byte.parseByte("1"));
shopUser.setJoinTime(new Timestamp(System.currentTimeMillis()));
shopUser.setCreditAmount(BigDecimal.ZERO);
shopUser.setConsumeAmount(BigDecimal.ZERO);
shopUser.setConsumeNumber(0);
@@ -537,21 +584,23 @@ public class LoginService {
) {
return Result.fail("参数错误");
}
TbUserInfo userInfo = tbUserInfoMapper.selectByPrimaryKey(Integer.valueOf(userId));
boolean flag = validate(map.get("code").toString(), userInfo.getTelephone());
if (!flag) {
return Result.fail("验证码错误");
String phone = userInfo.getTelephone();
if (map.containsKey("vipId")) {
TbShopUser tbShopUser = tbShopUserMapper.selectByPrimaryKey(map.get("vipId").toString());
phone = tbShopUser.getTelephone();
}
if (StringUtils.isBlank(phone)) return Result.fail("设置密码失败,手机号获取为空");
boolean flag = validate(map.get("code").toString(), phone);
if (!flag) return Result.fail("验证码错误");
userInfo.setIsPwd("1");
userInfo.setPwd(MD5Utils.md5(map.get("pwd").toString()));
userInfo.setUpdatedAt(System.currentTimeMillis());
tbUserInfoMapper.updateByPrimaryKey(userInfo);
return Result.success(CodeEnum.SUCCESS);
}
@@ -581,11 +630,4 @@ public class LoginService {
return Result.success(CodeEnum.SUCCESS);
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(RandomUtil.randomNumbers(10));
}
}
}

View File

@@ -1,35 +1,39 @@
package com.chaozhanggui.system.cashierservice.service;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.chaozhanggui.system.cashierservice.dao.*;
import com.chaozhanggui.system.cashierservice.entity.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chaozhanggui.system.cashierservice.constant.TableConstant;
import com.chaozhanggui.system.cashierservice.dao.TbOrderDetailMapper;
import com.chaozhanggui.system.cashierservice.dao.TbOrderInfoMapper;
import com.chaozhanggui.system.cashierservice.dao.TbShopInfoMapper;
import com.chaozhanggui.system.cashierservice.dao.TbShopTableMapper;
import com.chaozhanggui.system.cashierservice.entity.TbOrderDetail;
import com.chaozhanggui.system.cashierservice.entity.TbOrderInfo;
import com.chaozhanggui.system.cashierservice.entity.TbShopInfo;
import com.chaozhanggui.system.cashierservice.entity.TbShopTable;
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.mapper.MpCashierCartMapper;
import com.chaozhanggui.system.cashierservice.mapper.MpOrderDetailMapper;
import com.chaozhanggui.system.cashierservice.mapper.MpOrderInfoMapper;
import com.chaozhanggui.system.cashierservice.mapper.MpShopInfoMapper;
import com.chaozhanggui.system.cashierservice.sign.CodeEnum;
import com.chaozhanggui.system.cashierservice.sign.Result;
import com.chaozhanggui.system.cashierservice.util.DateUtils;
import com.chaozhanggui.system.cashierservice.util.N;
import com.chaozhanggui.system.cashierservice.util.RedisUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Collections;
import java.util.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
/**
* @author 12847
@@ -37,8 +41,6 @@ import java.util.concurrent.TimeUnit;
@Service
public class OrderService {
@Resource
private RabbitProducer producer;
@Resource
private TbOrderInfoMapper orderInfoMapper;
@@ -48,36 +50,19 @@ public class OrderService {
@Resource
private TbShopTableMapper shopTableMapper;
@Resource
private TbProductSkuMapper productSkuMapper;
@Resource
private TbUserInfoMapper userInfoMapper;
@Autowired
private TbWiningUserMapper tbWiningUserMapper;
@Resource
private TbOrderDetailMapper tbOrderDetailMapper;
@Autowired
private TbReleaseFlowMapper releaseFlowMapper;
@Resource
private TbParamsMapper paramsMapper;
@Resource
private RedisUtil redisUtil;
@Resource
private RedisUtils redisUtils;
@Resource
private TbUserCouponsMapper userCouponsMapper;
@Resource
private TbSystemCouponsMapper systemCouponsMapper;
@Autowired
private TbYhqParamsMapper yhqParamsMapper;
@Autowired
private TbShopUserMapper shopUserMapper;
@Autowired
private TbOrderInfoMapper tbOrderInfoMapper;
private MpCashierCartMapper mpCashierCartMapper;
@Autowired
private MpOrderDetailMapper mpOrderDetailMapper;
@Autowired
private MpOrderInfoMapper mpOrderInfoMapper;
@Autowired
private MpShopInfoMapper mpShopInfoMapper;
/**
* 创建订单
*
@@ -208,10 +193,20 @@ public class OrderService {
orderVo.setOrderId(orderInfo.getId());
orderVo.setSendType(orderInfo.getSendType());
orderVo.setOutNumber(orderInfo.getOutNumber());
orderVo.setUseType(orderInfo.getUseType());
orderVo.setShopId(Integer.valueOf(orderInfo.getShopId()));
return Result.success(CodeEnum.ENCRYPT, orderVo);
}
public Result rmOrder(Integer orderId) {
int i = orderInfoMapper.deleteByPrimaryKey(orderId);
if (i > 0) {
return Result.success(CodeEnum.SUCCESS);
}
return Result.fail("删除失败");
}
public Result orderList(Integer userId, Integer page, Integer size, String status) {
// TbUserInfo tbUserInfo = userInfoMapper.selectByPrimaryKey(userId);
@@ -220,10 +215,14 @@ public class OrderService {
// }
PageHelper.startPage(page, size);
List<TbOrderInfo> tbOrderInfos = orderInfoMapper.selectByUserId(userId, status);
String shopName = "";
for (TbOrderInfo orderInfo : tbOrderInfos) {
orderInfo.setDescription();
List<TbOrderDetail> list = tbOrderDetailMapper.selectAllByOrderId(orderInfo.getId());
TbShopInfo tbShopInfo = tbShopInfoMapper.selectByPrimaryKey(Integer.valueOf(orderInfo.getShopId()));
shopName = tbShopInfo.getShopName();
orderInfo.setDescription(shopName);
List<TbOrderDetail> list = mpOrderDetailMapper.selectList(new LambdaQueryWrapper<TbOrderDetail>()
.eq(TbOrderDetail::getOrderId, orderInfo.getId())
.ne(TbOrderDetail::getProductId, TableConstant.CART_SEAT_ID));
int num = 0;
for (TbOrderDetail orderDetail : list) {
num = num + orderDetail.getNum();
@@ -248,178 +247,87 @@ public class OrderService {
}
@Transactional(rollbackFor = Exception.class)
public Result tradeIntegral(String userId, String id) throws ParseException {
updateIntegral(userId, id);
return Result.success(CodeEnum.ENCRYPT);
}
public Object orderDetail(Integer orderId) {
private void updateIntegral(String userId, String id) throws ParseException {
TbOrderInfo orderInfo = mpOrderInfoMapper.selectOne(new LambdaQueryWrapper<TbOrderInfo>()
.eq(TbOrderInfo::getId, orderId));
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);
if (orderInfo == null) {
return Result.fail("订单不存在");
}
}
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;
TbShopInfo shopInfo = tbShopInfoMapper.selectByPrimaryKey(Integer.valueOf(orderInfo.getShopId()));
if (shopInfo == null) {
return Result.fail("店铺不存在");
}
LambdaQueryWrapper<TbOrderDetail> queryWrapper = new LambdaQueryWrapper<TbOrderDetail>()
.eq(TbOrderDetail::getShopId, orderInfo.getShopId())
.ne(TbOrderDetail::getProductId, TableConstant.CART_SEAT_ID)
.eq(TbOrderDetail::getOrderId, orderId);
List<TbOrderDetail> list = mpOrderDetailMapper.selectList(queryWrapper);
AtomicReference<TbOrderDetail> mealCashierCart = new AtomicReference<>();
list.forEach(item -> {
item.setPlaceNum(item.getPlaceNum() == null ? 0 : item.getPlaceNum());
if (item.getProductId() == -999) {
mealCashierCart.set(item);
}
});
// 根据placeNum进行分组
Map<Integer, List<TbOrderDetail>> groupedByPlaceNum = list.stream()
.collect(Collectors.groupingBy(TbOrderDetail::getPlaceNum));
ArrayList<HashMap<String, Object>> dataList = new ArrayList<>();
groupedByPlaceNum.forEach((k, v) -> {
HashMap<String, Object> item = new HashMap<>();
item.put("placeNum", k);
item.put("placeTime", v.isEmpty() ? null : DateUtil.format(v.get(0).getCreateTime(), "HH:mm:ss"));
BigDecimal totalPrice = BigDecimal.ZERO;
for (TbOrderDetail d : v) {
totalPrice = totalPrice.add(d.getPriceAmount());
}
item.put("info", v);
item.put("totalAmount", totalPrice);
dataList.add(item);
});
TbShopTable tbShopTable = shopTableMapper.selectQRcode(orderInfo.getTableId());
OrderVo orderVo = new OrderVo();
orderVo.setName(shopInfo.getShopName());
orderVo.setStatus(orderInfo.getStatus());
//TODO 增加商家二维码
orderVo.setShopQrcode(shopInfo.getShopQrcode());
orderVo.setDetails(list);
orderVo.setOrderNo(orderInfo.getOrderNo());
orderVo.setTime(orderInfo.getCreatedAt());
if (orderInfo.getStatus().equals("paying") || orderInfo.getStatus().equals("unpaid")) {
long totalSeconds = orderInfo.getCreatedAt() + 15 * 60 * 1000l - System.currentTimeMillis();
if(totalSeconds>0){
orderVo.setExpiredMinutes(totalSeconds/1000 / 60);
orderVo.setExpiredSeconds(totalSeconds/1000 % 60);
}
}
return typeName;
}
public Result mineCoupons(String userId, String orderId,String status, Integer page, Integer size) {
BigDecimal amount=null;
if(ObjectUtil.isNotNull(orderId)&&ObjectUtil.isNotEmpty(orderId)){
TbOrderInfo orderInfo= tbOrderInfoMapper.selectByPrimaryKey(Integer.valueOf(orderId));
amount=orderInfo.getOriginAmount();
}
PageHelper.startPage(page, size);
List<TbUserCoupons> list = userCouponsMapper.selectByUserId(userId,status,amount);
PageInfo pageInfo = new PageInfo(list);
return Result.success(CodeEnum.SUCCESS, pageInfo);
}
public Result findCoupons(String type, Integer page, Integer size) {
PageHelper.startPage(page, size);
List<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);
if (Objects.nonNull(userCoupons)){
TbOrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId);
userCoupons.setOrderInfo(orderInfo);
}
return Result.success(CodeEnum.SUCCESS,userCoupons);
}
@Transactional(rollbackFor = Exception.class)
public Result yhqDouble(Integer conponsId) {
TbUserCoupons userCoupons = userCouponsMapper.selectByPrimaryKey(conponsId);
if (Objects.isNull(userCoupons) || userCoupons.getIsDouble().equals("true")){
throw new MsgException("该优惠券翻倍已领取");
}
modityDouble(conponsId);
return Result.success(CodeEnum.SUCCESS);
}
private void modityDouble(Integer conponsId) {
boolean lock_coin = redisUtils.lock(RedisCst.COUPONS_COIN_KEY + conponsId, 5000, TimeUnit.MILLISECONDS);
if (lock_coin) {
TbUserCoupons userCoupons = userCouponsMapper.selectByPrimaryKey(conponsId);
if (Objects.isNull(userCoupons) || !userCoupons.getStatus().equals("0") || userCoupons.getIsDouble().equals("true")) {
throw new MsgException("该优惠券已翻倍");
}
TbParams params = shopUserMapper.selectParams();
userCoupons.setIsDouble("true");
userCoupons.setCouponsAmount(userCoupons.getCouponsAmount().multiply(params.getTwoRatio()));
userCoupons.setCouponsPrice(userCoupons.getCouponsPrice().multiply(params.getTwoRatio()));
userCoupons.setUpdateTime(new Date());
userCouponsMapper.updateByPrimaryKeySelective(userCoupons);
redisUtils.releaseLock(RedisCst.COUPONS_COIN_KEY + conponsId);
} else {
modityDouble(conponsId);
}
}
public Result mineWinner(Integer userId, Integer page, Integer size) {
PageHelper.startPage(page, size);
List<TbOrderInfo> list = orderInfoMapper.selectWinnerByUserId(userId);
for (TbOrderInfo tbOrderInfo:list){
if (StringUtils.isNotEmpty(tbOrderInfo.getWinnnerNo())){
tbOrderInfo.setIsWinner("true");
}else {
tbOrderInfo.setIsWinner("false");
}
}
PageInfo pageInfo = new PageInfo(list);
if (page > pageInfo.getPages()) {
pageInfo.setList(Collections.emptyList());
}
return Result.success(CodeEnum.SUCCESS, pageInfo);
}
public Result kc() {
List<TbProductSku> list = productSkuMapper.selectAll();
for (TbProductSku productSku:list){
redisUtil.saveMessage(RedisCst.PRODUCT + productSku.getShopId() + ":" +productSku.getId(),"10000");
}
return Result.success(CodeEnum.SUCCESS);
orderVo.setPayAmount(orderInfo.getOrderAmount());
orderVo.setTableName(tbShopTable == null ? "" : tbShopTable.getName());
orderVo.setOrderType(orderInfo.getOrderType());
orderVo.setOrderId(orderInfo.getId());
orderVo.setSendType(orderInfo.getSendType());
orderVo.setOutNumber(orderInfo.getOutNumber());
orderVo.setUseType(orderInfo.getUseType());
orderVo.setShopId(Integer.valueOf(orderInfo.getShopId()));
orderVo.setQrcode(shopInfo.getShopQrcode());
Map<String, Object> map = new HashMap<>();
// 餐位费
map.put("seatFee", mealCashierCart);
map.put("detailList", dataList);
map.put("orderInfo", orderInfo);
map.putAll(BeanUtil.beanToMap(orderVo, false, false));
map.put("createdAt", DateUtil.formatDateTime(DateUtil.date(orderInfo.getCreatedAt())));
map.put("paidTime", orderInfo.getPaidTime() == null ? null : DateUtil.formatDateTime(DateUtil.date(orderInfo.getPaidTime())));
map.put("registerType", shopInfo.getRegisterType());
return map;
}
}

View File

@@ -1,17 +1,29 @@
package com.chaozhanggui.system.cashierservice.service;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chaozhanggui.system.cashierservice.constant.TableConstant;
import com.chaozhanggui.system.cashierservice.dao.*;
import com.chaozhanggui.system.cashierservice.entity.*;
import com.chaozhanggui.system.cashierservice.entity.dto.HomeDto;
import com.chaozhanggui.system.cashierservice.entity.dto.QuerySpecDTO;
import com.chaozhanggui.system.cashierservice.entity.Enum.OrderUseTypeEnum;
import com.chaozhanggui.system.cashierservice.entity.Enum.PlatformTypeEnum;
import com.chaozhanggui.system.cashierservice.entity.Enum.ShopInfoEatModelEnum;
import com.chaozhanggui.system.cashierservice.entity.dto.*;
import com.chaozhanggui.system.cashierservice.entity.vo.*;
import com.chaozhanggui.system.cashierservice.exception.MsgException;
import com.chaozhanggui.system.cashierservice.mapper.MpCashierCartMapper;
import com.chaozhanggui.system.cashierservice.mapper.MpOrderInfoMapper;
import com.chaozhanggui.system.cashierservice.mapper.MpShopTableMapper;
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.*;
@@ -22,6 +34,7 @@ import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
@@ -75,25 +88,85 @@ public class ProductService {
@Autowired
private TbUserInfoMapper tbUserInfoMapper;
public Result queryShopIdByTableCode(String userId, String openId, String code, String lat, String lng) {
if (StringUtils.isBlank(code)) return Result.fail("桌码信息为空");
@Autowired
private TbProskuConMapper tbProskuConMapper;
@Autowired
private TbConsInfoMapper tbConsInfoMapper;
@Resource
private TbActivateInRecordService activateInRecordService;
private final ShopUtils shopUtils;
@Autowired
private MpShopTableMapper mpShopTableMapper;
@Autowired
private MpCashierCartMapper mpCashierCartMapper;
@Autowired
private MpOrderInfoMapper mpOrderInfoMapper;
@Autowired
private RedisUtil redisUtil;
@Autowired
private StringRedisTemplate stringRedisTemplate;
public ProductService(ShopUtils shopUtils) {
this.shopUtils = shopUtils;
}
private TbOrderInfo getCurrentOrder(ShopEatTypeInfoDTO eatTypeInfoDTO, String tableId, Object shopId) {
// 获取当前台桌最新订单,先付款模式不获取
if (eatTypeInfoDTO.isDineInBefore()) {
return null;
}
List<TbOrderInfo> orderInfoList = mpOrderInfoMapper.selectPage(new Page<>(1, 1), new LambdaQueryWrapper<TbOrderInfo>()
.eq(TbOrderInfo::getStatus, "unpaid")
.eq(TbOrderInfo::getUseType, eatTypeInfoDTO.getUseType())
.eq(TbOrderInfo::getShopId, shopId)
.gt(TbOrderInfo::getCreatedAt, DateUtil.date().getTime() - 1000 * 60 * 60 * 24)
.eq(TbOrderInfo::getTableId, tableId)
.orderByDesc(TbOrderInfo::getId)).getRecords();
return orderInfoList.isEmpty() ? null : orderInfoList.get(0);
}
public Result queryShopIdByTableCode(String userId, String openId, String code, String lat, String lng, Integer shopId) {
if (StringUtils.isBlank(lat) || lat.equals("undefined")) {
lat = "34.343207";
lng = "108.939645";
}
TbShopTable tbShopTable = tbShopTableMapper.selectQRcode(code);
if (tbShopTable == null) {
return Result.fail("台桌信息不存在");
TbShopTable tbShopTable = null;
if (StrUtil.isNotBlank(code)) {
tbShopTable = tbShopTableMapper.selectQRcode(code);
if (tbShopTable == null) {
return Result.fail("台桌信息不存在");
}
}
TbShopInfo shopInfo = tbShopInfoMapper.selectByPrimaryKey(tbShopTable.getShopId());
TbShopInfo shopInfo = tbShopInfoMapper.selectByPrimaryKey(shopId != null ? shopId : tbShopTable.getShopId());
String distance = LocationUtils.getDistanceString(
Double.parseDouble(lng), Double.parseDouble(lat),
Double.parseDouble(shopInfo.getLng()), Double.parseDouble(shopInfo.getLat()));
ConcurrentMap<String, Object> concurrentMap = new ConcurrentHashMap<>();
concurrentMap.put("shopTableInfo", tbShopTable);
// 获取当前台桌最新订单id
ShopEatTypeInfoDTO shopEatTypeInfoDTO = shopUtils.getEatModel(code, shopInfo.getId());
if (tbShopTable != null) {
if (shopEatTypeInfoDTO.isOpenDineIn()) {
TbOrderInfo order = getCurrentOrder(shopEatTypeInfoDTO, code, shopInfo.getId());
tbShopTable.setOrderId(order == null ? null : order.getId());
TbCashierCart seatCartInfo = getSeatCartInfo(tbShopTable.getShopId(), tbShopTable.getQrcode(), shopEatTypeInfoDTO);
tbShopTable.setChoseCount((shopInfo.getIsTableFee() != null && shopInfo.getIsTableFee().equals(1)) || (seatCartInfo != null && (seatCartInfo.getNumber() != null)));
tbShopTable.setSeatNum(seatCartInfo != null ? seatCartInfo.getNumber() : 0);
}else {
shopEatTypeInfoDTO.setUseType(OrderUseTypeEnum.TAKEOUT.getValue());
TbOrderInfo order = getCurrentOrder(shopEatTypeInfoDTO, code, shopInfo.getId());
tbShopTable.setOrderId(order == null ? null : order.getId());
tbShopTable.setChoseCount(true);
}
}
concurrentMap.put("shopTableInfo", tbShopTable == null ? "" : tbShopTable);
concurrentMap.put("storeInfo", shopInfo);
concurrentMap.put("distance", distance);
TbShopUser shopUser = tbShopUserMapper.selectByUserIdAndShopId(userId, tbShopTable.getShopId().toString());
TbShopUser shopUser = tbShopUserMapper.selectByUserIdAndShopId(userId, shopId != null ? shopId.toString() : tbShopTable.getShopId().toString());
try {
if (ObjectUtil.isEmpty(shopUser)) {
TbUserInfo tbUserInfo = tbUserInfoMapper.selectByPrimaryKey(Integer.valueOf(userId));
@@ -114,7 +187,7 @@ public class ProductService {
shopUser.setConsumeNumber(0);
shopUser.setLevelConsume(BigDecimal.ZERO);
shopUser.setStatus(Byte.parseByte("1"));
shopUser.setShopId(tbShopTable.getShopId().toString());
shopUser.setShopId(shopId != null ? shopId.toString() : tbShopTable.getShopId().toString());
shopUser.setUserId(userId);
shopUser.setMiniOpenId(openId);
shopUser.setCreatedAt(System.currentTimeMillis());
@@ -136,27 +209,26 @@ public class ProductService {
return Result.success(CodeEnum.SUCCESS, concurrentMap);
}
public Result queryProduct(String shopId, String productGroupId) {
public Result queryProduct(String userId,String shopId, String productGroupId) {
ConcurrentMap<String, Object> concurrentMap = new ConcurrentHashMap<>();
Integer id = ObjectUtil.isNotEmpty(productGroupId) ? Integer.valueOf(productGroupId) : null;
//招牌菜
List<TbProduct> tbProducts = tbProductMapper.selectIsSpecialty(Integer.valueOf(shopId));
concurrentMap.put("hots", handleDate(tbProducts,true,1));
concurrentMap.put("hots", handleDate(tbProducts,true,1,false));
List<TbProductGroup> groupList = tbProductGroupMapper.selectByShopId(shopId, id);
if (ObjectUtil.isNotEmpty(groupList) && groupList.size() > 0) {
//热销
TbProductGroup hot = new TbProductGroup();
hot.setName("热销");
List<TbProduct> hots = tbProductMapper.selectHot(shopId);
hot.setProducts(handleDate(hots,true,1));
hot.setProducts(handleDate(hots,true,1,false));
//商品
groupList.parallelStream().forEach(g -> {
if (g.getUseTime()==1) g.setIsSale(getIsSale(g.getSaleStartTime(),g.getSaleEndTime()));
String in = g.getProductIds().substring(1, g.getProductIds().length() - 1);
if (ObjectUtil.isNotEmpty(in) && ObjectUtil.isNotNull(in)) {
// List<TbProduct> products = tbProductMapper.selectByIdIn(in);
List<TbProduct> products = tbProductMapper.selectByIdInAndCheck(in);
g.setProducts(handleDate(products,false,g.getIsSale()));
g.setProducts(handleDate(products,false,g.getIsSale(),false));
} else {
g.setProducts(new ArrayList<>());
}
@@ -216,7 +288,8 @@ public class ProductService {
// 重组有效规格数据
String tagSnap = skuResult != null ? skuResult.getTagSnap() : null;
List<TbProductSku> tbProductSkus = tbProductSkuMapper.selectGroundingByProId(querySpecDTO.getProductId());
// List<TbProductSku> tbProductSkus = tbProductSkuMapper.selectGroundingByProId(querySpecDTO.getProductId());
List<TbProductSku> tbProductSkus = tbProductSkuMapper.selectSku(String.valueOf(querySpecDTO.getProductId()));
JSONArray finalSnap = new JSONArray();
// if (tagSnap != null) {
@@ -298,11 +371,17 @@ public class ProductService {
}
ArrayList<HashMap<String, Object>> specList = new ArrayList<>();
HashMap<String, TbProductSku> unGroundingMap = new HashMap<>();
tbProductSkus.forEach(item -> {
HashMap<String, Object> itemMap = new HashMap<>();
itemMap.put("specSnap", item.getSpecSnap());
itemMap.put("skuId", item.getId());
specList.add(itemMap);
if (item.getIsGrounding() == 1) {
HashMap<String, Object> itemMap = new HashMap<>();
itemMap.put("specSnap", item.getSpecSnap());
itemMap.put("skuId", item.getId());
itemMap.put("info", item);
specList.add(itemMap);
}else {
unGroundingMap.put(item.getSpecSnap(), item);
}
});
@@ -312,6 +391,14 @@ public class ProductService {
for (HashMap<String, Object> spec : specList) {
if (res.equals(spec.get("specSnap").toString())) {
spec.put("isGrounding", true);
TbProductSku sku = (TbProductSku) spec.get("info");
if (sku != null) {
tbProduct.setIsPauseSale(sku.getIsPauseSale().byteValue());
checkPauseSale(tbProduct, new ArrayList<>(Collections.singletonList(sku)), true);
spec.put("isPauseSale", tbProduct.getIsPauseSale());
}else {
spec.put("isPauseSale", 1);
}
found = true;
break;
}
@@ -321,6 +408,14 @@ public class ProductService {
itemMap.put("specSnap", res);
itemMap.put("skuId", null);
itemMap.put("isGrounding", false);
TbProductSku sku = unGroundingMap.get("specSnap");
if (sku != null) {
tbProduct.setIsPauseSale(sku.getIsPauseSale().byteValue());
checkPauseSale(tbProduct, Collections.singletonList(sku), true);
itemMap.put("isPauseSale", tbProduct.getIsPauseSale());
}else {
itemMap.put("isPauseSale", 1);
}
otherVal.add(itemMap);
}
}
@@ -347,9 +442,11 @@ public class ProductService {
* @param check 是否校验可售
* @return
*/
public List<TbProduct> handleDate(List<TbProduct> products,boolean check,Integer isSale){
public List<TbProduct> handleDate(List<TbProduct> products,boolean check,Integer isSale,boolean isVip){
if (!CollectionUtils.isEmpty(products)) {
products.parallelStream().forEach(it -> {
TbShopUnit tbShopUnit = unitMapper.selectByPrimaryKey(Integer.valueOf(it.getUnitId()));
it.setUnitSnap(tbShopUnit != null ? tbShopUnit.getName() : "");
if(check){
List<TbProductGroup> tbProductGroups = tbProductGroupMapper.selectByProductId(it.getShopId(), it.getId().toString());
for (TbProductGroup g : tbProductGroups) {
@@ -363,15 +460,14 @@ public class ProductService {
}else {
it.setIsSale(isSale);
}
TbShopUnit tbShopUnit = unitMapper.selectByPrimaryKey(Integer.valueOf(it.getUnitId()));
it.setUnitSnap(tbShopUnit != null ? tbShopUnit.getName() : "");
//购物车数量
it.setCartNumber("0");
List<TbProductSku> tbProductSkus = tbProductSkuMapper.selectGroundingByProId(it.getId());
TbProductSkuResult skuResult = tbProductSkuResultMapper.selectByPrimaryKey(it.getId());
// 上下架对应的sku
// HashSet<String> specSet = new HashSet<>();
//判断库存及耗材
checkPauseSale(it,tbProductSkus, false);
AtomicDouble sum = new AtomicDouble(0.0);
BigDecimal lowerPrice = null;
BigDecimal lowMemberPrice = null;
@@ -401,6 +497,10 @@ public class ProductService {
}
it.setLowMemberPrice(lowMemberPrice);
it.setProductSkuResult(skuResult);
if (isVip) {
it.setLowPrice(BigDecimal.ZERO);
it.setIsVip(Byte.parseByte("1"));
}
});
return products;
}else {
@@ -408,9 +508,43 @@ public class ProductService {
}
}
public void checkPauseSale(TbProduct tbProduct, List<TbProductSku> skus, boolean isSingle) {
if (tbProduct.getIsStock() == 1) {//库存开关 1开启
if (tbProduct.getStockNumber() != null && tbProduct.getStockNumber() <= 0) {
tbProduct.setIsPauseSale(Byte.parseByte("1"));//售罄 1暂停
return;
}
public Result queryProductSku(String code, String shopId, String productId, String spec_tag) {
if (ObjectUtil.isEmpty(shopId) || ObjectUtil.isEmpty(productId)) {
if (isSingle && tbProduct.getIsPauseSale() == 1) {
return;
}
Iterator<TbProductSku> iterator = skus.iterator();
while (iterator.hasNext()) {
TbProductSku tbProductSku = iterator.next();
List<TbProskuCon> proskuConList = tbProskuConMapper.selectByShopIdAndSkuIdAndProductId(Integer.valueOf(tbProductSku.getId()), Integer.valueOf(tbProductSku.getShopId()), Integer.valueOf(tbProductSku.getProductId()));
if (Objects.nonNull(proskuConList) && proskuConList.size() > 0) {
for (TbProskuCon proskuCon : proskuConList) {
if ("1".equals(proskuCon.getStatus())) {
TbConsInfo consInfo = tbConsInfoMapper.selectByPrimaryKey(proskuCon.getConInfoId());
if ("1".equals(consInfo.getIsCheck())) {
if (N.gt(proskuCon.getSurplusStock(), consInfo.getStockNumber().abs().subtract(consInfo.getStockConsume().abs()))) {
iterator.remove();
break;
}
}
}
}
}
}
if (CollectionUtils.isEmpty(skus)) {
tbProduct.setIsPauseSale(Byte.parseByte("1"));//售罄 1暂停
}
}
}
public Result queryProductSku(String code, String shopId, String productId, String spec_tag,String isVip) {
if (ObjectUtil.isEmpty(shopId) || ObjectUtil.isEmpty(productId) || StringUtils.isEmpty(isVip)|| isVip.equals("undefined") ) {
return Result.fail("参数错误");
}
TbProductSkuWithBLOBs tbProductSkuWithBLOBs = tbProductSkuMapper.selectByShopIdAndProductIdAndSpec(shopId, productId, spec_tag);
@@ -423,7 +557,7 @@ public class ProductService {
tbProductSkuWithBLOBs.setId(null);
}else {
if (StringUtils.isNotBlank(code)) {
Integer sum = tbProductMapper.selectByCodeAndSkuId(code, tbProductSkuWithBLOBs.getId(), shopId);
Integer sum = tbProductMapper.selectByCodeAndSkuId(code, tbProductSkuWithBLOBs.getId(), shopId,isVip);
tbProductSkuWithBLOBs.setNumber(sum);
}
}
@@ -703,39 +837,133 @@ public class ProductService {
* @param buyNum 购买数量
*/
public void updateStock(TbProduct tbProduct, TbProductSkuWithBLOBs tbProductSkuWithBLOBs, Integer buyNum) {
if (tbProduct.getIsDistribute() == 1) {
if (tbProductMapper.decrStock(String.valueOf(tbProduct.getId()), buyNum) < 1) {
throw new MsgException("库存修改失败,请稍后再试");
}
} else {
if (tbProductSkuMapper.decrStock(String.valueOf(tbProductSkuWithBLOBs.getId()), buyNum) < 1) {
throw new MsgException("库存修改失败,请稍后再试");
}
if (tbProductMapper.decrStock(String.valueOf(tbProduct.getId()), buyNum) < 1) {
throw new MsgException("库存修改失败,请稍后再试");
}
}
public void updateStock(String id, Integer skuId, Integer buyNum, boolean isDistribute) {
if (isDistribute) {
if (tbProductMapper.decrStock(String.valueOf(id), buyNum) < 1) {
throw new MsgException("库存不足,下单失败");
}
} else {
if (tbProductSkuMapper.decrStock(String.valueOf(skuId), buyNum) < 1) {
throw new MsgException("库存不足,下单失败");
}
public void updateStock(String id, Integer skuId, Integer buyNum) {
if (tbProductMapper.decrStock(String.valueOf(id), buyNum) < 1) {
throw new MsgException("库存不足,下单失败");
}
}
public void updateStockAndNoCheck(String id, Integer skuId, Integer buyNum, boolean isDistribute) {
if (isDistribute) {
if (tbProductMapper.decrStockUnCheck(String.valueOf(id), buyNum) < 1) {
throw new MsgException("库存不足,下单失败");
}
} else {
if (tbProductSkuMapper.decrStockUnCheck(String.valueOf(skuId), buyNum) < 1) {
throw new MsgException("库存不足,下单失败");
}
public void updateStockAndNoCheck(String id, Integer skuId, Integer buyNum) {
if (tbProductMapper.decrStockUnCheck(String.valueOf(id), buyNum) < 1) {
throw new MsgException("库存不足,下单失败");
}
}
public TbCashierCart choseCount(ChoseCountDTO choseCountDTO) {
return Utils.runFunAndCheckKey(() -> {
ShopEatTypeInfoDTO shopEatTypeInfoDTO = shopUtils.checkEatModel(choseCountDTO.getTableId(), choseCountDTO.getShopId());
TbShopInfo shopInfo = tbShopInfoMapper.selectByPrimaryKey(choseCountDTO.getShopId());
if (shopInfo == null) throw new MsgException("店铺信息不存在");
if (shopInfo.getIsTableFee() != null && shopInfo.getIsTableFee() == 1) {
throw new MsgException("当前店铺无需选择餐位费");
}
TbShopTable shopTable = mpShopTableMapper.selectOne(new LambdaQueryWrapper<TbShopTable>()
.eq(TbShopTable::getQrcode, choseCountDTO.getTableId()));
if (shopTable == null) {
throw new MsgException("台桌不存在");
}
if (shopTable.getMaxCapacity() < choseCountDTO.getNum()) {
throw new MsgException("当前台桌最大人数为: " + shopTable.getMaxCapacity());
}
Integer userId = TokenUtil.getUserId();
TbCashierCart tbCashierCart = getSeatCartInfo(choseCountDTO.getShopId(), choseCountDTO.getTableId(), shopEatTypeInfoDTO);
if (tbCashierCart == null) {
tbCashierCart = new TbCashierCart();
tbCashierCart.setStatus("create");
tbCashierCart.setCreatedAt(System.currentTimeMillis());
tbCashierCart.setTableId(choseCountDTO.getTableId());
tbCashierCart.setName("客座费");
tbCashierCart.setSalePrice(shopInfo.getTableFee());
tbCashierCart.setShopId(String.valueOf(choseCountDTO.getShopId()));
tbCashierCart.setTradeDay(DateUtils.getDay());
tbCashierCart.setStatus("create");
tbCashierCart.setTotalAmount(new BigDecimal(choseCountDTO.getNum()).multiply(shopInfo.getTableFee()));
tbCashierCart.setPlaceNum(1);
tbCashierCart.setProductId(TableConstant.CART_SEAT_ID);
tbCashierCart.setSkuId(TableConstant.CART_SEAT_ID);
tbCashierCart.setPackFee(BigDecimal.ZERO);
tbCashierCart.setNumber(choseCountDTO.getNum());
tbCashierCart.setTotalNumber(choseCountDTO.getNum());
tbCashierCart.setUseType(shopEatTypeInfoDTO.getUseType());
tbCashierCart.setPlatformType(PlatformTypeEnum.MINI_APP.getValue());
tbCashierCart.setUserId(userId);
mpCashierCartMapper.insert(tbCashierCart);
} else {
tbCashierCart.setTotalAmount(new BigDecimal(choseCountDTO.getNum()).multiply(shopInfo.getTableFee()));
tbCashierCart.setNumber(choseCountDTO.getNum());
tbCashierCart.setTotalNumber(choseCountDTO.getNum());
tbCashierCart.setUseType(shopEatTypeInfoDTO.getUseType());
tbCashierCart.setPlatformType(PlatformTypeEnum.MINI_APP.getValue());
tbCashierCart.setUserId(userId);
mpCashierCartMapper.updateById(tbCashierCart);
}
// 将数据加入缓存
String tableCartKey = RedisCst.getTableCartKey(String.valueOf(choseCountDTO.getShopId()), choseCountDTO.getTableId(), userId);
String message = redisUtil.getMessage(tableCartKey);
JSONArray jsonArray;
if (StrUtil.isNotBlank(message)) {
jsonArray = JSONObject.parseArray(message);
}else {
jsonArray = new JSONArray();
}
long count = jsonArray.stream().filter(item -> TableConstant.CART_SEAT_ID.equals(((JSONObject) item).getString("productId"))).count();
if (count < 1) {
jsonArray.add(tbCashierCart);
redisUtil.saveMessage(tableCartKey, jsonArray.toJSONString());
}
// 保存就餐人数信息
redisUtil.saveMessage(RedisCst.getCurrentTableSeatCount(choseCountDTO.getShopId(), choseCountDTO.getTableId()),
JSONObject.toJSONString(tbCashierCart), 60L * 60 * 12);
return tbCashierCart;
}, stringRedisTemplate, RedisCst.getLockKey(RedisCst.CHOSE_TABLE_COUNT, choseCountDTO.getShopId(), choseCountDTO.getTableId()));
}
private TbCashierCart getSeatCartInfo(Object shopId, String tableId, ShopEatTypeInfoDTO shopEatTypeInfoDTO) {
LambdaQueryWrapper<TbCashierCart> query = new LambdaQueryWrapper<TbCashierCart>()
.eq(TbCashierCart::getShopId, shopId)
.eq(TbCashierCart::getProductId, TableConstant.CART_SEAT_ID)
.eq(TbCashierCart::getSkuId, TableConstant.CART_SEAT_ID)
.eq(TbCashierCart::getStatus, "create")
.gt(TbCashierCart::getCreatedAt, DateUtil.offsetDay(DateUtil.date(), -1).getTime())
// .and(r -> r.eq(TbCashierCart::getUserId, userId).or().isNull(TbCashierCart::getUserId))
.eq(TbCashierCart::getUseType, shopEatTypeInfoDTO.getUseType())
.eq(TbCashierCart::getTableId, tableId)
.orderByDesc(TbCashierCart::getId);
List<TbCashierCart> cashierCartList = mpCashierCartMapper.selectList(query);
return cashierCartList.isEmpty() ? null : cashierCartList.get(0);
}
public Object choseEatModel(ChoseEatModelDTO choseTableDTO) {
ShopEatTypeInfoDTO shopEatTypeInfoDTO = shopUtils.checkEatModel(choseTableDTO.getTableId(), choseTableDTO.getShopId());
if (!shopEatTypeInfoDTO.isTakeout()) {
TbShopTable shopTable = mpShopTableMapper.selectOne(new LambdaQueryWrapper<TbShopTable>()
.notIn(TbShopTable::getStatus, "closed", "cleaning")
.eq(TbShopTable::getQrcode, choseTableDTO.getTableId()));
if (shopTable == null) {
throw new MsgException("台桌未开台或不存在");
}
}
return mpCashierCartMapper.update(null, new LambdaUpdateWrapper<TbCashierCart>()
.eq(TbCashierCart::getShopId, choseTableDTO.getShopId())
.isNull(TbCashierCart::getUseType)
.eq(TbCashierCart::getStatus, "create")
.set(TbCashierCart::getUseType, shopEatTypeInfoDTO.getUseType())) ;
}
}

View File

@@ -0,0 +1,25 @@
package com.chaozhanggui.system.cashierservice.service;
import com.alibaba.fastjson.JSONObject;
import com.chaozhanggui.system.cashierservice.entity.TbActivate;
import com.chaozhanggui.system.cashierservice.entity.TbCouponProduct;
import com.chaozhanggui.system.cashierservice.entity.TbShopCoupon;
import org.springframework.stereotype.Service;
/**
* 活动商品赠送表(TbActivateInRecord)表服务接口
*
* @author ww
* @since 2024-08-22 11:13:40
*/
@Service
public class TbActivateInRecordService {
public String getCouponJson(TbActivate activate, TbShopCoupon tbShopCoupon, TbCouponProduct couProduct){
JSONObject result = new JSONObject();
result.put("activate",JSONObject.toJSON(activate));
result.put("coupon",JSONObject.toJSON(tbShopCoupon));
result.put("couProduct",JSONObject.toJSON(couProduct));
return result.toJSONString();
}
}

View File

@@ -0,0 +1,13 @@
package com.chaozhanggui.system.cashierservice.service;
import com.chaozhanggui.system.cashierservice.entity.TbCallQueue;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* @author Administrator
* @description 针对表【tb_call_queue】的数据库操作Service
* @createDate 2024-09-13 13:44:26
*/
public interface TbCallQueueService extends IService<TbCallQueue> {
}

View File

@@ -0,0 +1,19 @@
package com.chaozhanggui.system.cashierservice.service;
import com.chaozhanggui.system.cashierservice.entity.dto.CallSubMsgDTO;
import com.chaozhanggui.system.cashierservice.entity.dto.CancelCallQueueDTO;
import com.chaozhanggui.system.cashierservice.entity.dto.TakeNumberDTO;
public interface TbCallService {
Object takeNumber(TakeNumberDTO takeNumberDTO);
Object getList(Integer shopId, String openId, Integer queueId);
Object getAllInfo(Integer shopId);
Object cancel(CancelCallQueueDTO cancelCallQueueDTO);
Object getState(String openId, Integer shopId, Integer queueId);
Object subMsg(CallSubMsgDTO subMsgDTO);
}

View File

@@ -0,0 +1,16 @@
package com.chaozhanggui.system.cashierservice.service;
import com.chaozhanggui.system.cashierservice.entity.TbCallTable;
import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
/**
* @author Administrator
* @description 针对表【tb_call_table】的数据库操作Service
* @createDate 2024-09-13 13:44:34
*/
@Service
public interface TbCallTableService extends IService<TbCallTable> {
}

View File

@@ -0,0 +1,21 @@
package com.chaozhanggui.system.cashierservice.service;
import com.chaozhanggui.system.cashierservice.entity.TbFreeDineConfig;
import com.baomidou.mybatisplus.extension.service.IService;
import com.chaozhanggui.system.cashierservice.entity.TbFreeDineRecord;
/**
* @author Administrator
* @description 针对表【tb_free_dine_config(霸王餐配置信息表)】的数据库操作Service
* @createDate 2024-10-25 14:22:41
*/
public interface TbFreeDineConfigService extends IService<TbFreeDineConfig> {
/**
* 根据店铺id查询
* @param shopId 店铺id
* @return 霸王餐配置
*/
TbFreeDineConfig getByShopId(String shopId);
}

View File

@@ -0,0 +1,27 @@
package com.chaozhanggui.system.cashierservice.service;
import com.chaozhanggui.system.cashierservice.constant.TableConstant;
import com.chaozhanggui.system.cashierservice.entity.TbFreeDineRecord;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* @author Administrator
* @description 针对表【tb_free_dine_record(霸王餐充值记录)】的数据库操作Service
* @createDate 2024-10-30 09:48:31
*/
public interface TbFreeDineRecordService extends IService<TbFreeDineRecord> {
/**
* 根据订单id获取霸王餐记录
* @param orderId 订单id
*/
TbFreeDineRecord selectByOrderId(Integer orderId);
/**
* 根据订单id修改霸王餐记录
* @param state 状态
* @param orderId 订单id
*/
boolean updateStateByOrderId(TableConstant.FreeDineRecord.State state, Integer orderId);
}

View File

@@ -0,0 +1,19 @@
package com.chaozhanggui.system.cashierservice.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.chaozhanggui.system.cashierservice.entity.TbMemberPointsLog;
import com.github.pagehelper.PageInfo;
import java.util.Map;
/**
* 会员积分变动记录
*
* @author Tankaikai tankaikai@aliyun.com
* @since 2.0 2024-10-25
*/
public interface TbMemberPointsLogService extends IService<TbMemberPointsLog> {
PageInfo<TbMemberPointsLog> page(Map<String, Object> params);
}

View File

@@ -0,0 +1,100 @@
package com.chaozhanggui.system.cashierservice.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.chaozhanggui.system.cashierservice.entity.TbMemberPoints;
import com.chaozhanggui.system.cashierservice.entity.dto.OrderDeductionPointsDTO;
import com.github.pagehelper.PageInfo;
import java.math.BigDecimal;
import java.util.Map;
/**
* 会员积分
*
* @author Tankaikai tankaikai@aliyun.com
* @since 2.0 2024-10-25
*/
public interface TbMemberPointsService extends IService<TbMemberPoints> {
/**
* 会员积分分页
*
* @param params
* @return
*/
PageInfo<TbMemberPoints> page(Map<String, Object> params);
/**
* 获取会员积分等信息
*
* @param memberId 会员id
* @return
*/
TbMemberPoints getMemberPoints(Long memberId);
/**
* 初始化会员积分
*
* @param memberId 会员id
* @return
*/
TbMemberPoints initMemberPoints(Long memberId);
/**
* 根据会员id及订单金额计算可抵扣积分及可抵扣金额
*
* @param memberId 会员id
* @param orderAmount 订单金额
* @return
*/
OrderDeductionPointsDTO getMemberUsablePoints(Long memberId, BigDecimal orderAmount);
/**
* 根据抵扣金额计算抵扣积分
*
* @param memberId 会员id
* @param orderAmount 订单金额
* @param deductionAmount 抵扣金额
*/
int calcUsedPoints(Long memberId, BigDecimal orderAmount, BigDecimal deductionAmount);
/**
* 根据抵扣积分计算抵扣金额
*
* @param memberId 会员id
* @param orderAmount 订单金额
* @param points 抵扣积分
*/
BigDecimal calcDeductionAmount(Long memberId, BigDecimal orderAmount, int points);
/**
* 扣除积分
*
* @param memberId 会员id
* @param points 积分
* @param content 摘要信息(如:兑换积分商品/积分抵扣账单/消费赠送积分/新会员送积分/储值赠送积分)
* @param orderId 订单id可以为空
* @throws Exception
*/
boolean deductPoints(Long memberId, int points, String content, Long orderId);
/**
* 追加积分
*
* @param memberId 会员id
* @param points 积分
* @param content 摘要信息(如:兑换积分商品/积分抵扣账单/消费赠送积分/新会员送积分/储值赠送积分)
* @param orderId 订单id可以为空
* @throws Exception
*/
boolean addPoints(Long memberId, int points, String content, Long orderId);
/**
* 消费赠送积分
*
* @param memberId 会员id
* @param orderId 订单id
* @throws Exception
*/
void consumeAwardPoints(Long memberId, Long orderId);
}

View File

@@ -0,0 +1,16 @@
package com.chaozhanggui.system.cashierservice.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.chaozhanggui.system.cashierservice.entity.TbPointsBasicSetting;
/**
* 积分基本设置
*
* @author Tankaikai tankaikai@aliyun.com
* @since 2.0 2024-10-25
*/
public interface TbPointsBasicSettingService extends IService<TbPointsBasicSetting> {
boolean save(TbPointsBasicSetting entity);
TbPointsBasicSetting getByShopId(Long shopId);
}

View File

@@ -0,0 +1,26 @@
package com.chaozhanggui.system.cashierservice.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.chaozhanggui.system.cashierservice.entity.TbPointsExchangeRecord;
import com.github.pagehelper.PageInfo;
import java.util.Map;
/**
* 积分兑换记录
*
* @author Tankaikai tankaikai@aliyun.com
* @since 2.0 2024-10-25
*/
public interface TbPointsExchangeRecordService extends IService<TbPointsExchangeRecord> {
PageInfo<TbPointsExchangeRecord> page(Map<String, Object> params);
TbPointsExchangeRecord get(Long id);
void checkout(String couponCode);
TbPointsExchangeRecord exchange(TbPointsExchangeRecord record);
Map<String, Object> total(Map<String, Object> params);
}

View File

@@ -0,0 +1,25 @@
package com.chaozhanggui.system.cashierservice.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.chaozhanggui.system.cashierservice.entity.TbPointsGoodsSetting;
import com.github.pagehelper.PageInfo;
import java.util.Map;
/**
* 积分商品设置
*
* @author Tankaikai tankaikai@aliyun.com
* @since 2.0 2024-10-25
*/
public interface TbPointsGoodsSettingService extends IService<TbPointsGoodsSetting> {
PageInfo<TbPointsGoodsSetting> page(Map<String, Object> params);
boolean save(TbPointsGoodsSetting entity);
boolean update(TbPointsGoodsSetting dto);
void delete(Long id);
}

View File

@@ -0,0 +1,32 @@
package com.chaozhanggui.system.cashierservice.service;
import com.chaozhanggui.system.cashierservice.entity.TbActivateOutRecord;
import com.chaozhanggui.system.cashierservice.entity.TbOrderInfo;
import com.chaozhanggui.system.cashierservice.entity.dto.CouponDto;
import com.chaozhanggui.system.cashierservice.entity.dto.CouponUseDto;
import com.chaozhanggui.system.cashierservice.entity.vo.TbUserCouponVo;
import com.chaozhanggui.system.cashierservice.sign.Result;
import org.springframework.context.annotation.Primary;
import java.math.BigDecimal;
import java.util.List;
/**
* 优惠券(TbShopCoupon)表服务接口
*
* @author ww
* @since 2024-10-23 15:37:37
*/
public interface TbShopCouponService {
/**
* 根据金额获取可用优惠券
* @param amount 订单金额
*/
List<TbUserCouponVo> getActivateCouponByAmount(Integer shopId, String userId, BigDecimal amount);
Result find(CouponDto param);
boolean use(Integer shopId,Integer orderId,Integer vipUserId,List<TbActivateOutRecord> param);
boolean refund(List<TbActivateOutRecord> param);
}

View File

@@ -1,26 +1,23 @@
package com.chaozhanggui.system.cashierservice.service;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.alibaba.fastjson.JSONObject;
import com.chaozhanggui.system.cashierservice.dao.*;
import com.chaozhanggui.system.cashierservice.entity.TbReleaseFlow;
import com.chaozhanggui.system.cashierservice.dao.TbShopInfoMapper;
import com.chaozhanggui.system.cashierservice.dao.TbShopUserMapper;
import com.chaozhanggui.system.cashierservice.dao.TbUserInfoMapper;
import com.chaozhanggui.system.cashierservice.entity.TbShopInfo;
import com.chaozhanggui.system.cashierservice.entity.TbShopUser;
import com.chaozhanggui.system.cashierservice.entity.TbUserInfo;
import com.chaozhanggui.system.cashierservice.entity.vo.IntegralFlowVo;
import com.chaozhanggui.system.cashierservice.entity.vo.IntegralVo;
import com.chaozhanggui.system.cashierservice.entity.vo.OpenMemberVo;
import com.chaozhanggui.system.cashierservice.exception.MsgException;
import com.chaozhanggui.system.cashierservice.redis.RedisCst;
import com.chaozhanggui.system.cashierservice.sign.CodeEnum;
import com.chaozhanggui.system.cashierservice.sign.Result;
import com.chaozhanggui.system.cashierservice.util.*;
import com.chaozhanggui.system.cashierservice.util.RedisUtils;
import com.chaozhanggui.system.cashierservice.wxUtil.WxAccountUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.Resource;
@@ -32,8 +29,7 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.sql.Timestamp;
@Service
public class UserService {
@@ -42,14 +38,8 @@ public class UserService {
@Autowired
private TbShopUserMapper shopUserMapper;
@Autowired
private TbReleaseFlowMapper releaseFlowMapper;
@Autowired
private TbUserInfoMapper userInfoMapper;
@Autowired
private TbUserCouponsMapper userCouponsMapper;
@Autowired
private TbSystemCouponsMapper systemCouponsMapper;
@Autowired
RedisUtils redisUtils;
@Qualifier("tbShopInfoMapper")
@Autowired
@@ -66,192 +56,8 @@ public class UserService {
this.resourceLoader = resourceLoader;
}
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;
}
public int userCoupon(String userId, BigDecimal orderNum) {
int userNum = userCouponsMapper.selectByUserIdAndAmount(userId,orderNum);
int sysNum = systemCouponsMapper.selectByAmount(orderNum);
return userNum+sysNum;
}
public String getSubQrCode(String shopId) throws Exception {
TbShopInfo shopInfo = tbShopInfoMapper.selectByPrimaryKey(Integer.valueOf(shopId));
@@ -271,25 +77,59 @@ public class UserService {
}
public Result openMember(OpenMemberVo memberVo) {
TbUserInfo userInfo = new TbUserInfo();
userInfo.setId(memberVo.getId());
userInfo.setHeadImg(memberVo.getHeadImg());
userInfo.setNickName(memberVo.getNickName());
userInfo.setTelephone(memberVo.getTelephone());
userInfo.setBirthDay(memberVo.getBirthDay());
userInfoMapper.updateByPrimaryKeySelective(userInfo);
List<TbShopUser> tbShopUsers = shopUserMapper.selectAllByUserId(memberVo.getId().toString());
for (TbShopUser tbShopUser : tbShopUsers) {
tbShopUser.setTelephone(memberVo.getTelephone());
shopUserMapper.updateByPrimaryKey(tbShopUser);
}
TbShopUser tbShopUser = shopUserMapper.selectByUserIdAndShopId(memberVo.getId().toString(), memberVo.getShopId().toString());
tbShopUser.setName(memberVo.getNickName());
tbShopUser.setHeadImg(memberVo.getHeadImg());
tbShopUser.setTelephone(memberVo.getTelephone());
tbShopUser.setBirthDay(memberVo.getBirthDay());
tbShopUser.setIsVip(Byte.parseByte("1"));
shopUserMapper.updateByPrimaryKey(tbShopUser);
if (tbShopUser != null) {
tbShopUser.setName(StringUtils.isNotBlank(memberVo.getNickName()) ? memberVo.getNickName() : null);
tbShopUser.setHeadImg(StringUtils.isNotBlank(memberVo.getHeadImg()) ? memberVo.getHeadImg() : null);
tbShopUser.setTelephone(memberVo.getTelephone());
tbShopUser.setBirthDay(StringUtils.isNotBlank(memberVo.getBirthDay()) ? memberVo.getBirthDay() : null);
tbShopUser.setIsVip(Byte.parseByte("1"));
tbShopUser.setJoinTime(new Timestamp(System.currentTimeMillis()));
shopUserMapper.updateByPrimaryKeySelective(tbShopUser);
} else {
TbUserInfo tbUserInfo = userInfoMapper.selectByPrimaryKey(memberVo.getId());
tbShopUser = shopUserMapper.selectPCByPhoneAndShopId(memberVo.getTelephone(), memberVo.getShopId().toString());
if (tbShopUser != null) {
tbShopUser.setName(StringUtils.isNotBlank(memberVo.getNickName()) ? memberVo.getNickName() : null);
tbShopUser.setHeadImg(StringUtils.isNotBlank(memberVo.getHeadImg()) ? memberVo.getHeadImg() : null);
tbShopUser.setTelephone(memberVo.getTelephone());
tbShopUser.setBirthDay(StringUtils.isNotBlank(memberVo.getBirthDay()) ? memberVo.getBirthDay() : null);
tbShopUser.setUserId(tbUserInfo.getId().toString());
tbShopUser.setMiniOpenId(tbUserInfo.getMiniAppOpenId());
shopUserMapper.updateByPrimaryKeySelective(tbShopUser);
return Result.success(CodeEnum.SUCCESS);
}
tbShopUser = new TbShopUser();
tbShopUser.setName(StringUtils.isNotBlank(memberVo.getNickName()) ? memberVo.getNickName() : null);
tbShopUser.setSex(Byte.parseByte("1"));
tbShopUser.setBirthDay(StringUtils.isNotBlank(memberVo.getBirthDay()) ? memberVo.getBirthDay() : null);
tbShopUser.setLevel(Byte.parseByte("1"));
String dynamicCode = RandomUtil.randomNumbers(8);
tbShopUser.setCode(dynamicCode);
tbShopUser.setTelephone(memberVo.getTelephone());
tbShopUser.setAmount(BigDecimal.ZERO);
tbShopUser.setIsVip(Byte.parseByte("1"));
tbShopUser.setJoinTime(new Timestamp(System.currentTimeMillis()));
tbShopUser.setCreditAmount(BigDecimal.ZERO);
tbShopUser.setConsumeAmount(BigDecimal.ZERO);
tbShopUser.setConsumeNumber(0);
tbShopUser.setLevelConsume(BigDecimal.ZERO);
tbShopUser.setStatus(Byte.parseByte("1"));
tbShopUser.setShopId(memberVo.getShopId().toString());
tbShopUser.setUserId(tbUserInfo.getId().toString());
tbShopUser.setMiniOpenId(tbUserInfo.getMiniAppOpenId());
tbShopUser.setCreatedAt(System.currentTimeMillis());
tbShopUser.setUpdatedAt(System.currentTimeMillis());
shopUserMapper.insertSelective(tbShopUser);
}
return Result.success(CodeEnum.SUCCESS);
}
public Result upVipPhont(OpenMemberVo memberVo) {
TbShopUser shopUser = new TbShopUser();
shopUser.setId(memberVo.getId().toString());
shopUser.setTelephone(memberVo.getTelephone());
shopUserMapper.updateByPrimaryKeySelective(shopUser);
return Result.success(CodeEnum.SUCCESS);
}
}

View File

@@ -0,0 +1,24 @@
package com.chaozhanggui.system.cashierservice.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chaozhanggui.system.cashierservice.entity.TbCallQueue;
import com.chaozhanggui.system.cashierservice.service.TbCallQueueService;
import com.chaozhanggui.system.cashierservice.mapper.TbCallQueueMapper;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
/**
* @author Administrator
* @description 针对表【tb_call_queue】的数据库操作Service实现
* @createDate 2024-09-13 13:44:26
*/
@Service
@Primary
public class TbCallQueueServiceImpl extends ServiceImpl<TbCallQueueMapper, TbCallQueue>
implements TbCallQueueService{
}

View File

@@ -0,0 +1,212 @@
package com.chaozhanggui.system.cashierservice.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.chaozhanggui.system.cashierservice.dao.TbShopInfoMapper;
import com.chaozhanggui.system.cashierservice.entity.TbCallQueue;
import com.chaozhanggui.system.cashierservice.entity.TbCallTable;
import com.chaozhanggui.system.cashierservice.entity.TbShopInfo;
import com.chaozhanggui.system.cashierservice.entity.dto.CallSubMsgDTO;
import com.chaozhanggui.system.cashierservice.entity.dto.CancelCallQueueDTO;
import com.chaozhanggui.system.cashierservice.entity.dto.TakeNumberDTO;
import com.chaozhanggui.system.cashierservice.entity.vo.CallQueueInfoVO;
import com.chaozhanggui.system.cashierservice.exception.MsgException;
import com.chaozhanggui.system.cashierservice.mapper.TbCallQueueMapper;
import com.chaozhanggui.system.cashierservice.redis.RedisCst;
import com.chaozhanggui.system.cashierservice.service.TbCallQueueService;
import com.chaozhanggui.system.cashierservice.service.TbCallService;
import com.chaozhanggui.system.cashierservice.service.TbCallTableService;
import com.chaozhanggui.system.cashierservice.util.MQUtils;
import com.chaozhanggui.system.cashierservice.util.Utils;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
@Service
@AllArgsConstructor
@Primary
public class TbCallServiceImpl implements TbCallService {
private final TbCallQueueService callQueueService;
private final TbCallTableService callTableService;
private final TbShopInfoMapper shopInfoMapper;
private final TbCallQueueMapper callQueueMapper;
private final StringRedisTemplate redisTemplate;
private final MQUtils mQUtils;
private String getCallNumber(Integer shopId, TbCallTable callTable) {
return Utils.runFunAndCheckKey(() -> {
String callNumKey = RedisCst.getTableCallNumKey(shopId, callTable.getId());
String value = redisTemplate.opsForValue().get(callNumKey);
AtomicReference<String> newVal = new AtomicReference<>("");
// 初始化
if (StrUtil.isBlank(value)) {
Boolean setFlag = Utils.runFunAndRetry(() -> redisTemplate.opsForValue().setIfAbsent(callNumKey, callTable.getStart().toString()), flag -> !flag,
r -> newVal.set(redisTemplate.opsForValue().get(callNumKey)));
if (setFlag) {
return callTable.getPrefix() + callTable.getStart();
} else if (StrUtil.isNotBlank(newVal.get())) {
value = String.valueOf((Integer.parseInt(newVal.get()) + 1));
redisTemplate.opsForValue().set(callNumKey, value);
return callTable.getPrefix() + value;
} else {
throw new MsgException("生成排队号码失败");
}
} else {
value = String.valueOf((Integer.parseInt(value) + 1));
redisTemplate.opsForValue().set(callNumKey, value);
return callTable.getPrefix() + value;
}
}, redisTemplate, RedisCst.getLockKey("UPDATE_TABLE", shopId, callTable.getId()));
}
@Override
public Object takeNumber(TakeNumberDTO takeNumberDTO) {
TbShopInfo shopInfo = shopInfoMapper.selectByPrimaryKey(takeNumberDTO.getShopId());
if (shopInfo == null) {
throw new MsgException("店铺信息不存在");
}
TbCallTable callTable = callTableService.lambdaQuery()
.eq(TbCallTable::getShopId, takeNumberDTO.getShopId())
.eq(TbCallTable::getId, takeNumberDTO.getCallTableId()).one();
if (callTable == null) {
throw new MsgException("桌型不存在");
}
TbCallQueue callQueue = callQueueService.lambdaQuery()
// .eq(TbCallQueue::getPhone, takeNumberDTO.getPhone())
.eq(TbCallQueue::getOpenId, takeNumberDTO.getOpenId())
.eq(TbCallQueue::getShopId, takeNumberDTO.getShopId())
.eq(TbCallQueue::getCreateDay, DateUtil.date().toString("yyyy-MM-dd"))
.in(TbCallQueue::getState, 0, 1)
// .ne(TbCallQueue::getIsPostpone, 2)
.eq(TbCallQueue::getCallTableId, takeNumberDTO.getCallTableId()).one();
if (callQueue != null) {
throw new MsgException("您已取号,请勿重复取号");
}
Integer count = callQueueService.lambdaQuery()
.eq(TbCallQueue::getPhone, takeNumberDTO.getPhone())
.eq(TbCallQueue::getShopId, takeNumberDTO.getShopId())
.eq(TbCallQueue::getCreateDay, DateUtil.date().toString("yyyy-MM-dd"))
.in(TbCallQueue::getState, 0, 1)
.eq(TbCallQueue::getCallTableId, takeNumberDTO.getCallTableId()).count();
if (count > 0) {
throw new MsgException("此号码已取号,请更换号码");
}
callQueue = BeanUtil.copyProperties(takeNumberDTO, TbCallQueue.class);
callQueue.setSubState(0);
callQueue.setCreateTime(DateUtil.date());
callQueue.setShopId(shopInfo.getId());
callQueue.setShopName(shopInfo.getShopName());
callQueue.setCallNum(getCallNumber(takeNumberDTO.getShopId(), callTable));
callQueue.setCreateDay(DateUtil.date().toString("yyyy-MM-dd"));
callQueue.setNote(callTable.getNote());
callQueue.setName(callTable.getName());
boolean save = callQueueService.save(callQueue);
// 打印排号票信息
mQUtils.printCallNumTicket(callQueue.getId(), callQueue.getShopId());
return callQueue;
}
@Override
public Object getList(Integer shopId, String openId, Integer queueId) {
return callQueueMapper.selectInfoByOpenId(shopId, openId, DateUtil.date().toString("yyyy-MM-dd"), queueId);
}
@Override
public Object getAllInfo(Integer shopId) {
ArrayList<Map<String, Object>> infoList = new ArrayList<>();
List<TbCallTable> list = callTableService.lambdaQuery()
.eq(TbCallTable::getShopId, shopId).list();
list.forEach(item -> {
Map<String, Object> map = BeanUtil.beanToMap(item, false, false);
Integer count = callQueueService.lambdaQuery()
.eq(TbCallQueue::getCallTableId, item.getId())
.eq(TbCallQueue::getShopId, shopId)
.eq(TbCallQueue::getCreateDay, DateUtil.date().toString("yyyy-MM-dd"))
.in(TbCallQueue::getState, 0, 1).count();
map.put("waitingCount", count);
map.put("waitTime", count * item.getWaitTime());
infoList.add(map);
});
return infoList;
}
@Override
public Object cancel(CancelCallQueueDTO cancelCallQueueDTO) {
return callQueueService.lambdaUpdate()
.eq(TbCallQueue::getShopId, cancelCallQueueDTO.getShopId())
.eq(TbCallQueue::getId, cancelCallQueueDTO.getQueueId())
.set(TbCallQueue::getCallTime, DateUtil.date())
.set(TbCallQueue::getState, -1).update();
}
@Override
public Object getState(String openId, Integer shopId, Integer queueId) {
List<CallQueueInfoVO> callQueueInfoVOS = callQueueMapper.selectInfoByOpenId(shopId, openId, DateUtil.date().toString("yyyy-MM-dd"), null);
if (callQueueInfoVOS.isEmpty()) {
callQueueInfoVOS = callQueueMapper.selectInfoByOpenId(shopId, openId, DateUtil.date().toString("yyyy-MM-dd"), queueId);
}
if (!callQueueInfoVOS.isEmpty()) {
CallQueueInfoVO callQueueInfoVO = callQueueInfoVOS.get(0);
callQueueMapper.update(null, new LambdaUpdateWrapper<TbCallQueue>()
.eq(TbCallQueue::getId, callQueueInfoVO.getId())
.set(TbCallQueue::getOpenId, openId));
}
TbShopInfo shopInfo = shopInfoMapper.selectByPrimaryKey(shopId);
HashMap<String, Object> data = new HashMap<>();
data.put("shopInfo", shopInfo);
data.put("queueInfo", callQueueInfoVOS.isEmpty() ? null : callQueueInfoVOS.get(0));
return data;
}
@Override
public Object subMsg(CallSubMsgDTO subMsgDTO) {
TbCallQueue queue = callQueueMapper.selectOne(new LambdaQueryWrapper<TbCallQueue>()
.eq(TbCallQueue::getShopId, subMsgDTO.getShopId())
.eq(TbCallQueue::getId, subMsgDTO.getQueueId()));
if (queue == null) {
throw new MsgException("您未排号请先排号");
}
if (queue.getOpenId() != null && queue.getOpenId().equals(subMsgDTO.getOpenId()) && queue.getSubState() == 1) {
return true;
}
if (StrUtil.isNotBlank(queue.getOpenId()) && queue.getSubState() == 1) {
throw new MsgException("此号码已被其他用户订阅");
}
if (!subMsgDTO.getOpenId().equals(queue.getOpenId()) && queue.getSubState() == 0) {
Integer count = callQueueService.lambdaQuery()
// .eq(TbCallQueue::getPhone, takeNumberDTO.getPhone())
.eq(TbCallQueue::getOpenId, subMsgDTO.getOpenId())
.eq(TbCallQueue::getShopId, subMsgDTO.getShopId())
.eq(TbCallQueue::getCreateDay, DateUtil.date().toString("yyyy-MM-dd"))
.in(TbCallQueue::getState, 0, 1)
.ne(TbCallQueue::getIsPostpone, 2)
.eq(TbCallQueue::getCallTableId, queue.getCallTableId()).count();
if (count > 0) {
throw new MsgException("您已订阅其他号码,请勿重复订阅");
}
}
queue.setSubState(1);
queue.setOpenId(subMsgDTO.getOpenId());
return callQueueMapper.updateById(queue);
}
}

View File

@@ -0,0 +1,24 @@
package com.chaozhanggui.system.cashierservice.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chaozhanggui.system.cashierservice.entity.TbCallTable;
import com.chaozhanggui.system.cashierservice.service.TbCallTableService;
import com.chaozhanggui.system.cashierservice.mapper.TbCallTableMapper;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
/**
* @author Administrator
* @description 针对表【tb_call_table】的数据库操作Service实现
* @createDate 2024-09-13 13:44:34
*/
@Service
@Primary
public class TbCallTableServiceImpl extends ServiceImpl<TbCallTableMapper, TbCallTable>
implements TbCallTableService{
}

View File

@@ -0,0 +1,33 @@
package com.chaozhanggui.system.cashierservice.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chaozhanggui.system.cashierservice.entity.TbFreeDineConfig;
import com.chaozhanggui.system.cashierservice.entity.TbFreeDineRecord;
import com.chaozhanggui.system.cashierservice.service.TbFreeDineConfigService;
import com.chaozhanggui.system.cashierservice.mapper.TbFreeDineConfigMapper;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
/**
* @author Administrator
* @description 针对表【tb_free_dine_config(霸王餐配置信息表)】的数据库操作Service实现
* @createDate 2024-10-25 14:22:41
*/
@Service
@Primary
public class TbFreeDineConfigServiceImpl extends ServiceImpl<TbFreeDineConfigMapper, TbFreeDineConfig>
implements TbFreeDineConfigService{
@Override
public TbFreeDineConfig getByShopId(String shopId) {
return getOne(new LambdaQueryWrapper<TbFreeDineConfig>()
.eq(TbFreeDineConfig::getShopId, shopId));
}
}

View File

@@ -0,0 +1,39 @@
package com.chaozhanggui.system.cashierservice.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chaozhanggui.system.cashierservice.constant.TableConstant;
import com.chaozhanggui.system.cashierservice.entity.TbFreeDineRecord;
import com.chaozhanggui.system.cashierservice.service.TbFreeDineRecordService;
import com.chaozhanggui.system.cashierservice.mapper.TbFreeDineRecordMapper;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
/**
* @author Administrator
* @description 针对表【tb_free_dine_record(霸王餐充值记录)】的数据库操作Service实现
* @createDate 2024-10-30 09:48:31
*/
@Service
@Primary
public class TbFreeDineRecordServiceImpl extends ServiceImpl<TbFreeDineRecordMapper, TbFreeDineRecord>
implements TbFreeDineRecordService{
@Override
public TbFreeDineRecord selectByOrderId(Integer orderId) {
return getOne(new LambdaQueryWrapper<TbFreeDineRecord>()
.eq(TbFreeDineRecord::getOrderId, orderId));
}
@Override
public boolean updateStateByOrderId(TableConstant.FreeDineRecord.State state, Integer orderId) {
return update(new LambdaUpdateWrapper<TbFreeDineRecord>()
.eq(TbFreeDineRecord::getOrderId, orderId)
.set(TbFreeDineRecord::getState, state.getValue()));
}
}

View File

@@ -0,0 +1,63 @@
package com.chaozhanggui.system.cashierservice.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapProxy;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chaozhanggui.system.cashierservice.entity.TbMemberPointsLog;
import com.chaozhanggui.system.cashierservice.mapper.TbMemberPointsLogMapper;
import com.chaozhanggui.system.cashierservice.service.TbMemberPointsLogService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import java.util.Map;
/**
* 会员积分变动记录
*
* @author Tankaikai tankaikai@aliyun.com
* @since 2.0 2024-10-25
*/
@Service
@Primary
public class TbMemberPointsLogServiceImpl extends ServiceImpl<TbMemberPointsLogMapper, TbMemberPointsLog> implements TbMemberPointsLogService {
private LambdaQueryWrapper<TbMemberPointsLog> getWrapper(Map<String, Object> params) {
MapProxy mapProxy = MapProxy.create(params);
String beginDate = mapProxy.getStr("beginDate");
String endDate = mapProxy.getStr("endDate");
TbMemberPointsLog param = BeanUtil.toBean(params, TbMemberPointsLog.class);
LambdaQueryWrapper<TbMemberPointsLog> wrapper = Wrappers.lambdaQuery();
wrapper.eq(TbMemberPointsLog::getShopId, param.getShopId());
wrapper.eq(param.getMemberId() != null, TbMemberPointsLog::getMemberId, param.getMemberId());
wrapper.like(StrUtil.isNotEmpty(param.getMemberName()), TbMemberPointsLog::getMemberName, param.getMemberName());
wrapper.like(StrUtil.isNotEmpty(param.getMobile()), TbMemberPointsLog::getMobile, param.getMobile());
wrapper.like(StrUtil.isNotEmpty(param.getContent()), TbMemberPointsLog::getContent, param.getContent());
wrapper.eq(StrUtil.isNotEmpty(param.getFloatType()), TbMemberPointsLog::getFloatType, param.getFloatType());
wrapper.eq(StrUtil.isNotEmpty(param.getOrderNo()), TbMemberPointsLog::getOrderNo, param.getOrderNo());
if (StrUtil.isNotEmpty(beginDate)) {
wrapper.apply("create_time >= str_to_date({0}, '%Y-%m-%d %H:%i:%s')", beginDate + " 00:00:00");
}
if (StrUtil.isNotEmpty(endDate)) {
wrapper.apply("create_time <= str_to_date({0}, '%Y-%m-%d %H:%i:%s')", endDate + " 23:59:59");
}
wrapper.orderByDesc(TbMemberPointsLog::getId);
return wrapper;
}
@Override
public PageInfo<TbMemberPointsLog> page(Map<String, Object> params) {
MapProxy mapProxy = MapProxy.create(params);
int pageNum = mapProxy.getInt("page", 1);
int pageSize = mapProxy.getInt("size", 10);
LambdaQueryWrapper<TbMemberPointsLog> wrapper = getWrapper(params);
PageInfo<TbMemberPointsLog> page = PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(() -> baseMapper.selectList(wrapper));
//Page<TbMemberPointsLog> page = super.page(new Page<>(pageNum, pageSize), wrapper);
return page;
}
}

View File

@@ -0,0 +1,290 @@
package com.chaozhanggui.system.cashierservice.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapProxy;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chaozhanggui.system.cashierservice.dao.TbOrderInfoMapper;
import com.chaozhanggui.system.cashierservice.dao.TbShopUserMapper;
import com.chaozhanggui.system.cashierservice.entity.TbMemberPoints;
import com.chaozhanggui.system.cashierservice.entity.TbMemberPointsLog;
import com.chaozhanggui.system.cashierservice.entity.TbOrderInfo;
import com.chaozhanggui.system.cashierservice.entity.TbPointsBasicSetting;
import com.chaozhanggui.system.cashierservice.entity.dto.OrderDeductionPointsDTO;
import com.chaozhanggui.system.cashierservice.exception.MsgException;
import com.chaozhanggui.system.cashierservice.mapper.TbMemberPointsLogMapper;
import com.chaozhanggui.system.cashierservice.mapper.TbMemberPointsMapper;
import com.chaozhanggui.system.cashierservice.mapper.TbPointsBasicSettingMapper;
import com.chaozhanggui.system.cashierservice.service.TbMemberPointsService;
import com.chaozhanggui.system.cashierservice.service.TbPointsBasicSettingService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.Map;
/**
* 会员积分
*
* @author Tankaikai tankaikai@aliyun.com
* @since 2.0 2024-10-25
*/
@Service
@Primary
public class TbMemberPointsServiceImpl extends ServiceImpl<TbMemberPointsMapper, TbMemberPoints> implements TbMemberPointsService {
@Autowired
private TbMemberPointsLogMapper tbMemberPointsLogMapper;
@Autowired
private TbPointsBasicSettingMapper tbPointsBasicSettingMapper;
@Autowired
private TbShopUserMapper tbShopUserMapper;
@Autowired
private TbOrderInfoMapper tbOrderInfoMapper;
@Autowired
private TbPointsBasicSettingService tbPointsBasicSettingService;
private LambdaQueryWrapper<TbMemberPoints> getWrapper(Map<String, Object> params) {
//MapProxy mapProxy = MapProxy.create(params);
TbMemberPoints param = BeanUtil.toBean(params, TbMemberPoints.class);
LambdaQueryWrapper<TbMemberPoints> wrapper = Wrappers.lambdaQuery();
wrapper.eq(TbMemberPoints::getShopId, param.getShopId());
wrapper.like(StrUtil.isNotEmpty(param.getMemberName()), TbMemberPoints::getMemberName, param.getMemberName());
wrapper.like(StrUtil.isNotEmpty(param.getMobile()), TbMemberPoints::getMobile, param.getMobile());
wrapper.orderByDesc(TbMemberPoints::getId);
return wrapper;
}
@Override
public PageInfo<TbMemberPoints> page(Map<String, Object> params) {
MapProxy mapProxy = MapProxy.create(params);
int pageNum = mapProxy.getInt("page", 1);
int pageSize = mapProxy.getInt("size", 10);
LambdaQueryWrapper<TbMemberPoints> wrapper = getWrapper(params);
PageInfo<TbMemberPoints> page = PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(() -> baseMapper.selectList(wrapper));
//Page<TbMemberPoints> page = super.page(new Page<>(pageNum, pageSize), wrapper);
return page;
}
@Override
public TbMemberPoints getMemberPoints(Long memberId) {
return initMemberPoints(memberId);
}
@Override
public TbMemberPoints initMemberPoints(Long memberId) {
TbMemberPoints entity = super.getOne(Wrappers.<TbMemberPoints>lambdaQuery().eq(TbMemberPoints::getMemberId, memberId));
if (entity == null) {
throw new MsgException("会员信息不存在");
}
if(entity.getAccountPoints() == null){
entity.setAccountPoints(0);
}
super.updateById(entity);
return entity;
}
@Override
public OrderDeductionPointsDTO getMemberUsablePoints(Long memberId, BigDecimal orderAmount) {
TbMemberPoints entity = initMemberPoints(memberId);
Long shopId = entity.getShopId();
Integer accountPoints = entity.getAccountPoints();
OrderDeductionPointsDTO dto = new OrderDeductionPointsDTO();
dto.setAccountPoints(accountPoints);
dto.setUsable(false);
dto.setMaxDeductionAmount(BigDecimal.ZERO);
dto.setMinDeductionAmount(BigDecimal.ZERO);
TbPointsBasicSetting basic = tbPointsBasicSettingMapper.selectOne(Wrappers.<TbPointsBasicSetting>lambdaQuery().eq(TbPointsBasicSetting::getShopId, shopId));
if (basic == null) {
dto.setUnusableReason("商家未启用积分抵扣功能");
return dto;
}
if (basic.getEnableDeduction() == 0) {
dto.setUnusableReason("商家未启用积分抵扣功能");
return dto;
}
dto.setMinDeductionPoints(basic.getMinDeductionPoint());
if (accountPoints == 0 || accountPoints < basic.getMinDeductionPoint()) {
dto.setUnusableReason("积分不足或小于最低使用门槛" + basic.getMinDeductionPoint());
return dto;
}
// 下单抵扣积分比例 1元=?积分
Integer equivalentPoints = basic.getEquivalentPoints();
// 计算账户积分=?元
BigDecimal accountYuan = NumberUtil.div(accountPoints, equivalentPoints);
// 下单最高抵扣比例
BigDecimal maxDeductionRatio = basic.getMaxDeductionRatio();
// 计算订单最多可以抵扣多少元
BigDecimal orderYuan = NumberUtil.mul(orderAmount, NumberUtil.div(maxDeductionRatio, new BigDecimal("100")));
// 积分余额足够
if (NumberUtil.isGreaterOrEqual(accountYuan, orderYuan)) {
dto.setMaxDeductionAmount(orderYuan);
} else {
dto.setMaxDeductionAmount(NumberUtil.roundDown(accountYuan, 2));
}
if (NumberUtil.isLess(dto.getMaxDeductionAmount(), new BigDecimal("0.01"))) {
dto.setUnusableReason("积分不足0.01元,无法进行抵扣");
return dto;
}
// 计算抵扣门槛=?元
BigDecimal minYuan = NumberUtil.div(basic.getMinDeductionPoint(), equivalentPoints);
if (NumberUtil.isLess(minYuan, new BigDecimal("0.01"))) {
dto.setMinDeductionAmount(new BigDecimal("0.01"));
} else {
dto.setMinDeductionAmount(NumberUtil.roundDown(minYuan, 2));
}
dto.setEquivalentPoints(equivalentPoints);
dto.setOrderAmount(orderAmount);
dto.setUsable(true);
// 计算最多可抵扣的积分
BigDecimal mul = NumberUtil.mul(dto.getMaxDeductionAmount(), equivalentPoints);
BigDecimal round = NumberUtil.round(mul, 0, RoundingMode.CEILING);
dto.setMaxUsablePoints(round.intValue());
return dto;
}
@Override
public int calcUsedPoints(Long memberId, BigDecimal orderAmount, BigDecimal deductionAmount) {
OrderDeductionPointsDTO core = getMemberUsablePoints(memberId, orderAmount);
if (!core.getUsable()) {
throw new MsgException(core.getUnusableReason());
}
if (NumberUtil.isGreater(deductionAmount, core.getMaxDeductionAmount())) {
throw new MsgException(StrUtil.format("抵扣金额不能超过最大抵扣金额{}元", core.getMaxDeductionAmount()));
}
if (NumberUtil.isGreater(deductionAmount, orderAmount)) {
throw new MsgException(StrUtil.format("抵扣金额不能超过订单金额{}元", orderAmount));
}
// 计算可抵扣的积分
BigDecimal mul = NumberUtil.mul(deductionAmount, core.getEquivalentPoints());
BigDecimal round = NumberUtil.round(mul, 0, RoundingMode.CEILING);
return round.intValue();
}
@Override
public BigDecimal calcDeductionAmount(Long memberId, BigDecimal orderAmount, int points) {
OrderDeductionPointsDTO core = getMemberUsablePoints(memberId, orderAmount);
if (!core.getUsable()) {
throw new MsgException(core.getUnusableReason());
}
if (points < core.getMinDeductionPoints()) {
throw new MsgException(StrUtil.format("使用积分不能低于使用门槛(每次最少使用{}积分)", core.getMinDeductionPoints()));
}
if (points > core.getMaxUsablePoints()) {
throw new MsgException(StrUtil.format("使用积分不能超过最大使用限制{}", core.getMaxUsablePoints()));
}
BigDecimal mul = NumberUtil.mul(new BigDecimal("0.01"), core.getEquivalentPoints());
int minPoints = NumberUtil.round(mul, 0, RoundingMode.CEILING).intValue();
if (points < minPoints) {
throw new MsgException(StrUtil.format("使用积分不能低于{}(0.01元)", minPoints));
}
BigDecimal money = NumberUtil.mul(points, NumberUtil.div(BigDecimal.ONE, core.getEquivalentPoints()));
return NumberUtil.roundDown(money, 2);
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean deductPoints(Long memberId, int points, String content, Long orderId) {
TbMemberPoints entity = initMemberPoints(memberId);
// 扣除账户积分
entity.setAccountPoints(entity.getAccountPoints() - points);
entity.setLastPointsChangeTime(new Date());
entity.setLastFloatPoints(-points);
// 记录积分变动记录
TbMemberPointsLog log = new TbMemberPointsLog();
log.setShopId(entity.getShopId());
log.setMemberId(entity.getMemberId());
log.setMemberName(entity.getMemberName());
log.setAvatarUrl(entity.getAvatarUrl());
log.setMobile(entity.getMobile());
log.setContent(content);
log.setFloatType("subtract");
log.setFloatPoints(-points);
log.setCreateTime(new Date());
// 有关联订单的需要回置订单表的相关积分使用字段
if (orderId != null) {
TbOrderInfo orderInfo = tbOrderInfoMapper.selectByPrimaryKey(Convert.toInt(orderId));
if (orderInfo != null) {
log.setOrderNo(orderInfo.getOrderNo());
// TODO 是否需要回执“使用的积分数量(points_num)”和“积分抵扣金额(points_discount_amount)”,目前不清楚是创建订单的时候置入还是支付完成后回调时置入需要商议后决定
}
}
super.updateById(entity);
tbMemberPointsLogMapper.insert(log);
return true;
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean addPoints(Long memberId, int points, String content, Long orderId) {
TbMemberPoints entity = initMemberPoints(memberId);
// 增加账户积分
entity.setAccountPoints(entity.getAccountPoints() + points);
entity.setLastPointsChangeTime(new Date());
entity.setLastFloatPoints(points);
// 记录积分变动记录
TbMemberPointsLog log = new TbMemberPointsLog();
log.setShopId(entity.getShopId());
log.setMemberId(entity.getMemberId());
log.setMemberName(entity.getMemberName());
log.setAvatarUrl(entity.getAvatarUrl());
log.setMobile(entity.getMobile());
log.setContent(content);
log.setFloatType("add");
log.setFloatPoints(points);
log.setCreateTime(new Date());
// 有关联订单的需要回置订单表的相关积分使用字段
if (orderId != null) {
TbOrderInfo orderInfo = tbOrderInfoMapper.selectByPrimaryKey(Convert.toInt(orderId));
if (orderInfo != null) {
log.setOrderNo(orderInfo.getOrderNo());
}
}
super.updateById(entity);
tbMemberPointsLogMapper.insert(log);
return true;
}
@Override
@Transactional(rollbackFor = Exception.class)
public void consumeAwardPoints(Long memberId, Long orderId) {
TbOrderInfo orderInfo = tbOrderInfoMapper.selectByPrimaryKey(Convert.toInt(orderId));
if (orderInfo == null) {
throw new MsgException("订单不存在");
}
BigDecimal payAmount = orderInfo.getPayAmount();
if (NumberUtil.isLessOrEqual(payAmount, BigDecimal.ZERO)) {
return;
}
TbPointsBasicSetting basicSetting = tbPointsBasicSettingService.getByShopId(Convert.toLong(orderInfo.getShopId()));
if (basicSetting == null) {
return;
}
Integer enableRewards = basicSetting.getEnableRewards();
if (enableRewards == 0) {
return;
}
BigDecimal consumeAmount = basicSetting.getConsumeAmount();
if (consumeAmount == null) {
return;
}
if (NumberUtil.isLessOrEqual(consumeAmount, BigDecimal.ZERO)) {
return;
}
BigDecimal awardPoints = NumberUtil.roundDown(NumberUtil.div(payAmount, consumeAmount), 0);
addPoints(memberId, awardPoints.intValue(), StrUtil.format("消费¥{}送{}积分", payAmount, awardPoints.intValue()), orderId);
}
}

View File

@@ -0,0 +1,53 @@
package com.chaozhanggui.system.cashierservice.service.impl;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chaozhanggui.system.cashierservice.entity.TbPointsBasicSetting;
import com.chaozhanggui.system.cashierservice.exception.MsgException;
import com.chaozhanggui.system.cashierservice.mapper.TbPointsBasicSettingMapper;
import com.chaozhanggui.system.cashierservice.service.TbPointsBasicSettingService;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
/**
* 积分基本设置
*
* @author Tankaikai tankaikai@aliyun.com
* @since 2.0 2024-10-25
*/
@Service
@Primary
public class TbPointsBasicSettingServiceImpl extends ServiceImpl<TbPointsBasicSettingMapper, TbPointsBasicSetting> implements TbPointsBasicSettingService {
@Override
@Transactional(rollbackFor = Exception.class)
public boolean save(TbPointsBasicSetting entity) {
try {
Assert.notNull(entity.getShopId(), "{}({})不能为空", "店铺id","shopId");
Assert.notNull(entity.getEnableRewards(), "{}({})不能为空", "开启消费赠送积分","enableRewards");
Assert.notNull(entity.getConsumeAmount(), "{}({})不能为空", "每消费xx元赠送1积分","consumeAmount");
Assert.notNull(entity.getEnableDeduction(), "{}({})不能为空", "开启下单积分抵扣","enableDeduction");
Assert.notNull(entity.getMinDeductionPoint(), "{}({})不能为空", "下单积分抵扣门槛","minDeductionPoint");
Assert.notNull(entity.getMaxDeductionRatio(), "{}({})不能为空", "下单最高抵扣比例","maxDeductionRatio");
Assert.notNull(entity.getEquivalentPoints(), "{}({})不能为空", "下单抵扣积分比例","equivalentPoints");
Assert.notNull(entity.getEnablePointsMall(), "{}({})不能为空", "开启积分商城","enablePointsMall");
Assert.notEmpty(entity.getBrowseMode(), "{}({})不能为空", "浏览模式","browseMode");
} catch (IllegalArgumentException e) {
throw new MsgException(e.getMessage());
}
entity.setCreateTime(new Date());
super.remove(Wrappers.<TbPointsBasicSetting>lambdaQuery().eq(TbPointsBasicSetting::getShopId, entity.getShopId()));
super.save(entity);
return true;
}
@Override
public TbPointsBasicSetting getByShopId(Long shopId) {
return super.getOne(Wrappers.<TbPointsBasicSetting>lambdaQuery().eq(TbPointsBasicSetting::getShopId, shopId));
}
}

View File

@@ -0,0 +1,204 @@
package com.chaozhanggui.system.cashierservice.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.map.MapProxy;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chaozhanggui.system.cashierservice.entity.*;
import com.chaozhanggui.system.cashierservice.exception.MsgException;
import com.chaozhanggui.system.cashierservice.mapper.*;
import com.chaozhanggui.system.cashierservice.service.TbPointsExchangeRecordService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* 积分兑换记录
*
* @author Tankaikai tankaikai@aliyun.com
* @since 2.0 2024-10-25
*/
@Service
@Primary
public class TbPointsExchangeRecordServiceImpl extends ServiceImpl<TbPointsExchangeRecordMapper, TbPointsExchangeRecord> implements TbPointsExchangeRecordService {
@Autowired
private TbPointsBasicSettingMapper tbPointsBasicSettingMapper;
@Autowired
private TbPointsGoodsSettingMapper tbPointsGoodsSettingMapper;
@Autowired
private TbMemberPointsMapper tbMemberPointsMapper;
@Autowired
private TbMemberPointsLogMapper tbMemberPointsLogMapper;
private LambdaQueryWrapper<TbPointsExchangeRecord> getWrapper(Map<String, Object> params) {
MapProxy mapProxy = MapProxy.create(params);
String keywords = mapProxy.getStr("keywords");
String beginDate = mapProxy.getStr("beginDate");
String endDate = mapProxy.getStr("endDate");
TbPointsExchangeRecord param = BeanUtil.toBean(params, TbPointsExchangeRecord.class);
LambdaQueryWrapper<TbPointsExchangeRecord> wrapper = Wrappers.lambdaQuery();
wrapper.eq(TbPointsExchangeRecord::getShopId, param.getShopId());
wrapper.eq(StrUtil.isNotEmpty(param.getPickupMethod()), TbPointsExchangeRecord::getPickupMethod, param.getPickupMethod());
wrapper.eq(StrUtil.isNotEmpty(param.getStatus()), TbPointsExchangeRecord::getStatus, param.getStatus());
wrapper.eq(param.getMemberId() != null, TbPointsExchangeRecord::getMemberId, param.getMemberId());
if (StrUtil.isNotEmpty(keywords)) {
wrapper.nested(i -> i.like(TbPointsExchangeRecord::getOrderNo, keywords).or().like(TbPointsExchangeRecord::getCouponCode, keywords));
}
if (StrUtil.isNotEmpty(beginDate)) {
wrapper.apply("create_time >= str_to_date({0}, '%Y-%m-%d %H:%i:%s')", beginDate + " 00:00:00");
}
if (StrUtil.isNotEmpty(endDate)) {
wrapper.apply("create_time <= str_to_date({0}, '%Y-%m-%d %H:%i:%s')", endDate + " 23:59:59");
}
wrapper.orderByDesc(TbPointsExchangeRecord::getId);
return wrapper;
}
@Override
public PageInfo<TbPointsExchangeRecord> page(Map<String, Object> params) {
MapProxy mapProxy = MapProxy.create(params);
int pageNum = mapProxy.getInt("page", 1);
int pageSize = mapProxy.getInt("size", 10);
LambdaQueryWrapper<TbPointsExchangeRecord> wrapper = getWrapper(params);
PageInfo<TbPointsExchangeRecord> page = PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(() -> baseMapper.selectList(wrapper));
//Page<TbPointsExchangeRecord> page = super.page(new Page<>(pageNum, pageSize), wrapper);
return page;
}
@Override
public TbPointsExchangeRecord get(Long id) {
return super.getById(id);
}
@Override
public void checkout(String couponCode) {
if (StrUtil.isBlank(couponCode)) {
throw new MsgException("兑换券券码不能为空");
}
TbPointsExchangeRecord entity = super.getOne(Wrappers.<TbPointsExchangeRecord>lambdaQuery().eq(TbPointsExchangeRecord::getCouponCode, couponCode));
if (entity == null) {
throw new MsgException("兑换券券码无效");
}
entity.setStatus("done");
entity.setUpdateTime(new Date());
super.updateById(entity);
}
@Override
@Transactional(rollbackFor = Exception.class)
public TbPointsExchangeRecord exchange(TbPointsExchangeRecord record) {
try {
Assert.notNull(record.getShopId(), "{}({})不能为空", "店铺id", "shopId");
Assert.notNull(record.getPointsGoodsId(), "{}({})不能为空", "积分商品id", "pointsGoodsId");
Assert.notEmpty(record.getPickupMethod(), "{}({})不能为空", "领取方式", "pickupMethod");
Assert.notNull(record.getMemberId(), "{}({})不能为空", "会员id", "memberId");
Assert.notEmpty(record.getMemberName(), "{}({})不能为空", "会员名称", "memberName");
Assert.notEmpty(record.getMobile(), "{}({})不能为空", "手机号码", "mobile");
} catch (IllegalArgumentException e) {
throw new MsgException(e.getMessage());
}
TbPointsBasicSetting basic = tbPointsBasicSettingMapper.selectOne(Wrappers.<TbPointsBasicSetting>lambdaQuery().eq(TbPointsBasicSetting::getShopId, record.getShopId()));
if (basic == null) {
throw new MsgException("未配置积分锁客基本设置");
}
if (basic.getEnablePointsMall() != 1) {
throw new MsgException("积分商城未开启");
}
TbPointsGoodsSetting goods = tbPointsGoodsSettingMapper.selectById(record.getPointsGoodsId());
if (goods == null) {
throw new MsgException("兑换的商品信息不存在");
}
if (goods.getDelFlag() == 1) {
throw new MsgException("兑换的商品信息不存在");
}
record.setPointsGoodsName(goods.getGoodsName());
record.setGoodsImageUrl(goods.getGoodsImageUrl());
Integer status = goods.getStatus();
if (status != 1) {
throw new MsgException("兑换的商品已下架");
}
Integer quantity = goods.getQuantity();
if (quantity <= 0) {
throw new MsgException("兑换的商品库存不足");
}
TbMemberPoints memberPoints = tbMemberPointsMapper.selectOne(Wrappers.<TbMemberPoints>lambdaQuery().eq(TbMemberPoints::getMemberId, record.getMemberId()));
if (memberPoints == null) {
throw new MsgException("该会员积分不足无法兑换这个商品");
}
Integer accountPoints = memberPoints.getAccountPoints();
Integer requiredPoints = goods.getRequiredPoints();
if (accountPoints < requiredPoints) {
throw new MsgException("该会员积分不足无法兑换这个商品");
}
BigDecimal extraPrice = goods.getExtraPrice();
record.setExtraPaymentAmount(extraPrice);
record.setSpendPoints(requiredPoints);
Snowflake seqNo = IdUtil.getSnowflake(0, 0);
String orderNo = DateUtil.format(new Date(), "yyyyMMddHH") + StrUtil.subSuf(seqNo.nextIdStr(), -12);
record.setOrderNo(orderNo);
record.setCouponCode(IdUtil.getSnowflakeNextIdStr());
record.setStatus("waiting");
record.setCreateTime(new Date());
// 生成订单
super.save(record);
// 扣减积分
memberPoints.setAccountPoints(accountPoints - requiredPoints);
memberPoints.setLastPointsChangeTime(new Date());
memberPoints.setLastFloatPoints(-requiredPoints);
tbMemberPointsMapper.updateById(memberPoints);
// 扣减库存
goods.setQuantity(quantity - 1);
goods.setUpdateTime(new Date());
tbPointsGoodsSettingMapper.updateById(goods);
// 记录积分浮动流水
TbMemberPointsLog log = new TbMemberPointsLog();
log.setShopId(record.getShopId());
log.setMemberId(record.getMemberId());
log.setMemberName(record.getMemberName());
log.setMobile(record.getMobile());
log.setAvatarUrl(record.getAvatarUrl());
log.setContent(StrUtil.format("兑换商品:{} * {}", record.getPointsGoodsName(), "1"));
log.setFloatType("subtract");
log.setFloatPoints(-requiredPoints);
log.setCreateTime(new Date());
tbMemberPointsLogMapper.insert(log);
// 更新累计兑换数量
goods.setTotalExchangeCount(goods.getTotalExchangeCount() + 1);
goods.setUpdateTime(new Date());
tbPointsGoodsSettingMapper.updateById(goods);
return record;
}
@Override
public Map<String, Object> total(Map<String, Object> params) {
LambdaQueryWrapper<TbPointsExchangeRecord> wrapper = getWrapper(params);
wrapper.select(TbPointsExchangeRecord::getCount, TbPointsExchangeRecord::getTotalAmount);
TbPointsExchangeRecord summary = baseMapper.selectOne(wrapper);
Map<String, Object> result = new HashMap<>(2);
result.put("count", summary.getCount());
result.put("totalAmount", NumberUtil.null2Zero(summary.getTotalAmount()));
return result;
}
}

View File

@@ -0,0 +1,103 @@
package com.chaozhanggui.system.cashierservice.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapProxy;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chaozhanggui.system.cashierservice.entity.TbPointsGoodsSetting;
import com.chaozhanggui.system.cashierservice.exception.MsgException;
import com.chaozhanggui.system.cashierservice.mapper.TbPointsGoodsSettingMapper;
import com.chaozhanggui.system.cashierservice.service.TbPointsGoodsSettingService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.Map;
/**
* 积分商品设置
*
* @author Tankaikai tankaikai@aliyun.com
* @since 2.0 2024-10-25
*/
@Service
@Primary
public class TbPointsGoodsSettingServiceImpl extends ServiceImpl<TbPointsGoodsSettingMapper, TbPointsGoodsSetting> implements TbPointsGoodsSettingService {
@Override
public PageInfo<TbPointsGoodsSetting> page(Map<String, Object> params) {
MapProxy mapProxy = MapProxy.create(params);
int pageNum = mapProxy.getInt("page", 1);
int pageSize = mapProxy.getInt("size", 10);
TbPointsGoodsSetting param = BeanUtil.toBean(params, TbPointsGoodsSetting.class);
Page<TbPointsGoodsSetting> pg = new Page<>(pageNum, pageSize);
pg.addOrder(OrderItem.desc("sort"));
LambdaQueryWrapper<TbPointsGoodsSetting> wrapper = Wrappers.<TbPointsGoodsSetting>lambdaQuery()
.eq(TbPointsGoodsSetting::getShopId, param.getShopId())
.like(StrUtil.isNotEmpty(param.getGoodsName()), TbPointsGoodsSetting::getGoodsName, param.getGoodsName())
.like(StrUtil.isNotEmpty(param.getGoodsCategory()), TbPointsGoodsSetting::getGoodsCategory, param.getGoodsCategory())
.eq(param.getStatus() != null, TbPointsGoodsSetting::getStatus, param.getStatus())
.eq(TbPointsGoodsSetting::getDelFlag, 0)
.orderByDesc(TbPointsGoodsSetting::getId);
PageInfo<TbPointsGoodsSetting> page = PageHelper.startPage(pageNum, pageSize,"sort desc").doSelectPageInfo(() -> baseMapper.selectList(wrapper));
return page;
}
@Override
public boolean save(TbPointsGoodsSetting entity) {
try {
Assert.notNull(entity.getShopId(), "{}({})不能为空", "店铺id", "shopId");
Assert.notEmpty(entity.getGoodsCategory(), "{}({})不能为空", "商品类型", "goodsCategory");
Assert.notEmpty(entity.getGoodsName(), "{}({})不能为空", "商品名称", "goodsName");
//Assert.notNull(entity.getGoodsImageUrl(), "{}({})不能为空", "商品图片URL","goodsImageUrl");
Assert.notNull(entity.getRequiredPoints(), "{}({})不能为空", "所需积分", "requiredPoints");
Assert.notNull(entity.getExtraPrice(), "{}({})不能为空", "额外价格", "extraPrice");
Assert.notNull(entity.getSort(), "{}({})不能为空", "排序(权重)", "sort");
Assert.notNull(entity.getQuantity(), "{}({})不能为空", "数量", "quantity");
//Assert.notEmpty(entity.getGoodsDescription(), "{}({})不能为空", "商品详情","goodsDescription");
Assert.notNull(entity.getStatus(), "{}({})不能为空", "是否上架", "status");
} catch (IllegalArgumentException e) {
throw new MsgException(e.getMessage());
}
entity.setCreateTime(new Date());
return super.save(entity);
}
@Override
public boolean update(TbPointsGoodsSetting dto) {
try {
Assert.notNull(dto.getId(), "{}不能为空", "商品id");
Assert.notNull(dto.getShopId(), "{}({})不能为空", "店铺id", "shopId");
Assert.notEmpty(dto.getGoodsCategory(), "{}({})不能为空", "商品类型", "goodsCategory");
Assert.notEmpty(dto.getGoodsName(), "{}({})不能为空", "商品名称", "goodsName");
//Assert.notNull(entity.getGoodsImageUrl(), "{}({})不能为空", "商品图片URL","goodsImageUrl");
Assert.notNull(dto.getRequiredPoints(), "{}({})不能为空", "所需积分", "requiredPoints");
Assert.notNull(dto.getExtraPrice(), "{}({})不能为空", "额外价格", "extraPrice");
Assert.notNull(dto.getSort(), "{}({})不能为空", "排序(权重)", "sort");
Assert.notNull(dto.getQuantity(), "{}({})不能为空", "数量", "quantity");
//Assert.notEmpty(entity.getGoodsDescription(), "{}({})不能为空", "商品详情","goodsDescription");
Assert.notNull(dto.getStatus(), "{}({})不能为空", "是否上架", "status");
} catch (IllegalArgumentException e) {
throw new MsgException(e.getMessage());
}
TbPointsGoodsSetting entity = super.getById(dto.getId());
BeanUtil.copyProperties(dto, entity, CopyOptions.create().setIgnoreNullValue(false).setIgnoreProperties("createTime"));
entity.setUpdateTime(new Date());
return super.updateById(entity);
}
@Override
public void delete(Long id) {
super.update(Wrappers.<TbPointsGoodsSetting>lambdaUpdate().set(TbPointsGoodsSetting::getDelFlag, 1).eq(TbPointsGoodsSetting::getId, id));
}
}

View File

@@ -0,0 +1,209 @@
package com.chaozhanggui.system.cashierservice.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.chaozhanggui.system.cashierservice.dao.*;
import com.chaozhanggui.system.cashierservice.entity.*;
import com.chaozhanggui.system.cashierservice.entity.dto.CouponDto;
import com.chaozhanggui.system.cashierservice.entity.vo.TbUserCouponVo;
import com.chaozhanggui.system.cashierservice.service.TbShopCouponService;
import com.chaozhanggui.system.cashierservice.sign.CodeEnum;
import com.chaozhanggui.system.cashierservice.sign.Result;
import com.google.gson.JsonObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
/**
* 优惠券(TbShopCoupon)表服务实现类
*
* @author ww
* @since 2024-10-23 15:37:37
*/
@Primary
@Service
public class TbShopCouponServiceImpl implements TbShopCouponService {
@Resource
private TbOrderDetailMapper orderDetailMapper;
@Resource
private TbShopUserMapper shopUserMapper;
@Resource
private TbShopCouponMapper couponMapper;
@Resource
private TbOrderInfoMapper orderInfoMapper;
@Resource
private TbActivateInRecordMapper inRecordMapper;
@Resource
private TbActivateOutRecordMapper outRecordMapper;
@Override
public List<TbUserCouponVo> getActivateCouponByAmount(Integer shopId, String userId, BigDecimal amount) {
TbShopUser tbShopUser = shopUserMapper.selectByUserIdAndShopId(userId, String.valueOf(shopId));
List<TbUserCouponVo> tbUserCouponVos = inRecordMapper.queryByVipIdAndShopId(Arrays.asList(Integer.valueOf(tbShopUser.getId())), shopId);
ArrayList<TbUserCouponVo> canUseCoupon = new ArrayList<>();
if (CollectionUtil.isNotEmpty(tbUserCouponVos)) {
String week = DateUtil.dayOfWeekEnum(new Date()).toChinese("");
LocalTime now = LocalTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
//券id 券使用描述
Map<Integer, JsonObject> coupons = new HashMap<>();
for (TbUserCouponVo tbUserCouponVo : tbUserCouponVos) {
if (tbUserCouponVo.getType() != null && tbUserCouponVo.getType() == 1 &&
tbUserCouponVo.getFullAmount().compareTo(amount) <= 0) {
if (!coupons.containsKey(tbUserCouponVo.getCouponId())) {
setCouponInfo(coupons, tbUserCouponVo, amount, week, now, formatter);
}
JsonObject couponJson = coupons.get(tbUserCouponVo.getCouponId());
tbUserCouponVo.setUseRestrictions(couponJson.get("useRestrictions").toString());
if (tbUserCouponVo.getType().equals(1)) {
tbUserCouponVo.setUse(couponJson.get("isUse").getAsBoolean());
}
canUseCoupon.add(tbUserCouponVo);
}
}
canUseCoupon.sort(Comparator.comparing(TbUserCouponVo::isUse).reversed().thenComparing(TbUserCouponVo::getExpireTime));
}
return canUseCoupon;
}
private void setCouponInfo( Map<Integer, JsonObject> coupons, TbUserCouponVo tbUserCouponVo, BigDecimal amount, String week, LocalTime now, DateTimeFormatter formatter) {
JsonObject json = new JsonObject();
boolean isUse = true;
TbShopCoupon tbShopCoupon = couponMapper.queryById(tbUserCouponVo.getCouponId());
StringBuilder useRestrictions = new StringBuilder("每天 ");
if (tbShopCoupon.getType().equals(1)) {
if (amount.compareTo(new BigDecimal(tbShopCoupon.getFullAmount())) < 0) {
isUse = false;
}
}
if (StringUtils.isNotBlank(tbShopCoupon.getUserDays())) {
String[] split = tbShopCoupon.getUserDays().split(",");
if (split.length != 7) {
useRestrictions = new StringBuilder(tbShopCoupon.getUserDays() + " ");
}
if (!tbShopCoupon.getUserDays().contains(week)) {
isUse = false;
}
}
if (tbShopCoupon.getUseTimeType().equals("custom")) {
if (now.isBefore(tbShopCoupon.getUseStartTime()) || now.isAfter(tbShopCoupon.getUseEndTime())) {
isUse = false;
}
useRestrictions.append(
tbShopCoupon.getUseStartTime().format(formatter)
+ "-"
+ tbShopCoupon.getUseEndTime().format(formatter));
} else {
useRestrictions.append("全时段");
}
useRestrictions.append(" 可用");
json.addProperty("isUse", isUse);
json.addProperty("useRestrictions", useRestrictions.toString());
coupons.put(tbUserCouponVo.getCouponId(), json);
}
@Override
public Result find(CouponDto param) {
if (param.getOrderId() != null) {
TbShopUser tbShopUser = shopUserMapper.selectByUserIdAndShopId(param.getUserId().toString(), param.getShopId().toString());
TbOrderInfo tbOrderInfo = orderInfoMapper.selectByPrimaryKey(param.getOrderId());
List<TbOrderDetail> tbOrderDetails = orderDetailMapper.selectAllByOrderId(param.getOrderId());
Set<Integer> pros = tbOrderDetails.stream().map(TbOrderDetail::getProductId).collect(Collectors.toSet());
if (CollectionUtil.isNotEmpty(tbOrderDetails)) {
List<TbUserCouponVo> tbUserCouponVos = inRecordMapper.queryByVipIdAndShopId(Arrays.asList(Integer.valueOf(tbShopUser.getId())), param.getShopId());
if (CollectionUtil.isNotEmpty(tbUserCouponVos)) {
String week = DateUtil.dayOfWeekEnum(new Date()).toChinese("");
LocalTime now = LocalTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
//券id 券使用描述
Map<Integer, JsonObject> coupons = new HashMap<>();
for (TbUserCouponVo tbUserCouponVo : tbUserCouponVos) {
if (!coupons.containsKey(tbUserCouponVo.getCouponId())) {
setCouponInfo(coupons, tbUserCouponVo, tbOrderInfo.getAmount(), week, now, formatter);
}
JsonObject couponJson = coupons.get(tbUserCouponVo.getCouponId());
tbUserCouponVo.setUseRestrictions(couponJson.get("useRestrictions").toString());
if (tbUserCouponVo.getType().equals(1)) {
tbUserCouponVo.setUse(couponJson.get("isUse").getAsBoolean());
} else if (tbUserCouponVo.getType().equals(2) && couponJson.get("isUse").getAsBoolean()) {
if (!pros.contains(tbUserCouponVo.getProId())) {
tbUserCouponVo.setUse(false);
}
}
}
tbUserCouponVos.sort(Comparator.comparing(TbUserCouponVo::isUse).reversed().thenComparing(TbUserCouponVo::getExpireTime));
return new Result(CodeEnum.SUCCESS, tbUserCouponVos);
}
}
} else {
List<TbShopUser> tbShopUser = shopUserMapper.selectAllByUserId(param.getUserId().toString());
List<Integer> ids = tbShopUser.stream().map(TbShopUser::getId).map(Integer::valueOf).collect(Collectors.toList());
if (param.getStatus().equals(1)) {
return new Result(CodeEnum.SUCCESS, inRecordMapper.queryByVipIdAndShopId(ids, param.getShopId()));
} else if (param.getStatus().equals(-1)) {
return new Result(CodeEnum.SUCCESS, inRecordMapper.queryByVipIdAndShopIdExpire(ids, param.getShopId()));
} else if (param.getStatus().equals(2)) {
return new Result(CodeEnum.SUCCESS, outRecordMapper.queryByVipIdAndShopId(ids, param.getShopId()));
}
}
return new Result(CodeEnum.SUCCESS);
}
/**
* 使用券
*
* @param shopId
* @param orderId
* @param vipUserId
* @param param giveId 和 useNum 必传
* @return
*/
@Override
public boolean use(Integer shopId, Integer orderId, Integer vipUserId, List<TbActivateOutRecord> param) {
for (TbActivateOutRecord outRecord : param) {
TbActivateInRecord inRecord = inRecordMapper.queryById(outRecord.getGiveId());
inRecord.setOverNum(inRecord.getOverNum() - outRecord.getUseNum());
inRecordMapper.updateOverNum(inRecord.getId(), inRecord.getOverNum());
outRecord.setType(inRecord.getType());
outRecord.setShopId(shopId);
outRecord.setOrderId(orderId.toString());
outRecord.setVipUserId(vipUserId);
outRecord.setStatus("closed");
outRecord.setCreateTime(new Date());
}
outRecordMapper.insertBatch(param);
return true;
}
/**
* 退还券
*
* @param param giveId和 refNum 必传
* @return
*/
@Override
public boolean refund(List<TbActivateOutRecord> param) {
for (TbActivateOutRecord outRecord : param) {
outRecord.setUpdateTime(new Date());
outRecordMapper.updateRefNum(outRecord.getId(), outRecord.getRefNum());
TbActivateInRecord inRecord = inRecordMapper.queryById(outRecord.getGiveId());
inRecord.setOverNum(inRecord.getOverNum() + outRecord.getRefNum());
inRecordMapper.updateOverNum(inRecord.getId(), inRecord.getOverNum());
}
return true;
}
}