统计数据归档查询、商品数据分类缓存、已知问题修复

This commit is contained in:
Tankaikai
2025-04-16 15:24:32 +08:00
parent ff8a1e5de2
commit 954f2329bc
29 changed files with 611 additions and 273 deletions

View File

@@ -1,5 +1,7 @@
package com.czg.controller;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.alibaba.fastjson2.JSONObject;
import com.czg.CzgPayUtils;
import com.czg.entity.CzgBaseRespParams;
@@ -9,10 +11,9 @@ import com.czg.task.StatisticTask;
import com.czg.utils.AssertUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
/**
* @author ww
@@ -32,7 +33,7 @@ public class NotifyController {
@RequestMapping("/payCallBack")
public String notifyCallBack(@RequestBody CzgBaseRespParams respParams){
public String notifyCallBack(@RequestBody CzgBaseRespParams respParams) {
JSONObject czg = CzgPayUtils.getCzg(respParams);
AssertUtil.isNull(czg, "支付回调数据为空");
log.info("支付回调数据为:{}", czg);
@@ -41,7 +42,7 @@ public class NotifyController {
}
@RequestMapping("/refundCallBack")
public String refundCallBack(@RequestBody CzgBaseRespParams respParams){
public String refundCallBack(@RequestBody CzgBaseRespParams respParams) {
JSONObject czg = CzgPayUtils.getCzg(respParams);
AssertUtil.isNull(czg, "退款回调数据为空");
log.info("退款回调数据为:{}", czg);
@@ -51,8 +52,18 @@ public class NotifyController {
@Resource
private PrintMqListener printMqListener;
@RequestMapping("/test")
public void test(@RequestParam String id) {
printMqListener.orderPrint(id);
}
@GetMapping("/anew/statistic/history/data")
public String statistic(@RequestParam String now) {
String format = DateUtil.format(new Date(), "yyyyMMddHHmm");
if (format.equals(now)) {
ThreadUtil.execAsync(() -> statisticTask.statisticHistoryData());
}
return SUCCESS;
}
}

View File

@@ -47,7 +47,7 @@ public class DataSummaryController {
if (param.getShopId() == null) {
param.setShopId(shopId);
}
ShopOrderStatistic data = dataSummaryService.getTradeData(param);
ShopOrderStatistic data = dataSummaryService.getArchiveTradeData(param);
return CzgResult.success(data);
}

View File

@@ -1,13 +1,27 @@
package com.czg.task;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.czg.order.entity.ShopOrderStatistic;
import com.czg.order.entity.ShopProdStatistic;
import com.czg.order.entity.ShopTableOrderStatistic;
import com.czg.order.service.ShopOrderStatisticService;
import com.czg.order.service.ShopProdStatisticService;
import com.czg.order.service.ShopTableOrderStatisticService;
import com.czg.service.order.mapper.ShopOrderStatisticMapper;
import com.czg.service.order.mapper.ShopProdStatisticMapper;
import com.czg.service.order.mapper.ShopTableOrderStatisticMapper;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.DbChain;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDate;
import java.util.List;
/**
* @author Administrator
*/
@@ -20,15 +34,81 @@ public class StatisticTask {
private ShopProdStatisticService shopProdStatisticService;
@Resource
private ShopOrderStatisticService shopOrderStatisticService;
@Resource
private ShopOrderStatisticMapper shopOrderStatisticMapper;
@Resource
private ShopProdStatisticMapper shopProdStatisticMapper;
@Resource
private ShopTableOrderStatisticMapper shopTableOrderStatisticMapper;
// @Scheduled(cron = "1/6 * * * * ? ")
/**
* 基础统计
*
* @param dateTime 日期时间
*/
private void baseStatistic(DateTime dateTime) {
try {
shopOrderStatisticService.statistic(dateTime);
} catch (Exception e) {
log.error("统计订单数据失败", e);
}
try {
shopProdStatisticService.statistic(dateTime);
} catch (Exception e) {
log.error("统计商品数据失败", e);
}
try {
shopTableOrderStatisticService.statistic(dateTime);
} catch (Exception e) {
log.error("统计桌台数据失败", e);
}
}
// @Scheduled(cron = "1/6 * * * * ? ")
@Scheduled(cron = "0 0 8 * * ?")
public void run() {
long start = System.currentTimeMillis();
log.info("定时任务执行,开始统计数据");
shopOrderStatisticService.statistic();
shopProdStatisticService.statistic();
shopTableOrderStatisticService.statistic();
// 获取前一天
DateTime yesterday = DateUtil.yesterday();
baseStatistic(yesterday);
log.info("定时任务执行完毕,耗时:{}ms", start - System.currentTimeMillis());
}
@Scheduled(cron = "0 0,15,30,45 * * * ? ")
public void run2() {
long start = System.currentTimeMillis();
log.info("定时任务2执行开始统计数据");
// 获取当天
DateTime today = DateUtil.date();
baseStatistic(today);
log.info("定时任务2执行完毕耗时:{}ms", start - System.currentTimeMillis());
}
/**
* 统计历史数据
*/
public void statisticHistoryData() {
// 指定开始日期
LocalDate startDate = LocalDate.of(2024, 3, 1);
// 指定结束日期
LocalDate endDate = LocalDate.now();
List<Long> shopIdList = DbChain.table("tb_shop_info").select("id").objListAs(Long.class);
List<List<Long>> split = CollUtil.split(shopIdList, 10);
// 1.清除历史统计的数据
for (List<Long> splitIdList : split) {
splitIdList.parallelStream().forEach(shopId -> {
shopOrderStatisticMapper.deleteByQuery(QueryWrapper.create().eq(ShopOrderStatistic::getShopId, shopId));
shopProdStatisticMapper.deleteByQuery(QueryWrapper.create().eq(ShopProdStatistic::getShopId, shopId));
shopTableOrderStatisticMapper.deleteByQuery(QueryWrapper.create().eq(ShopTableOrderStatistic::getShopId, shopId));
});
}
// 2.开始从2024-3-1开始统计数据
startDate.datesUntil(endDate.plusDays(1)).forEach(date -> {
System.out.println(date.toString());
DateTime dateTime = DateUtil.parseDate(date.toString());
System.out.println(dateTime);
baseStatistic(dateTime);
});
}
}

View File

@@ -2,8 +2,6 @@ package com.czg.controller.admin;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.czg.account.service.ShopConfigService;
import com.czg.annotation.SaStaffCheckPermission;
import com.czg.config.RabbitPublisher;
@@ -72,22 +70,9 @@ public class ProductController {
public CzgResult<List<ProductDTO>> getProductList(ProductDTO param) {
Long shopId = StpKit.USER.getShopId(0L);
param.setShopId(shopId);
ProductDTO cacheParam = new ProductDTO();
cacheParam.setShopId(shopId);
List<ProductDTO> data = getProductCacheList(cacheParam, param);
productService.refreshProductStock(param, data);
return CzgResult.success(data);
}
private List<ProductDTO> getProductCacheList(ProductDTO cacheParam, ProductDTO param) {
List<ProductDTO> productList = productService.getProductList(cacheParam);
if (StrUtil.isNotEmpty(param.getName())) {
productList = productList.stream().filter(obj -> StrUtil.contains(obj.getName(), param.getName())).toList();
}
if (ObjUtil.isNotNull(param.getCategoryId())) {
productList = productList.stream().filter(obj -> param.getCategoryId().equals(obj.getCategoryId())).toList();
}
return productList;
List<ProductDTO> productList = productService.getProductCacheList(param);
productService.refreshProductStock(param, productList);
return CzgResult.success(productList);
}
/**
@@ -160,6 +145,9 @@ public class ProductController {
Long shopId = StpKit.USER.getShopId(0L);
param.setShopId(shopId);
productService.updateProductStock(param);
ThreadUtil.execAsync(() -> {
rabbitPublisher.sendProductInfoChangeMsg(Convert.toStr(shopId));
});
return CzgResult.success();
}

View File

@@ -1,6 +1,5 @@
package com.czg.controller.user;
import com.czg.product.dto.ProdGroupDTO;
import com.czg.product.param.ShopProductSkuParam;
import com.czg.product.service.ProdGroupService;
import com.czg.product.service.UProductService;
@@ -21,7 +20,6 @@ import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
@@ -57,19 +55,13 @@ public class UProductController {
@GetMapping("/miniApp/group/query")
public CzgResult<List<ShopGroupProductVo>> queryGroupProductList() {
Long shopId = StpKit.USER.getShopId(0L);
ProdGroupDTO param = new ProdGroupDTO();
List<ProdGroupDTO> prodGroupList = prodGroupService.getProdGroupList(param);
Map<Long, ProdGroupDTO> groupMap = prodGroupList.stream().collect(Collectors.toMap(ProdGroupDTO::getId, i -> i));
List<ShopGroupProductVo> list = uProductService.queryGroupProductList(shopId);
Map<Long, Integer> productStock = uProductService.findShopProductStock(shopId);
list.forEach(item -> {
uProductService.refreshProductStock(productStock, item.getProductList());
ProdGroupDTO config = groupMap.get(item.getId());
item.getProductList().forEach(prod -> {
prod.setIsSaleTime(uProductService.calcIsSaleTime(prod.getDays(), prod.getStartTime(), prod.getEndTime()));
if (config != null) {
prod.setIsSaleTime(uProductService.calcIsSaleTime(config.getUseTime(), config.getSaleStartTime(), config.getSaleEndTime()));
}
prod.setIsSaleTime(uProductService.calcIsSaleTime(item.getUseTime(), item.getSaleStartTime(), item.getSaleEndTime()));
});
});
return CzgResult.success(list);

View File

@@ -1,5 +1,7 @@
package com.czg.service;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -598,4 +600,54 @@ public class RedisService {
return redisTemplate.opsForList().rightPop(key);
}
/**
* 右模糊查找key
*
* @param key 模糊匹配的key前缀
* @return 匹配的keys
*/
public Set<String> rightLikeKey(String key) {
return redisTemplate.keys(key + "*");
}
/**
* JsonString缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean setJsonStr(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, JSON.toJSONString(value, JSONWriter.Feature.WriteMapNullValue));
return true;
} catch (Exception e) {
log.error("redis error:{}", e + "");
return false;
}
}
/**
* JsonString缓存获取
*
* @param key 键
* @return 值
*/
public String getJsonStr(String key) {
return key == null ? null : (String) redisTemplate.opsForValue().get(key);
}
/**
* JsonString缓存获取
*
* @param key 键
* @return 值
*/
public <T> List<T> getJsonToBeanList(String key, Class<T> type) {
String jsonStr = getJsonStr(key);
if (jsonStr == null) {
return null;
}
return JSON.parseArray(jsonStr, type);
}
}

View File

@@ -1,7 +1,6 @@
package com.czg.order.entity;
import com.alibaba.fastjson2.annotation.JSONField;
import com.mybatisflex.annotation.Column;
import com.mybatisflex.annotation.Id;
import com.mybatisflex.annotation.KeyType;
import com.mybatisflex.annotation.Table;
@@ -141,7 +140,6 @@ public class ShopOrderStatistic implements Serializable {
/**
* 新增会员数
*/
@Column(ignore = true)
private Long newMemberCount = 0L;
/**
* 店铺id

View File

@@ -3,16 +3,15 @@ package com.czg.order.entity;
import com.mybatisflex.annotation.Id;
import com.mybatisflex.annotation.KeyType;
import com.mybatisflex.annotation.Table;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Date;
import java.io.Serial;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serial;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/**
* 实体类。
*

View File

@@ -3,16 +3,15 @@ package com.czg.order.entity;
import com.mybatisflex.annotation.Id;
import com.mybatisflex.annotation.KeyType;
import com.mybatisflex.annotation.Table;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Date;
import java.io.Serial;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serial;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/**
* 台桌订单统计表 实体类。
*
@@ -32,8 +31,22 @@ public class ShopTableOrderStatistic implements Serializable {
@Id(keyType = KeyType.Auto)
private Long id;
/**
* 台桌id
*/
private Long tableId;
/**
* 台桌id
*/
private String tableCode;
/**
* 台桌名称
*/
private String tableName;
/**
* 区域名称
*/
private String areaName;
/**
* 订单数量
*/
@@ -56,7 +69,7 @@ public class ShopTableOrderStatistic implements Serializable {
/**
* 退款数量
*/
private long refundCount;
private Long refundCount;
/**
* 退款金额
*/

View File

@@ -18,7 +18,9 @@ import java.util.List;
*/
public interface DataSummaryService {
ShopOrderStatistic getTradeData(DataSummaryTradeParam param);
ShopOrderStatistic getArchiveTradeData(DataSummaryTradeParam param);
ShopOrderStatistic getRealTimeTradeData(DataSummaryTradeParam param);
Page<DataSummaryProductSaleRankingVo> getProductSaleRankingPage(DataSummaryProductSaleParam param);

View File

@@ -1,7 +1,8 @@
package com.czg.order.service;
import com.mybatisflex.core.service.IService;
import cn.hutool.core.date.DateTime;
import com.czg.order.entity.ShopOrderStatistic;
import com.mybatisflex.core.service.IService;
/**
* 服务层。
@@ -11,6 +12,6 @@ import com.czg.order.entity.ShopOrderStatistic;
*/
public interface ShopOrderStatisticService extends IService<ShopOrderStatistic> {
void statistic();
void statistic(DateTime dateTime);
}

View File

@@ -1,7 +1,8 @@
package com.czg.order.service;
import com.mybatisflex.core.service.IService;
import cn.hutool.core.date.DateTime;
import com.czg.order.entity.ShopProdStatistic;
import com.mybatisflex.core.service.IService;
/**
* 服务层。
@@ -11,6 +12,6 @@ import com.czg.order.entity.ShopProdStatistic;
*/
public interface ShopProdStatisticService extends IService<ShopProdStatistic> {
void statistic();
void statistic(DateTime dateTime);
}

View File

@@ -1,8 +1,9 @@
package com.czg.order.service;
import cn.hutool.core.date.DateTime;
import com.czg.order.entity.ShopTableOrderStatistic;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.service.IService;
import com.czg.order.entity.ShopTableOrderStatistic;
import java.math.BigDecimal;
@@ -25,5 +26,5 @@ public interface ShopTableOrderStatisticService extends IService<ShopTableOrderS
*/
boolean addInfo(long shopId, long tableId, long count, BigDecimal amount);
void statistic();
void statistic(DateTime dateTime);
}

View File

@@ -5,7 +5,6 @@ import lombok.NoArgsConstructor;
import java.io.Serial;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
@@ -26,27 +25,4 @@ public class DataSummaryDateAmountVo implements Serializable {
*/
private List<TotalVo> total = new ArrayList<>();
/**
* TotalVo
*/
@NoArgsConstructor
@Data
public static class TotalVo {
/**
* 实收金额
*/
private BigDecimal actualAmount = BigDecimal.ZERO;
/**
* 优惠金额
*/
private BigDecimal discountAmount = BigDecimal.ZERO;
/**
* 订单金额
*/
private BigDecimal orderAmount = BigDecimal.ZERO;
/**
* 日期
*/
private String tradeDay;
}
}

View File

@@ -19,6 +19,11 @@ public class DataSummaryProductSaleRankingVo implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
/**
* 商品名称
*/
private Long productId;
/**
* 商品名称
*/
@@ -34,4 +39,14 @@ public class DataSummaryProductSaleRankingVo implements Serializable {
*/
private BigDecimal amount;
/**
* 退单量
*/
private BigDecimal refundCount;
/**
* 退单金额
*/
private BigDecimal refundAmount;
}

View File

@@ -32,6 +32,11 @@ public class TableSummaryInfoVo implements Serializable {
@ExcelIgnore
@JSONField(serialize = false)
private Long lineNum;
/**
* 台桌id
*/
@ExcelIgnore
private Long tableId;
/**
* 台桌码
*/

View File

@@ -0,0 +1,38 @@
package com.czg.order.vo;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serial;
import java.io.Serializable;
import java.math.BigDecimal;
/**
* 销售趋势柱状图 左下
* @author tankaikai
* @since 2025-03-07 16:08
*/
@NoArgsConstructor
@Data
public class TotalVo implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
/**
* 实收金额
*/
private BigDecimal actualAmount = BigDecimal.ZERO;
/**
* 优惠金额
*/
private BigDecimal discountAmount = BigDecimal.ZERO;
/**
* 订单金额
*/
private BigDecimal orderAmount = BigDecimal.ZERO;
/**
* 日期
*/
private String tradeDay;
}

View File

@@ -34,6 +34,19 @@ public interface ProductService extends IService<Product> {
*/
List<ProductDTO> getProductList(ProductDTO param);
/**
* 从缓存里面获取商品列表
*
* @param param 查询参数
* @return 商品列表数据
*/
List<ProductDTO> getProductCacheList(ProductDTO param);
/**
* 清除某个商品分类的缓存
*/
void clearProductCache(Long... categoryIds);
/**
* 获取商品详情
*

View File

@@ -73,9 +73,14 @@ public class PageUtil {
*/
public QueryWrapper buildSortQueryWrapper() {
QueryWrapper queryWrapper = QueryWrapper.create();
String orderBy = ServletUtil.getRequest().getParameter(ORDER_BY);
if (StrUtil.isNotEmpty(orderBy)) {
queryWrapper.orderBy(SqlUtil.escapeOrderBySql(orderBy));
try {
HttpServletRequest request = ServletUtil.getRequest();
String orderBy = request.getParameter(ORDER_BY);
if (StrUtil.isNotEmpty(orderBy)) {
queryWrapper.orderBy(SqlUtil.escapeOrderBySql(orderBy));
}
} catch (Exception e) {
//System.out.println("排序参数异常");
}
return queryWrapper;
}

View File

@@ -14,6 +14,7 @@ import com.czg.order.service.DataSummaryService;
import com.czg.order.vo.DataSummaryDateAmountVo;
import com.czg.order.vo.DataSummaryPayTypeVo;
import com.czg.order.vo.DataSummaryProductSaleRankingVo;
import com.czg.order.vo.TotalVo;
import com.czg.service.order.mapper.OrderInfoMapper;
import com.czg.service.order.mapper.ShopOrderStatisticMapper;
import com.czg.service.order.mapper.ShopProdStatisticMapper;
@@ -50,7 +51,15 @@ public class DataSummaryServiceImpl implements DataSummaryService {
private ShopProdStatisticMapper shopProdStatisticMapper;
@Override
public ShopOrderStatistic getTradeData(DataSummaryTradeParam param) {
public ShopOrderStatistic getArchiveTradeData(DataSummaryTradeParam param) {
ShopOrderStatistic shopOrderStatistic = shopOrderStatisticMapper.getTradeData(param);
shopOrderStatistic.setCustomerUnitPrice(shopOrderStatistic.getCustomerUnitPrice().setScale(2, java.math.RoundingMode.HALF_UP));
shopOrderStatistic.setTableTurnoverRate(shopOrderStatistic.getTableTurnoverRate().setScale(2, java.math.RoundingMode.HALF_UP));
return shopOrderStatistic;
}
@Override
public ShopOrderStatistic getRealTimeTradeData(DataSummaryTradeParam param) {
List<String> funs = Arrays.asList("getPayTypeAmountCount", "getVipRechargeAmountCount", "getNewMemberCount", "getCustomerUnitPrice", "getTableTurnoverRate");
Map<String, Object> collect = funs.parallelStream().collect(Collectors.toMap(fun -> fun, fun ->
ReflectUtil.invoke(shopOrderStatisticMapper, fun, param)
@@ -106,13 +115,6 @@ public class DataSummaryServiceImpl implements DataSummaryService {
data.setDiscountAmount(discountAmount);
data.setDiscountCount(discountCount);
return data;
/*ShopOrderStatistic shopOrderStatistic = shopOrderStatisticMapper.getTradeData(param);
long newMemberCount = shopOrderStatisticMapper.getNewMemberCount(param);
data.setNewMemberCount(newMemberCount);
shopOrderStatistic.setCustomerUnitPrice(shopOrderStatistic.getCustomerUnitPrice().setScale(2, java.math.RoundingMode.HALF_UP));
shopOrderStatistic.setTableTurnoverRate(shopOrderStatistic.getTableTurnoverRate().setScale(2, java.math.RoundingMode.HALF_UP));
return shopOrderStatistic;*/
}
@Override
@@ -129,7 +131,7 @@ public class DataSummaryServiceImpl implements DataSummaryService {
param.setBeginDate(days.getFirst() + " 00:00:00");
param.setEndDate(days.getLast() + " 23:59:59");
PageHelper.startPage(PageUtil.buildPageHelp());
PageInfo<DataSummaryProductSaleRankingVo> pageInfo = new PageInfo<>(shopProdStatisticMapper.findProdRandingSummaryPage2(param));
PageInfo<DataSummaryProductSaleRankingVo> pageInfo = new PageInfo<>(shopProdStatisticMapper.findProdRandingSummaryPage(param));
return PageUtil.convert(pageInfo);
}
@@ -138,7 +140,7 @@ public class DataSummaryServiceImpl implements DataSummaryService {
LocalDate now = LocalDate.now();
LocalDate beginDate = now.plusDays(-day);
DataSummaryDateAmountVo data = new DataSummaryDateAmountVo();
List<DataSummaryDateAmountVo.TotalVo> total = new ArrayList<>();
List<TotalVo> total = new ArrayList<>();
for (int i = 1; i <= day; i++) {
String thisDay = beginDate.plusDays(i).format(DatePattern.NORM_DATE_FORMATTER);
OrderInfo orderInfo = orderInfoMapper.selectOneByQuery(QueryWrapper.create()
@@ -147,7 +149,7 @@ public class DataSummaryServiceImpl implements DataSummaryService {
.eq(OrderInfo::getTradeDay, thisDay)
.isNotNull(OrderInfo::getPaidTime)
);
DataSummaryDateAmountVo.TotalVo totalVo = new DataSummaryDateAmountVo.TotalVo();
TotalVo totalVo = new TotalVo();
if (orderInfo != null) {
totalVo.setOrderAmount(orderInfo.getOrderAmount());
totalVo.setActualAmount(orderInfo.getPayAmount());
@@ -209,4 +211,5 @@ public class DataSummaryServiceImpl implements DataSummaryService {
public List<Long> getShopIdList() {
return shopOrderStatisticMapper.getShopIdList();
}
}

View File

@@ -27,7 +27,7 @@ public class SaleSummaryServiceImpl implements SaleSummaryService {
@Override
public SaleSummaryCountVo summaryCount(SaleSummaryCountParam param) {
SaleSummaryCountVo saleSummaryCount = shopProdStatisticMapper.getSaleSummaryCount2(param);
SaleSummaryCountVo saleSummaryCount = shopProdStatisticMapper.getSaleSummaryCount(param);
if (saleSummaryCount == null) {
saleSummaryCount = new SaleSummaryCountVo();
}
@@ -37,12 +37,12 @@ public class SaleSummaryServiceImpl implements SaleSummaryService {
@Override
public Page<SaleSummaryInfoVo> summaryPage(SaleSummaryCountParam param) {
PageHelper.startPage(PageUtil.buildPageHelp());
PageInfo<SaleSummaryInfoVo> pageInfo = new PageInfo<>(shopProdStatisticMapper.findSaleSummaryList2(param));
PageInfo<SaleSummaryInfoVo> pageInfo = new PageInfo<>(shopProdStatisticMapper.findSaleSummaryList(param));
return PageUtil.convert(pageInfo);
}
@Override
public List<SaleSummaryInfoVo> summaryList(SaleSummaryCountParam param) {
return shopProdStatisticMapper.findSaleSummaryList2(param);
return shopProdStatisticMapper.findSaleSummaryList(param);
}
}

View File

@@ -10,9 +10,9 @@ import com.czg.order.service.ShopOrderStatisticService;
import com.czg.service.order.mapper.ShopOrderStatisticMapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
@@ -23,34 +23,54 @@ import java.util.List;
* @since 2025-03-07
*/
@Service
@Slf4j
public class ShopOrderStatisticServiceImpl extends ServiceImpl<ShopOrderStatisticMapper, ShopOrderStatistic> implements ShopOrderStatisticService {
@Resource
private DataSummaryService dataSummaryService;
@Override
public void statistic() {
// 获取前一天
DateTime yesterday = DateUtil.yesterday();
public void statistic(DateTime dateTime) {
// 获取前一天的开始时间00:00:00
DateTime startOfDay = DateUtil.beginOfDay(yesterday);
DateTime startOfDay = DateUtil.beginOfDay(dateTime);
// 获取前一天的结束时间23:59:59
DateTime endOfDay = DateUtil.endOfDay(yesterday);
DateTime endOfDay = DateUtil.endOfDay(dateTime);
List<Long> shopIdList = dataSummaryService.getShopIdList();
if (CollUtil.isEmpty(shopIdList)) {
return;
}
shopIdList.parallelStream().forEach(shopId -> {
DataSummaryTradeParam param = new DataSummaryTradeParam();
param.setShopId(shopId);
param.setBeginDate(startOfDay.toStringDefaultTimeZone());
param.setEndDate(endOfDay.toStringDefaultTimeZone());
ShopOrderStatistic statistic = dataSummaryService.getTradeData(param);
statistic.setShopId(shopId);
statistic.setCreateDay(LocalDate.now());
statistic.setUpdateTime(LocalDateTime.now());
saveOrUpdate(statistic);
});
List<List<Long>> split = CollUtil.split(shopIdList, 5);
for (List<Long> splitIdList : split) {
splitIdList.parallelStream().forEach(shopId -> {
DataSummaryTradeParam param = new DataSummaryTradeParam();
param.setShopId(shopId);
param.setBeginDate(startOfDay.toStringDefaultTimeZone());
param.setEndDate(endOfDay.toStringDefaultTimeZone());
ShopOrderStatistic statistic = dataSummaryService.getRealTimeTradeData(param);
statistic.setShopId(shopId);
statistic.setCreateDay(dateTime.toLocalDateTime().toLocalDate());
statistic.setUpdateTime(LocalDateTime.now());
if (statistic.getNewMemberCount() != 0L) {
System.out.println("newMemberCount:" + statistic.getNewMemberCount());
}
// 如果没有订单和退款,则不更新数据,否则会产出很多数据
if (statistic.getSaleCount() == 0
&& statistic.getRefundCount() == 0
&& statistic.getMemberPayCount() == 0
&& statistic.getNewMemberCount() == 0
) {
log.info("店铺:{}{},没有要存档的订单统计数据", shopId, dateTime.toDateStr());
} else {
ShopOrderStatistic entity = getMapper().selectOneByQuery(query().eq(ShopOrderStatistic::getShopId, shopId).eq(ShopOrderStatistic::getCreateDay, dateTime.toDateStr()));
if (entity != null) {
statistic.setId(entity.getId());
updateById(statistic);
} else {
save(statistic);
}
}
});
}
}
}

View File

@@ -1,35 +1,41 @@
package com.czg.service.order.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.czg.order.entity.OrderDetail;
import com.czg.order.service.OrderDetailService;
import cn.hutool.core.util.NumberUtil;
import com.czg.order.entity.ShopProdStatistic;
import com.czg.order.param.DataSummaryProductSaleParam;
import com.czg.order.service.DataSummaryService;
import com.czg.order.service.ShopProdStatisticService;
import com.czg.order.vo.DataSummaryProductSaleRankingVo;
import com.czg.service.order.mapper.ShopProdStatisticMapper;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.czg.order.entity.ShopProdStatistic;
import com.czg.order.service.ShopProdStatisticService;
import com.czg.service.order.mapper.ShopProdStatisticMapper;
import jakarta.annotation.Resource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 服务层实现。
* 服务层实现。
*
* @author zs
* @since 2025-03-07
*/
@Service
public class ShopProdStatisticServiceImpl extends ServiceImpl<ShopProdStatisticMapper, ShopProdStatistic> implements ShopProdStatisticService{
@Slf4j
public class ShopProdStatisticServiceImpl extends ServiceImpl<ShopProdStatisticMapper, ShopProdStatistic> implements ShopProdStatisticService {
@Resource
private OrderDetailService orderDetailService;
private DataSummaryService dataSummaryService;
@Resource
private ShopProdStatisticMapper shopProdStatisticMapper;
@Data
private static class StatisticTask{
private static class StatisticTask {
private BigDecimal successCount = BigDecimal.ZERO;
private BigDecimal successAmount = BigDecimal.ZERO;
private BigDecimal refundCount = BigDecimal.ZERO;
@@ -37,57 +43,42 @@ public class ShopProdStatisticServiceImpl extends ServiceImpl<ShopProdStatisticM
}
@Override
public void statistic() {
// 获取前一天
DateTime yesterday = DateUtil.yesterday();
public void statistic(DateTime dateTime) {
// 获取前一天的开始时间00:00:00
DateTime startOfDay = DateUtil.beginOfDay(yesterday);
DateTime startOfDay = DateUtil.beginOfDay(dateTime);
// 获取前一天的结束时间23:59:59
DateTime endOfDay = DateUtil.endOfDay(yesterday);
List<OrderDetail> orderDetails = orderDetailService.list(new QueryWrapper()
.ge(OrderDetail::getCreateTime, startOfDay)
.le(OrderDetail::getCreateTime, endOfDay)
.ne(OrderDetail::getStatus, "wait-pay"));
HashMap<Long, Map<Long, StatisticTask>> countInfo = new HashMap<>();
for (OrderDetail item : orderDetails) {
Map<Long, StatisticTask> map = countInfo.computeIfAbsent(item.getShopId(), k -> new HashMap<>());
StatisticTask statisticTask = map.get(item.getProductId());
if (statisticTask == null) {
map.put(item.getProductId(), statisticTask = new StatisticTask());
}
if ("refunding".equals(item.getStatus()) || "refund".equals(item.getStatus()) || "part-refund".equals(item.getStatus())) {
statisticTask.setRefundAmount(statisticTask.getRefundAmount().add(item.getReturnAmount()));
statisticTask.setRefundCount(statisticTask.getRefundCount().add(item.getRefundNum()));
if (item.getReturnNum().compareTo(item.getNum()) < 0) {
statisticTask.setSuccessAmount(statisticTask.getSuccessAmount().add(item.getPayAmount().subtract(item.getReturnAmount())));
statisticTask.setSuccessCount(statisticTask.getSuccessCount().add(item.getNum().subtract(item.getReturnAmount())));
}
}else {
statisticTask.setSuccessCount(statisticTask.getSuccessCount().add(item.getNum()));
statisticTask.setSuccessAmount(statisticTask.getSuccessAmount().add(item.getPayAmount()));
}
DateTime endOfDay = DateUtil.endOfDay(dateTime);
List<Long> shopIdList = dataSummaryService.getShopIdList();
if (CollUtil.isEmpty(shopIdList)) {
return;
}
List<List<Long>> split = CollUtil.split(shopIdList, 5);
for (List<Long> splitIdList : split) {
splitIdList.parallelStream().forEach(shopId -> {
DataSummaryProductSaleParam param = new DataSummaryProductSaleParam();
param.setShopId(shopId);
param.setBeginDate(startOfDay.toStringDefaultTimeZone());
param.setEndDate(endOfDay.toStringDefaultTimeZone());
// 删除之前统计数据
getMapper().deleteByQuery(QueryWrapper.create().eq(ShopProdStatistic::getShopId, shopId).eq(ShopProdStatistic::getCreateDay, dateTime.toDateStr()));
// 重新统计数据
List<DataSummaryProductSaleRankingVo> list = shopProdStatisticMapper.findProdRandingSummaryPage2(param);
for (DataSummaryProductSaleRankingVo dto : list) {
ShopProdStatistic entity = new ShopProdStatistic();
entity.setProdId(dto.getProductId());
entity.setSaleCount(dto.getNumber());
entity.setSaleAmount(dto.getAmount());
entity.setRefundCount(dto.getRefundCount());
entity.setRefundAmount(dto.getRefundAmount());
entity.setShopId(shopId);
entity.setCreateDay(dateTime.toJdkDate());
if (NumberUtil.isLessOrEqual(entity.getSaleCount(), BigDecimal.ZERO) && NumberUtil.isLessOrEqual(entity.getRefundCount(), BigDecimal.ZERO)) {
log.info("店铺:{}{},没有要存档的商品统计数据", shopId, dateTime.toDateStr());
} else {
save(entity);
}
}
});
}
countInfo.forEach((shopId, map) -> map.forEach((productId, statisticTask) -> {
ShopProdStatistic statistic = getOne(new QueryWrapper().eq(ShopProdStatistic::getShopId, shopId).eq(ShopProdStatistic::getCreateDay, yesterday.toSqlDate()));
if (statistic == null) {
statistic = new ShopProdStatistic();
statistic.setShopId(shopId);
statistic.setCreateDay(yesterday.toSqlDate());
}
statistic.setProdId(productId);
statistic.setSaleCount(statisticTask.getSuccessCount());
statistic.setSaleAmount(statisticTask.getSuccessAmount());
statistic.setRefundCount(statisticTask.getRefundCount());
statistic.setRefundAmount(statisticTask.getRefundAmount());
saveOrUpdate(statistic);
}));
}
}

View File

@@ -1,25 +1,26 @@
package com.czg.service.order.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.czg.config.RedisCst;
import com.czg.order.entity.OrderInfo;
import com.czg.order.service.OrderInfoService;
import com.czg.order.entity.ShopTableOrderStatistic;
import com.czg.order.param.TableSummaryParam;
import com.czg.order.service.DataSummaryService;
import com.czg.order.service.ShopTableOrderStatisticService;
import com.czg.order.vo.TableSummaryInfoVo;
import com.czg.service.order.mapper.ShopTableOrderStatisticMapper;
import com.czg.utils.PageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.czg.order.entity.ShopTableOrderStatistic;
import com.czg.order.service.ShopTableOrderStatisticService;
import com.czg.service.order.mapper.ShopTableOrderStatisticMapper;
import jakarta.annotation.Resource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
/**
@@ -29,35 +30,38 @@ import java.util.List;
* @since 2025-03-07
*/
@Service
public class ShopTableOrderStatisticServiceImpl extends ServiceImpl<ShopTableOrderStatisticMapper, ShopTableOrderStatistic> implements ShopTableOrderStatisticService{
@Slf4j
public class ShopTableOrderStatisticServiceImpl extends ServiceImpl<ShopTableOrderStatisticMapper, ShopTableOrderStatistic> implements ShopTableOrderStatisticService {
@Resource
private OrderInfoService orderInfoService;
private DataSummaryService dataSummaryService;
@Resource
private ShopTableOrderStatisticMapper shopTableOrderStatisticMapper;
@Override
public Page<ShopTableOrderStatistic> summary(Long shopId, String startTime, String endTime) {
Page<Object> page = PageUtil.buildPage();
PageHelper.startPage(Math.toIntExact(page.getPageNumber()),Math.toIntExact(page.getPageSize()));
PageHelper.startPage(Math.toIntExact(page.getPageNumber()), Math.toIntExact(page.getPageSize()));
return PageUtil.convert(new PageInfo<>(mapper.selectSummary(shopId, startTime, endTime)));
}
@Override
public boolean addInfo(long shopId, long tableId, long count, BigDecimal amount) {
ShopTableOrderStatistic statistic = getOne(new QueryWrapper().eq(ShopTableOrderStatistic::getShopId, shopId).eq(ShopTableOrderStatistic::getTableId, tableId)
.eq(ShopTableOrderStatistic::getCreateDay, DateUtil.date().toDateStr()));
if (statistic == null) {
statistic = new ShopTableOrderStatistic();
statistic.setShopId(shopId);
statistic.setTableId(tableId);
statistic.setCreateDay(DateUtil.date().toSqlDate());
statistic.setOrderCount(count);
statistic.setOrderAmount(amount);
save(statistic);
}
return mapper.incrInfo(shopId, tableId, count, amount, DateUtil.date().toDateStr());
ShopTableOrderStatistic statistic = getOne(new QueryWrapper().eq(ShopTableOrderStatistic::getShopId, shopId).eq(ShopTableOrderStatistic::getTableId, tableId)
.eq(ShopTableOrderStatistic::getCreateDay, DateUtil.date().toDateStr()));
if (statistic == null) {
statistic = new ShopTableOrderStatistic();
statistic.setShopId(shopId);
statistic.setTableId(tableId);
statistic.setCreateDay(DateUtil.date().toSqlDate());
statistic.setOrderCount(count);
statistic.setOrderAmount(amount);
save(statistic);
}
return mapper.incrInfo(shopId, tableId, count, amount, DateUtil.date().toDateStr());
}
@Data
private static class StatisticTask{
private static class StatisticTask {
private long successCount = 0;
private BigDecimal successAmount = BigDecimal.ZERO;
private long refundCount = 0;
@@ -65,53 +69,46 @@ public class ShopTableOrderStatisticServiceImpl extends ServiceImpl<ShopTableOrd
}
@Override
public void statistic() {
// 获取前一天
DateTime yesterday = DateUtil.yesterday();
public void statistic(DateTime dateTime) {
// 获取前一天的开始时间00:00:00
DateTime startOfDay = DateUtil.beginOfDay(yesterday);
DateTime startOfDay = DateUtil.beginOfDay(dateTime);
// 获取前一天的结束时间23:59:59
DateTime endOfDay = DateUtil.endOfDay(yesterday);
List<OrderInfo> orderInfos = orderInfoService.list(new QueryWrapper()
.ge(OrderInfo::getCreateTime, startOfDay)
.le(OrderInfo::getCreateTime, endOfDay)
.ne(OrderInfo::getStatus, "unpaid").ne(OrderInfo::getStatus, "cancelled"));
HashMap<Long, StatisticTask> countInfo = new HashMap<>();
for (OrderInfo item : orderInfos) {
StatisticTask statisticTask = countInfo.get(item.getShopId());
if (statisticTask == null) {
countInfo.put(item.getShopId(), statisticTask = new StatisticTask());
}
if ("refunding".equals(item.getStatus()) || "refund".equals(item.getStatus()) || "part-refund".equals(item.getStatus())) {
statisticTask.setRefundAmount(statisticTask.getRefundAmount().add(item.getRefundAmount()));
statisticTask.setRefundCount(statisticTask.getRefundCount() + 1);
if (item.getRefundAmount().compareTo(item.getPayAmount()) < 0) {
statisticTask.setSuccessAmount(statisticTask.getSuccessAmount().add(item.getPayAmount().subtract(item.getRefundAmount())));
}
}else {
statisticTask.setSuccessCount(statisticTask.getSuccessCount() + 1);
statisticTask.setSuccessAmount(statisticTask.getSuccessAmount().add(item.getPayAmount()));
}
DateTime endOfDay = DateUtil.endOfDay(dateTime);
List<Long> shopIdList = dataSummaryService.getShopIdList();
if (CollUtil.isEmpty(shopIdList)) {
return;
}
List<List<Long>> split = CollUtil.split(shopIdList, 5);
for (List<Long> splitIdList : split) {
splitIdList.parallelStream().forEach(shopId -> {
TableSummaryParam param = new TableSummaryParam();
param.setShopId(shopId);
param.setBeginDate(startOfDay.toStringDefaultTimeZone());
param.setEndDate(endOfDay.toStringDefaultTimeZone());
// 删除之前统计数据
getMapper().deleteByQuery(QueryWrapper.create().eq(ShopTableOrderStatistic::getShopId, shopId).eq(ShopTableOrderStatistic::getCreateDay, dateTime.toDateStr()));
// 重新统计数据
List<TableSummaryInfoVo> list = shopTableOrderStatisticMapper.findSummaryList2(param);
for (TableSummaryInfoVo dto : list) {
ShopTableOrderStatistic entity = new ShopTableOrderStatistic();
entity.setTableId(dto.getTableId());
entity.setTableCode(dto.getTableCode());
entity.setTableName(dto.getTableName());
entity.setAreaName(dto.getAreaName());
entity.setOrderCount(dto.getOrderCount());
entity.setOrderAmount(dto.getOrderAmount());
entity.setRefundCount(dto.getRefundCount());
entity.setRefundAmount(dto.getRefundAmount());
entity.setShopId(shopId);
entity.setCreateDay(dateTime.toJdkDate());
if (entity.getOrderCount() == 0L && entity.getRefundCount() == 0L) {
log.info("店铺:{}{},没有要存档的台桌统计数据", shopId, dateTime.toDateStr());
} else {
save(entity);
}
}
});
}
countInfo.forEach((shopId, statisticTask) -> {
ShopTableOrderStatistic statistic = getOne(new QueryWrapper().eq(ShopTableOrderStatistic::getShopId, shopId).eq(ShopTableOrderStatistic::getCreateDay, yesterday.toSqlDate()));
if (statistic == null) {
statistic = new ShopTableOrderStatistic();
statistic.setShopId(shopId);
statistic.setTableId(0L);
statistic.setCreateDay(yesterday.toSqlDate());
}
statistic.setOrderCount(statisticTask.getSuccessCount());
statistic.setOrderAmount(statisticTask.getSuccessAmount());
statistic.setRefundCount(statisticTask.getRefundCount());
statistic.setRefundAmount(statisticTask.getRefundAmount());
saveOrUpdate(statistic);
});
}
}

View File

@@ -30,7 +30,7 @@ public class TableSummaryServiceImpl implements TableSummaryService {
@Override
public List<TableSummaryInfoVo> summaryList(TableSummaryParam param) {
return shopTableOrderStatisticMapper.findSummaryList2(param);
return shopTableOrderStatisticMapper.findSummaryList(param);
}
@Override

View File

@@ -17,7 +17,8 @@
<foreach item="day" collection="days" open="(" separator="," close=")">
#{day}
</foreach>
group by t1.prod_id
group by t1.prod_id,t2.name
order by sum(t1.sale_count) desc
</select>
<select id="getSaleSummaryCount" resultType="com.czg.order.vo.SaleSummaryCountVo">
select
@@ -146,10 +147,12 @@
t1.product_id,
t1.product_name,
sum(t1.num) as number,
sum(t1.pay_amount) as amount
sum(t1.pay_amount) as amount,
sum(t1.return_num) AS refundCount,
sum(t1.return_amount) AS refundAmount
from tb_order_detail t1
where t1.shop_id = #{shopId}
and t1.status = 'done'
and t1.status in ('part-refund','refund','done')
<if test="beginDate != null and beginDate != ''">
and t1.create_time >= str_to_date(#{beginDate}, '%Y-%m-%d %H:%i:%s')
</if>

View File

@@ -28,9 +28,10 @@
</select>
<select id="findSummaryList" resultType="com.czg.order.vo.TableSummaryInfoVo">
select
t1.table_code,
t1.table_id,
ifnull(t3.name,'N/A') as area_name,
ifnull(t2.name,'N/A') as table_name,
t1.table_name as table_name,
t1.area_name as area_name,
sum(t1.order_count) as order_count,
sum(t1.order_amount) as order_amount,
ifnull(sum(t1.refund_count),0) as refund_count,
@@ -45,12 +46,13 @@
<if test="endDate != null and endDate != ''">
and t1.create_day &lt;= str_to_date(#{endDate}, '%Y-%m-%d')
</if>
group by t1.table_id
order by sum(t1.order_count) desc,max(t1.id) desc
group by t1.table_code
order by sum(t1.order_count) desc,sum(t1.order_amount) desc
</select>
<select id="findSummaryList2" resultType="com.czg.order.vo.TableSummaryInfoVo">
SELECT
t1.table_code,
t2.id as table_id,
ifnull(t2.NAME,t1.table_code) AS table_name,
ifnull(t3.NAME,'未知') AS area_name,
count( t1.id ) AS order_count,
@@ -80,8 +82,8 @@
SELECT
t.product_name,
date_format(t.create_time, '%Y-%m-%d') as create_date,
if(t.table_name = '11111111','银收客',t.table_name) as table_name,
concat(if(t.table_name = '11111111','银收客',t.table_name),'-',date_format(t.create_time, '%Y-%m-%d')) as tableConcatDate,
if(t.table_name = 'NONE','银收客',t.table_name) as table_name,
concat(if(t.table_name = 'NONE','银收客',t.table_name),'-',date_format(t.create_time, '%Y-%m-%d')) as tableConcatDate,
t.category_name,
t.unit_name,
group_concat(distinct t.sku_name SEPARATOR ';') as sku_name,
@@ -95,7 +97,7 @@
SELECT
t1.product_id,
t2.table_code,
IF(t2.table_code is null or t2.table_code = '' or t6.NAME is null, '11111111', t6.NAME) AS table_name,
IF(t2.table_code is null or t2.table_code = '' or t6.NAME is null, 'NONE', t6.NAME) AS table_name,
t1.create_time,
t4.NAME AS category_name,
t3.name as product_name,

View File

@@ -14,29 +14,31 @@ import com.czg.exception.CzgException;
import com.czg.product.dto.ProdConsRelationDTO;
import com.czg.product.dto.ProdSkuDTO;
import com.czg.product.dto.ProductDTO;
import com.czg.product.dto.ShopProdCategoryDTO;
import com.czg.product.entity.*;
import com.czg.product.enums.*;
import com.czg.product.param.*;
import com.czg.product.service.ConsStockFlowService;
import com.czg.product.service.ProductService;
import com.czg.product.service.ProductStockFlowService;
import com.czg.product.service.SensitiveOperationService;
import com.czg.product.service.*;
import com.czg.product.vo.ProductStatisticsVo;
import com.czg.product.vo.ProductVO;
import com.czg.sa.StpKit;
import com.czg.service.RedisService;
import com.czg.service.product.mapper.*;
import com.czg.utils.PageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.DbChain;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
@@ -73,6 +75,10 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> impl
private final ConsStockFlowService consStockFlowService;
private final SensitiveOperationService sensitiveOperationService;
private final ProdGroupRelationMapper prodGroupRelationMapper;
private final RedisService redisService;
@Resource
@Lazy
private ShopProdCategoryService shopProdCategoryService;
private QueryWrapper buildQueryWrapper(ProductDTO param) {
QueryWrapper queryWrapper = PageUtil.buildSortQueryWrapper();
@@ -107,8 +113,11 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> impl
queryWrapper.eq(Product::getIsSale, YesNoEnum.NO.value());
}
}
Long shopId = StpKit.USER.getShopId(0L);
queryWrapper.eq(Product::getShopId, shopId);
if (param.getShopId() == null) {
Long shopId = StpKit.USER.getShopId(0L);
param.setShopId(shopId);
}
queryWrapper.eq(Product::getShopId, param.getShopId());
queryWrapper.eq(Product::getIsDel, DeleteEnum.NORMAL.value());
queryWrapper.orderBy(Product::getIsSoldStock, true);
queryWrapper.orderBy(Product::getIsSale, false);
@@ -162,7 +171,6 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> impl
}
@Override
@Cacheable(value = ADMIN_CLIENT_PRODUCT_LIST, key = "#param.shopId", unless = "#result.isEmpty()")
public List<ProductDTO> getProductList(ProductDTO param) {
QueryWrapper queryWrapper = buildFullQueryWrapper(param);
//queryWrapper.eq(Product::getIsSale, YesNoEnum.YES.value());
@@ -171,6 +179,92 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> impl
return records;
}
@Override
public List<ProductDTO> getProductCacheList(ProductDTO param) {
Long shopId = param.getShopId();
initProductCache(shopId);
String prefix = ADMIN_CLIENT_PRODUCT_LIST + "::" + shopId + "::";
List<ProductDTO> list;
if (param.getCategoryId() == null) {
list = new ArrayList<>();
Set<String> keys = redisService.rightLikeKey(prefix);
for (String key : keys) {
List<ProductDTO> prodList = redisService.getJsonToBeanList(key, ProductDTO.class);
list.addAll(prodList);
}
} else {
String key = prefix + param.getCategoryId();
list = redisService.getJsonToBeanList(key, ProductDTO.class);
}
if (StrUtil.isNotEmpty(param.getName())) {
list = list.stream().filter(obj -> StrUtil.contains(obj.getName(), param.getName())).toList();
}
// 重新进行排序
list = list.stream()
.sorted(Comparator.comparingInt(ProductDTO::getIsSoldStock))
.sorted(Comparator.comparingInt(ProductDTO::getIsSale).reversed())
.sorted(Comparator.comparingInt(ProductDTO::getSort).reversed())
.sorted(Comparator.comparingLong(ProductDTO::getId).reversed())
.toList();
return list;
}
/**
* 初始化商品缓存数据
*/
private void initProductCache(Long shopId) {
ProductDTO param = new ProductDTO();
param.setShopId(shopId);
List<ProductDTO> productList = getProductList(param);
Map<Long, List<ProductDTO>> categoryMap = productList.stream().filter(item -> item.getCategoryId() != null).collect(Collectors.groupingBy(ProductDTO::getCategoryId));
ShopProdCategoryDTO dto = new ShopProdCategoryDTO();
dto.setShopId(shopId);
List<ShopProdCategoryDTO> categoryList = shopProdCategoryService.getShopProdCategoryList(dto);
String prefix = ADMIN_CLIENT_PRODUCT_LIST + "::" + shopId + "::";
for (ShopProdCategoryDTO category : categoryList) {
String key = prefix + category.getId();
boolean b = redisService.hasKey(key);
if (!b) {
List<ProductDTO> list = categoryMap.get(category.getId());
if (CollUtil.isNotEmpty(list)) {
redisService.setJsonStr(key, list);
} else {
List<ProductDTO> empty = new ArrayList<>();
redisService.setJsonStr(key, empty);
}
}
}
}
/**
* 清除某个商品分类的缓存
*/
@Override
public void clearProductCache(Long... categoryIds) {
Long shopId = StpKit.USER.getShopId(0L);
String prefix = ADMIN_CLIENT_PRODUCT_LIST + "::" + shopId + "::";
for (Long categoryId : categoryIds) {
redisService.del(prefix + categoryId);
}
}
/**
* 系统启动会一次性加载商品缓存数据,防止首次访问时加载缓慢的问题
*/
@PostConstruct
public void initProductListCache() {
log.info("系统启动后初始化商品列表缓存,开始...");
List<Long> shopIdList = DbChain.table("tb_shop_info").select("id").objListAs(Long.class);
for (Long shopId : shopIdList) {
log.info("商品列表缓存>>当前店铺:{}", shopId);
ProductDTO dto = new ProductDTO();
dto.setShopId(shopId);
getProductCacheList(dto);
log.info("商品列表缓存>>当前店铺:{},初始化结束", shopId);
}
log.info("系统启动后初始化商品列表缓存,结束。");
}
/**
* 计算是否在可售时间内
*
@@ -223,7 +317,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> impl
@Override
@Transactional(rollbackFor = Exception.class)
@CacheEvict(value = {CacheConstant.USER_CLIENT_HOTS_PRODUCT, CacheConstant.USER_CLIENT_GROUPS_PRODUCT, ADMIN_CLIENT_PRODUCT_LIST}, key = "#dto.shopId", allEntries = true)
@CacheEvict(value = {CacheConstant.USER_CLIENT_HOTS_PRODUCT, CacheConstant.USER_CLIENT_GROUPS_PRODUCT}, key = "#dto.shopId", allEntries = true)
public void addProduct(ProductDTO dto) {
Long shopId = StpKit.USER.getShopId(0L);
boolean exists = super.exists(query().eq(Product::getName, dto.getName()).eq(Product::getShopId, shopId).eq(Product::getIsDel, DeleteEnum.NORMAL.value()));
@@ -246,6 +340,8 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> impl
entity.setShopId(shopId);
super.save(entity);
dto.setId(entity.getId());
// 清除商品分类列表缓存
clearProductCache(entity.getCategoryId());
List<ProdSkuDTO> skuList = dto.getSkuList();
if (CollUtil.isNotEmpty(skuList)) {
List<ProdSku> prodSkuList = new ArrayList<>();
@@ -283,7 +379,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> impl
@Override
@Transactional(rollbackFor = Exception.class)
@CacheEvict(value = {CacheConstant.USER_CLIENT_HOTS_PRODUCT, CacheConstant.USER_CLIENT_GROUPS_PRODUCT, ADMIN_CLIENT_PRODUCT_LIST}, key = "#dto.shopId", allEntries = true)
@CacheEvict(value = {CacheConstant.USER_CLIENT_HOTS_PRODUCT, CacheConstant.USER_CLIENT_GROUPS_PRODUCT}, key = "#dto.shopId", allEntries = true)
public void updateProduct(ProductDTO dto) {
Long shopId = StpKit.USER.getShopId(0L);
dto.setShopId(shopId);
@@ -307,11 +403,16 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> impl
}
entity.setIsDel(DeleteEnum.NORMAL.value());
entity.setShopId(shopId);
if(!ProductTypeEnum.SKU.value().equals(entity.getType())){
if (!ProductTypeEnum.SKU.value().equals(entity.getType())) {
entity.setSpecId(null);
}
entity.setSpecId(null);
super.updateById(entity);
// 清除商品分类列表缓存
if (!old.getCategoryId().equals(dto.getCategoryId())) {
// 清除旧分类缓存&新分类缓存
clearProductCache(old.getCategoryId(), entity.getCategoryId());
}
List<ProdSkuDTO> skuList = dto.getSkuList();
// 商品SKU-ID列表
List<Long> skuIdList = prodSkuMapper.selectListByQueryAs(query().select(ProdSku::getId).eq(ProdSku::getProductId, dto.getId()), Long.class);
@@ -425,8 +526,10 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> impl
}
@Override
@CacheEvict(value = {CacheConstant.USER_CLIENT_HOTS_PRODUCT, CacheConstant.USER_CLIENT_GROUPS_PRODUCT, ADMIN_CLIENT_PRODUCT_LIST}, key = "#shopId", allEntries = true)
@CacheEvict(value = {CacheConstant.USER_CLIENT_HOTS_PRODUCT, CacheConstant.USER_CLIENT_GROUPS_PRODUCT}, key = "#shopId", allEntries = true)
public void deleteProduct(Long shopId, Long id) {
Product old = getById(id);
Long categoryId = old.getCategoryId();
UpdateChain.of(Product.class)
.set(Product::getIsDel, DeleteEnum.DELETED.value())
.eq(Product::getId, id)
@@ -434,11 +537,13 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> impl
.update();
prodGroupRelationMapper.deleteByQuery(query().eq(ProdGroupRelation::getProductId, id));
prodConsRelationMapper.deleteByQuery(query().eq(ProdConsRelation::getProductId, id));
// 清除商品分类列表缓存
clearProductCache(categoryId);
}
@Override
@Transactional(rollbackFor = Exception.class)
@CacheEvict(value = {CacheConstant.USER_CLIENT_HOTS_PRODUCT, CacheConstant.USER_CLIENT_GROUPS_PRODUCT, ADMIN_CLIENT_PRODUCT_LIST}, key = "#param.shopId", allEntries = true, beforeInvocation = true)
@CacheEvict(value = {CacheConstant.USER_CLIENT_HOTS_PRODUCT, CacheConstant.USER_CLIENT_GROUPS_PRODUCT}, key = "#param.shopId", allEntries = true, beforeInvocation = true)
public void onOffProduct(ProductIsSaleParam param) {
Long shopId = StpKit.USER.getShopId(0L);
String type = param.getType();
@@ -450,6 +555,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> impl
} else {
sensitiveOperation = "下架";
}
Long prodId = null;
if (ProductIsSaleTypeEnum.SKU.value().equals(type)) {
ProdSku prodSku = prodSkuMapper.selectOneById(id);
if (prodSku == null) {
@@ -468,6 +574,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> impl
.eq(Product::getId, prodSku.getProductId())
.eq(Product::getShopId, shopId)
.update();
prodId = prodSku.getProductId();
}
Long productId = prodSku.getProductId();
Product product = mapper.selectOneById(productId);
@@ -484,19 +591,25 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> impl
.eq(ProdSku::getShopId, shopId)
.update();
Product product = mapper.selectOneById(id);
prodId = product.getId();
sensitiveOperation = sensitiveOperation + "商品:" + product.getName();
}
sensitiveOperationService.send(sensitiveOperation);
// 清除商品分类列表缓存
Product old = getById(prodId);
Long categoryId = old.getCategoryId();
clearProductCache(categoryId);
}
@Override
@Transactional(rollbackFor = Exception.class)
@CacheEvict(value = {CacheConstant.USER_CLIENT_HOTS_PRODUCT, CacheConstant.USER_CLIENT_GROUPS_PRODUCT, ADMIN_CLIENT_PRODUCT_LIST}, key = "#param.shopId", allEntries = true, beforeInvocation = true)
@CacheEvict(value = {CacheConstant.USER_CLIENT_HOTS_PRODUCT, CacheConstant.USER_CLIENT_GROUPS_PRODUCT}, key = "#param.shopId", allEntries = true, beforeInvocation = true)
public void markProductIsSoldOut(ProductIsSoldOutParam param) {
Long shopId = StpKit.USER.getShopId(0L);
String type = param.getType();
Long id = param.getId();
Integer isSoldOut = param.getIsSoldOut();
Long prodId = null;
if (ProductIsSaleTypeEnum.SKU.value().equals(type)) {
ProdSku prodSku = prodSkuMapper.selectOneById(id);
if (prodSku == null) {
@@ -516,6 +629,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> impl
.eq(Product::getShopId, shopId)
.update();
}
prodId = prodSku.getProductId();
} else if (ProductIsSaleTypeEnum.PRODUCT.value().equals(type)) {
UpdateChain.of(Product.class)
.set(Product::getIsSoldStock, isSoldOut)
@@ -527,7 +641,12 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> impl
.eq(ProdSku::getProductId, id)
.eq(ProdSku::getShopId, shopId)
.update();
prodId = id;
}
// 清除商品分类列表缓存
Product old = getById(prodId);
Long categoryId = old.getCategoryId();
clearProductCache(categoryId);
}
@Override

View File

@@ -6,6 +6,7 @@ import com.czg.enums.StatusEnum;
import com.czg.exception.CzgException;
import com.czg.product.dto.ShopProdCategoryDTO;
import com.czg.product.entity.ShopProdCategory;
import com.czg.product.service.ProductService;
import com.czg.product.service.ShopProdCategoryService;
import com.czg.sa.StpKit;
import com.czg.service.product.mapper.ShopProdCategoryMapper;
@@ -14,6 +15,8 @@ import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import java.util.List;
@@ -27,13 +30,20 @@ import java.util.List;
@Service
public class ShopProdCategoryServiceImpl extends ServiceImpl<ShopProdCategoryMapper, ShopProdCategory> implements ShopProdCategoryService {
@Resource
@Lazy
private ProductService productService;
private QueryWrapper buildQueryWrapper(ShopProdCategoryDTO param) {
QueryWrapper queryWrapper = PageUtil.buildSortQueryWrapper();
if (StrUtil.isNotEmpty(param.getName())) {
queryWrapper.like(ShopProdCategory::getName, param.getName());
}
Long shopId = StpKit.USER.getShopId(0L);
queryWrapper.eq(ShopProdCategory::getShopId, shopId);
if (param.getShopId() == null) {
Long shopId = StpKit.USER.getShopId(0L);
param.setShopId(shopId);
}
queryWrapper.eq(ShopProdCategory::getShopId, param.getShopId());
queryWrapper.orderBy(ShopProdCategory::getSort, true);
queryWrapper.orderBy(ShopProdCategory::getId, false);
return queryWrapper;
@@ -93,6 +103,7 @@ public class ShopProdCategoryServiceImpl extends ServiceImpl<ShopProdCategoryMap
public void deleteShopProdCategory(Long id) {
Long shopId = StpKit.USER.getShopId(0L);
super.remove(query().eq(ShopProdCategory::getId, id).eq(ShopProdCategory::getShopId, shopId));
productService.clearProductCache(id);
}
@Override
@@ -103,6 +114,7 @@ public class ShopProdCategoryServiceImpl extends ServiceImpl<ShopProdCategoryMap
.eq(ShopProdCategory::getId, id)
.eq(ShopProdCategory::getShopId, shopId)
.update();
productService.clearProductCache(id);
}
@Override
@@ -113,6 +125,7 @@ public class ShopProdCategoryServiceImpl extends ServiceImpl<ShopProdCategoryMap
.eq(ShopProdCategory::getId, id)
.eq(ShopProdCategory::getShopId, shopId)
.update();
productService.clearProductCache(id);
}
}