商品的活动同步

This commit is contained in:
liyj 2025-06-20 17:46:56 +08:00
parent 003e1b8d86
commit 310f827782
12 changed files with 544 additions and 32 deletions

View File

@ -147,7 +147,7 @@ public class ShopProductBase implements Serializable{
@ApiModelProperty(value = "单价")
@TableField(updateStrategy=NOT_EMPTY)
private BigDecimal unit_price;
private BigDecimal unit_price;
@ApiModelProperty(value = "商品分类编号,通过type决定规格但是分类下的规格值都不同")
@TableField(exist = false)

View File

@ -174,13 +174,13 @@ public class ShopProductItem implements Serializable {
@ApiModelProperty(value = "乐观锁")
private Integer version;
// @ApiModelProperty(value = "产品名称")
// @TableField(exist=false)
// private String productName;
@ApiModelProperty(value = "产品itemId组合 用,分开")
@TableField(exist=false)
private String mergedItemId;
// @ApiModelProperty(value = "商品SKU(JSON):{'uniq_id':[item_id, price, url]}")
// @TableField(exist=false)
// private String product_uniqid;
@ApiModelProperty(value = "产品价格组合 用,分开")
@TableField(exist=false)
private String mergedUnitPrices;
}

View File

@ -1,9 +1,6 @@
package com.suisung.mall.common.modules.store;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.Version;
import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ -15,6 +12,8 @@ import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.util.Date;
import static com.baomidou.mybatisplus.annotation.FieldStrategy.NOT_EMPTY;
/**
* <p>
* 活动表-通过插件实现
@ -37,67 +36,87 @@ public class ShopStoreActivityBase implements Serializable {
private Integer activity_id;
@ApiModelProperty(value = "店铺编号")
@TableField(updateStrategy = NOT_EMPTY)
private Integer store_id;
@ApiModelProperty(value = "用户编号")
@TableField(updateStrategy = NOT_EMPTY)
private Integer user_id;
@ApiModelProperty(value = "活动名称")
@TableField(updateStrategy = NOT_EMPTY)
private String activity_name;
@ApiModelProperty(value = "活动标题")
@TableField(updateStrategy = NOT_EMPTY)
private String activity_title;
@ApiModelProperty(value = "活动说明")
@TableField(updateStrategy = NOT_EMPTY)
private String activity_remark;
@ApiModelProperty(value = "套餐编号")
@TableField(updateStrategy = NOT_EMPTY)
private Integer activity_combo_id;
@ApiModelProperty(value = "活动类型")
@TableField(updateStrategy = NOT_EMPTY)
private Integer activity_type_id;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@ApiModelProperty(value = "活动开始时间")
@TableField(updateStrategy = NOT_EMPTY)
private Date activity_starttime;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@ApiModelProperty(value = "活动结束时间")
@TableField(updateStrategy = NOT_EMPTY)
private Date activity_endtime;
@ApiModelProperty(value = "活动状态(ENUM):0-未开启;1-正常;2-已结束;3-管理员关闭;4-商家关闭")
@TableField(updateStrategy = NOT_EMPTY)
private Integer activity_state;
@ApiModelProperty(value = "活动规则(json):不检索{rule_id:{}, rule_id:{}}")
@TableField(updateStrategy = NOT_EMPTY)
private String activity_rule;
@ApiModelProperty(value = "参与类型(ENUM):1-免费参与;2-积分参与;3-购买参与")
@TableField(updateStrategy = NOT_EMPTY)
private Integer activity_type;
@ApiModelProperty(value = "排序")
@TableField(updateStrategy = NOT_EMPTY)
private Integer activity_order;
@ApiModelProperty(value = "活动是否完成(ENUM):0-未完成;1-已完成;2-已解散(目前用于团购)")
@TableField(updateStrategy = NOT_EMPTY)
private Integer activity_is_finish;
@ApiModelProperty(value = "单品优惠商品编号")
@TableField(updateStrategy = NOT_EMPTY)
private String item_id;
@ApiModelProperty(value = "分站id")
@TableField(updateStrategy = NOT_EMPTY)
private Integer subsite_id;
@ApiModelProperty(value = "活动使用等级(DOT)")
@TableField(updateStrategy = NOT_EMPTY)
private String activity_use_level;
@ApiModelProperty(value = "发布时间")
@TableField(updateStrategy = NOT_EMPTY)
private Date activity_releasetime;
@ApiModelProperty(value = "活动是否线上或线下:0:线上,1:线下")
@TableField(updateStrategy = NOT_EMPTY)
private Integer activity_on_is_off;
@ApiModelProperty(value = "分享次数")
@TableField(updateStrategy = NOT_EMPTY)
private Integer activity_share_num;
@Version

View File

@ -289,4 +289,13 @@ public interface ShopProductBaseService extends IBaseService<ShopProductBase> {
List<List<ShopProductImage>> shopProductImageList,
List<ShopProductValidPeriod> shopProductValidPeriodList,
List<ShopProductAssistIndex> shopProductAssistIndexList);
/**
* 加载商品
* @param store_id
* @return
*/
Map getProductBasicIdByStore(Integer store_id);
void clearBasicIdByStore(Integer store_id);
}

View File

@ -70,4 +70,13 @@ public interface ShopProductItemService extends IBaseService<ShopProductItem> {
int lockSkuStock(Long itemId, int cart_quantity);
/**
* 加载商品
* @param store_id
* @return
*/
Map getProductItemIdByStore(Integer store_id);
void clearProductItemIdByStore(Integer store_id);
}

View File

@ -51,6 +51,7 @@ import com.suisung.mall.common.utils.CSVUtils;
import com.suisung.mall.common.utils.CheckUtil;
import com.suisung.mall.common.utils.CommonUtil;
import com.suisung.mall.common.utils.I18nUtil;
import com.suisung.mall.core.web.service.RedisService;
import com.suisung.mall.core.web.service.impl.BaseServiceImpl;
import com.suisung.mall.shop.activity.service.ShopActivityGroupbookingService;
import com.suisung.mall.shop.base.service.*;
@ -68,6 +69,7 @@ import com.suisung.mall.shop.sixun.service.SxSyncGoodsService;
import com.suisung.mall.shop.store.service.*;
import com.suisung.mall.shop.sync.Utils.ProductPriceCalculator;
import com.suisung.mall.shop.sync.Utils.ShopJsonUtils;
import com.suisung.mall.shop.sync.keymanage.RedisKey;
import com.suisung.mall.shop.sync.service.ProductMappingService;
import com.suisung.mall.shop.user.service.*;
import org.apache.commons.lang3.StringUtils;
@ -211,7 +213,7 @@ public class ShopProductBaseServiceImpl extends BaseServiceImpl<ShopProductBaseM
@Autowired
private ProductMappingService productMappingService;
private RedisService redisService;
@Override
@ -5417,6 +5419,7 @@ public class ShopProductBaseServiceImpl extends BaseServiceImpl<ShopProductBaseM
newShopProductAssistIndexList,updateShopProductAssistIndexList);
}
/**
* 执行批量操作新增和更新分开处理
*/
@ -6151,6 +6154,26 @@ public class ShopProductBaseServiceImpl extends BaseServiceImpl<ShopProductBaseM
}
}
@Override
public Map getProductBasicIdByStore(Integer store_id) {
String key=redisService.get(RedisKey.STORESHOPPRODUCTKEY)+":"+store_id;
if(null!=redisService.get(key)){
return (Map) redisService.get(key);
}
QueryWrapper<ShopProductBase> queryWrapper=new QueryWrapper();
queryWrapper.select("product_number","product_id");
List<ShopProductBase> shopProductBaseList= this.list(queryWrapper);
Map map= shopProductBaseList.stream().collect(Collectors.toMap(shopBase->shopBase.getProduct_number(),shopBase->shopBase.getProduct_id()));
redisService.set(RedisKey.STORESHOPPRODUCTKEY,map,60*10);
return map;
}
@Override
public void clearBasicIdByStore(Integer store_id) {
String key=redisService.get(RedisKey.STORESHOPPRODUCTKEY)+":"+store_id;
if(null!=redisService.get(key)){
redisService.del(key);
}
}
}

View File

@ -55,6 +55,7 @@ import com.suisung.mall.shop.product.mapper.ShopProductItemMapper;
import com.suisung.mall.shop.product.pojo.vo.ProductVo;
import com.suisung.mall.shop.product.service.*;
import com.suisung.mall.shop.store.service.*;
import com.suisung.mall.shop.sync.keymanage.RedisKey;
import com.suisung.mall.shop.user.service.ShopUserFavoritesItemService;
import com.suisung.mall.shop.user.service.ShopUserProductBrowseService;
import io.seata.spring.annotation.GlobalTransactional;
@ -2243,6 +2244,36 @@ public class ShopProductItemServiceImpl extends BaseServiceImpl<ShopProductItemM
return flag;
}
@Override
public Map getProductItemIdByStore(Integer store_id) {
String key= RedisKey.STORESHOPPRODUCITEMTKEY+":"+store_id;
if(null!=redisService.get(key)){
return (Map) redisService.get(key);
}
QueryWrapper<ShopProductItem> queryWrapper = new QueryWrapper<>();
/**
* 一对多如product_id:1002,item_number:120_121;数据格式为item_id,item_id item_unit_price,item_unit_price
* 最终组合item_id,item_id_item_unit_price,item_unit_price
*/
queryWrapper.select("product_id","GROUP_CONCAT(item_id SEPARATOR ',') AS mergedItemId","GROUP_CONCAT(item_unit_price SEPARATOR ',') AS mergedUnitPrices");
queryWrapper.eq("store_id",store_id);
queryWrapper.groupBy("product_id");
List<ShopProductItem> shopProductItems= this.list(queryWrapper);
Map map=shopProductItems.stream().collect(Collectors.toMap(ShopProductItem::getProduct_id,shopProductItem->shopProductItem.getMergedItemId()
+"_"+shopProductItem.getMergedUnitPrices()));
redisService.set(key,map,60*10);
return map;
}
@Override
public void clearProductItemIdByStore(Integer store_id) {
String key= RedisKey.STORESHOPPRODUCITEMTKEY+":"+store_id;
if(null!=redisService.get(key)){
redisService.del(key);
}
}
/**
* 清理库存缓存
*
@ -2257,4 +2288,6 @@ public class ShopProductItemServiceImpl extends BaseServiceImpl<ShopProductItemM
}
}
}

View File

@ -24,6 +24,7 @@ import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
@ -149,10 +150,38 @@ public class SyncThirdDataController {
@ApiOperation(value = "通知上传商品文件到cos", notes = "通知上传商品文件到cos")
@RequestMapping(value = "/uploudToCos", method = RequestMethod.POST)
public ThirdApiRes uploudToCos(@RequestBody List<String> folders,
@RequestParam String appKey,
@RequestParam String appKey,
@RequestParam String sign,
@RequestParam Date refreshDate,
@RequestParam String syncType) {
return syncThirdDataService.fileUploadToOss(appKey,sign,syncType,refreshDate,folders);
}
/**
* todo test
* 目前只同步满减和折扣
* @param appKey
* @param sign
* @param activeJsonArray
* @return
*/
@ApiOperation(value = "同步活动数据", notes = "同步商品数据")
@RequestMapping(value = "/syncAtive", method = RequestMethod.POST)
public ThirdApiRes syncAtive(@RequestParam String appKey,
@RequestParam String sign,
@RequestParam String syncType) {
return syncThirdDataService.fileUploadToOss(appKey,sign,syncType,folders);
@RequestBody JSONArray activeJsonArray) {
syncThirdDataService.syncActives(appKey,sign,activeJsonArray);
return new ThirdApiRes().success("服务器已执行活动数据操作");
}
//todo test
@ApiOperation(value = "同步活动商品数据", notes = "同步活动商品数据")
@RequestMapping(value = "/syncAtiveShop", method = RequestMethod.POST)
public ThirdApiRes syncAtiveShop(@RequestParam String appKey,
@RequestParam String sign,
@RequestBody JSONArray activeJsonArray) {
syncThirdDataService.syncActiveShops(appKey,sign,activeJsonArray);
return new ThirdApiRes().success("服务器已执行活动数据操作");
}

View File

@ -15,4 +15,7 @@ public class RedisKey {
public static final String STOREDATAPRODUCTSPECITEM="storedata:ProductSpecItem";
public static final String STORESHOPPRODUCTKEY="storedata:shopProductkey";
public static final String STORESHOPPRODUCITEMTKEY="storedata:shopProductItemKey";
}

View File

@ -136,4 +136,22 @@ public interface SyncThirdDataService {
* @return
*/
ThirdApiRes fileUploadToOss(String appKey, String sign, String syncType, List<String> folders);
/**
*同步活动
* @param appKey
* @param sign
* @param activeJsonArray
* @return
*/
void syncActives(String appKey, String sign, JSONArray activeJsonArray);
/**
*同步活动商品
* @param appKey
* @param sign
* @param activeJsonArray
* @return
*/
void syncActiveShops(String appKey, String sign, JSONArray activeJsonArray);
}

View File

@ -4,6 +4,7 @@ import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
@ -29,10 +30,12 @@ import com.suisung.mall.common.modules.pay.PayUserResource;
import com.suisung.mall.common.modules.product.*;
import com.suisung.mall.common.modules.sixun.SxSyncGoods;
import com.suisung.mall.common.modules.sixun.SxSyncVip;
import com.suisung.mall.common.modules.store.ShopStoreActivityBase;
import com.suisung.mall.common.modules.store.ShopStoreBase;
import com.suisung.mall.common.pojo.req.SyncThirdMemberReq;
import com.suisung.mall.common.utils.DateTimeUtils;
import com.suisung.mall.common.utils.I18nUtil;
import com.suisung.mall.common.utils.JsonUtil;
import com.suisung.mall.common.utils.StringUtils;
import com.suisung.mall.shop.base.service.ShopBaseProductBrandService;
import com.suisung.mall.shop.base.service.ShopBaseProductCategoryService;
@ -45,6 +48,7 @@ import com.suisung.mall.shop.product.service.ShopProductItemService;
import com.suisung.mall.shop.product.service.impl.ShopProductBaseServiceImpl;
import com.suisung.mall.shop.product.service.impl.ShopProductItemServiceImpl;
import com.suisung.mall.shop.sixun.dto.SxGoosModel;
import com.suisung.mall.shop.store.service.ShopStoreActivityBaseService;
import com.suisung.mall.shop.store.service.ShopStoreBaseService;
import com.suisung.mall.shop.sync.service.ProductMappingService;
import org.apache.commons.lang3.math.NumberUtils;
@ -89,7 +93,7 @@ public abstract class SyncBaseThirdSxAbstract{
private ShopBaseProductSpecService shopBaseProductSpecService;
@Autowired
private ProductMappingService productMappingService;
private ShopStoreActivityBaseService shopStoreActivityBaseService;
/**
* 对商品分类进行保存
@ -662,10 +666,9 @@ public abstract class SyncBaseThirdSxAbstract{
shopProductItem.setItem_quantity(99); // 库存
shopProductItem.setItem_weight(new BigDecimal("0"));//切割重量
}
shopProductItem.setItem_quantity_frozen(0);
shopProductItem.setItem_number(jsonObj.getStr("product_number"));// SKU商家编码
shopProductItem.setItem_barcode(jsonObj.getStr("product_number")); // 条形码正常情况下就是货号
shopProductItem.setItem_barcode(jsonObj.getStr("product_barcode")); // 条形码正常情况下就是货号
shopProductItem.setItem_is_default(1);
shopProductItem.setItem_enable(shopProductBase.getProduct_state_id());
@ -813,4 +816,46 @@ public abstract class SyncBaseThirdSxAbstract{
return shopBaseProductSpecService.list(query);
}
/**
* 检查哪些活动已经存在 根据活动名称+活动状态
*/
public Map<String, String> checkExistingActive(JSONArray jsonArray,Integer storeId) {
List<ShopStoreActivityBase> storeProductPairs = jsonArray.stream()
.map(object->{
final JSONObject jsonObj= (JSONObject) object;
ShopStoreActivityBase shopStoreActivityBase=new ShopStoreActivityBase();
shopStoreActivityBase.setActivity_name(jsonObj.getStr("activityName"));
shopStoreActivityBase.setActivity_state(jsonObj.getInt("activityState"));
shopStoreActivityBase.setActivity_starttime(jsonObj.getDate("activityStarttime"));
return shopStoreActivityBase;
})
.distinct()
.collect(Collectors.toList());
List<ShopStoreActivityBase> existing = batchGetByAtiveShopBase(storeProductPairs,storeId);
return existing.stream()
.collect(Collectors.toMap(
shopStoreActivityBase -> shopStoreActivityBase.getActivity_title()+"_"+shopStoreActivityBase.getActivity_starttime().getTime()+"_"+shopStoreActivityBase.getActivity_state(),
shopStoreActivityBase->shopStoreActivityBase.getActivity_id()+"_"+shopStoreActivityBase.getActivity_rule()
));
}
/**
* 批量根据店铺和货号查询商品
*/
private List<ShopStoreActivityBase> batchGetByAtiveShopBase(List<ShopStoreActivityBase> shopStoreActivityBases,Integer storeId) {
if (CollUtil.isEmpty(shopStoreActivityBases)) {
return Collections.emptyList();
}
QueryWrapper<ShopStoreActivityBase> query = new QueryWrapper<>();
query.select("activity_name", "activity_state");
shopStoreActivityBases.forEach(shopStoreActivityBase -> {
query.or(q -> q.eq("activity_name", shopStoreActivityBase.getActivity_name()).eq("activity_state",shopStoreActivityBase.getActivity_state())
.eq("activity_starttime",shopStoreActivityBase.getActivity_starttime())
.eq("store_id", storeId));
});
return shopStoreActivityBaseService.list(query);
}
}

View File

@ -12,11 +12,13 @@ import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
@ -72,6 +74,8 @@ import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
@ -827,27 +831,347 @@ public class SyncThirdDataServiceImpl extends SyncBaseThirdSxAbstract implements
}
@Override
public ThirdApiRes fileUploadToOss(String appKey, String sign, String syncType, List<String> folders) {
SyncApp syncApp = syncAppService.getOne(new LambdaQueryWrapper<SyncApp>()
.select(SyncApp::getApp_key, SyncApp::getApp_secret, SyncApp::getStore_id)
.eq(SyncApp::getApp_key, appKey)
.eq(SyncApp::getApp_secret, sign));
String storeId = syncApp.getStore_id();
Date tenMinutesAgo = Date.from(Instant.now().minus(Duration.ofMinutes(5)));//校准误差
Date date = DateUtil.date(tenMinutesAgo);
if (null == syncApp.getStore_id() || syncApp.getStore_id().isEmpty()) {
logger.info("商品id为空");
return new ThirdApiRes().fail(250, "商品id为空");
public ThirdApiRes fileUploadToOss(String appKey, String sign, String syncType,Date refreshDate, List<String> folders) {
if (StrUtil.isBlank(appKey) || StrUtil.isBlank(sign) ) {
return new ThirdApiRes().fail(1003, I18nUtil._("缺少必要参数!"));
}
if (folders == null || folders.isEmpty()) {
// 验签appid必要参数判断
SyncApp syncApp = syncAppService.getOne(new LambdaQueryWrapper<SyncApp>()
.select(SyncApp::getApp_key, SyncApp::getApp_secret,SyncApp::getStore_id)
.eq(SyncApp::getApp_key, appKey)
.eq(SyncApp::getApp_secret,sign));
if (syncApp == null) {
return new ThirdApiRes().fail(1001, I18nUtil._("签名有误!"));
}
String storeId = syncApp.getStore_id();
if(null==syncApp.getStore_id()|| syncApp.getStore_id().isEmpty()){
logger.info("商店id为空");
return new ThirdApiRes().fail(250,"商店id为空");
}
if(folders==null||folders.isEmpty()){
logger.info("没有商品数据");
return new ThirdApiRes().fail(250, "没有商品数据");
return new ThirdApiRes().fail(250,"没有商品数据");
}
String newfolder = new FileUtils().getSyncTypeFlag(syncType, clientPath) + storeId + FileUtils.pathSeparator + folders.get(0) + FileUtils.pathSeparator;
String newfolder=new FileUtils().getSyncTypeFlag(syncType,clientPath)+storeId+FileUtils.pathSeparator+folders.get(0)+FileUtils.pathSeparator;
upLoadZipToOss(newfolder);//上传文件到cos
//更新当前的获取时间用户客户端获取
try {
QueryWrapper<StoreDbConfig> storeDbConfigQueryWrapper = new QueryWrapper<>();
storeDbConfigQueryWrapper.eq("store_id", storeId);
StoreDbConfig storeDbConfig=storeDbConfigService.getOne(storeDbConfigQueryWrapper);
if(ObjectUtil.isNotEmpty(storeDbConfig)){
storeDbConfig.setRefreshTime(refreshDate);
storeDbConfigService.saveOrUpdate(storeDbConfig);
}
}catch (RuntimeException e){
logger.error("同步时间失败"+e.getMessage());
}
return new ThirdApiRes().success("上传成功");
}
@Override
public ThirdApiRes fileUploadToOss(String appKey, String sign, String syncType,Date refreshDate, List<String> folders) {
if (StrUtil.isBlank(appKey) || StrUtil.isBlank(sign) ) {
return new ThirdApiRes().fail(1003, I18nUtil._("缺少必要参数!"));
}
// 验签appid必要参数判断
SyncApp syncApp = syncAppService.getOne(new LambdaQueryWrapper<SyncApp>()
.select(SyncApp::getApp_key, SyncApp::getApp_secret,SyncApp::getStore_id)
.eq(SyncApp::getApp_key, appKey)
.eq(SyncApp::getApp_secret,sign));
if (syncApp == null) {
return new ThirdApiRes().fail(1001, I18nUtil._("签名有误!"));
}
String storeId = syncApp.getStore_id();
if(null==syncApp.getStore_id()|| syncApp.getStore_id().isEmpty()){
logger.info("商店id为空");
return new ThirdApiRes().fail(250,"商店id为空");
}
if(folders==null||folders.isEmpty()){
logger.info("没有商品数据");
return new ThirdApiRes().fail(250,"没有商品数据");
}
String newfolder=new FileUtils().getSyncTypeFlag(syncType,clientPath)+storeId+FileUtils.pathSeparator+folders.get(0)+FileUtils.pathSeparator;
upLoadZipToOss(newfolder);//上传文件到cos
//更新当前的获取时间用户客户端获取
try {
QueryWrapper<StoreDbConfig> storeDbConfigQueryWrapper = new QueryWrapper<>();
storeDbConfigQueryWrapper.eq("store_id", storeId);
StoreDbConfig storeDbConfig=storeDbConfigService.getOne(storeDbConfigQueryWrapper);
if(ObjectUtil.isNotEmpty(storeDbConfig)){
storeDbConfig.setRefreshTime(refreshDate);
storeDbConfigService.saveOrUpdate(storeDbConfig);
}
}catch (RuntimeException e){
logger.error("同步时间失败"+e.getMessage());
}
return new ThirdApiRes().success("上传成功");
}
@Override
@Async
public void syncActives(String appKey, String sign, JSONArray activeJsonArray) {
if (StrUtil.isBlank(appKey) || StrUtil.isBlank(sign) || ObjectUtil.isEmpty(activeJsonArray)) {
logger.error("缺少必要参数!");
return;
}
// 验签appid必要参数判断
SyncApp syncAppO = syncAppService.getOne(new LambdaQueryWrapper<SyncApp>()
.select(SyncApp::getApp_key, SyncApp::getApp_secret,SyncApp::getStore_id)
.eq(SyncApp::getApp_key, appKey)
.eq(SyncApp::getApp_secret,sign));
if (syncAppO == null) {
logger.error("签名有误!");
return;
}
String storeId = syncAppO.getStore_id();
//活动逻辑
batchSaveShopStoreActivityBase(activeJsonArray, Integer.valueOf(storeId));
}
/**
* 批量新增或更新活动数据
* @param jsonArray
*/
private void batchSaveShopStoreActivityBase(JSONArray jsonArray,Integer storeId) {
List<ShopStoreActivityBase> addshopStoreActivityBaseList=new ArrayList<>();
List<ShopStoreActivityBase> updateShopStoreActivityBaseList=new ArrayList<>();
Map<String, String> stringIntegerMap= checkExistingActive(jsonArray,storeId);
jsonArray.stream().parallel().forEach(object->{
final JSONObject jsonObj= (JSONObject) object;
String activityName=jsonObj.getStr("activityName");
Integer activityTypeId=jsonObj.getInt("activityTypeId");
if(null==activityTypeId){
return;
}
ShopStoreActivityBase shopStoreActivityBase=new ShopStoreActivityBase();
if (activityTypeId == 1) {
activityTypeId = StateCode.ACTIVITY_TYPE_LIMITED_DISCOUNT; //限时秒杀
}
if (activityTypeId == 2) {
activityTypeId = StateCode.ACTIVITY_TYPE_ONE_PIECE_DISCOUNT; //折扣
}
if (activityTypeId == 3) {
JSONArray activeMaxDesList=jsonObj.getJSONArray("activeMaxDesList");
activityTypeId = StateCode.ACTIVITY_TYPE_REDUCTION; //满减
String rules= ActiveShopJsonUtils.getRules(activeMaxDesList);
shopStoreActivityBase.setActivity_rule(rules);
}
Date activityStarttime=jsonObj.getDate("activityStarttime");
Date activityEndtime=jsonObj.getDate("activityEndtime");
Integer activityState=jsonObj.getInt("activityState");
Date activityReleasetime= jsonObj.getDate("activityReleasetime");
BigDecimal discount=jsonObj.getBigDecimal("discount");
String key=activityName+"_"+activityStarttime.getTime()+"_"+activityState;
shopStoreActivityBase.setActivity_state(activityState);
shopStoreActivityBase.setActivity_name(activityName);
shopStoreActivityBase.setActivity_type(1);//免费参与
shopStoreActivityBase.setActivity_releasetime(activityReleasetime);
shopStoreActivityBase.setStore_id(storeId);
shopStoreActivityBase.setActivity_on_is_off(0);
shopStoreActivityBase.setActivity_type_id(activityTypeId);
shopStoreActivityBase.setActivity_starttime(activityStarttime);
shopStoreActivityBase.setActivity_endtime(activityEndtime);
shopStoreActivityBase.setActivity_state(activityState);
shopStoreActivityBase.setSubsite_id(0);
if(stringIntegerMap.containsKey(key)){//更新
String keyVal= MapUtil.getStr(stringIntegerMap,key);
shopStoreActivityBase.setActivity_id(MapUtil.getInt(stringIntegerMap,keyVal.split("_")[0]));
updateShopStoreActivityBaseList.add(shopStoreActivityBase);
}else {
addshopStoreActivityBaseList.add(shopStoreActivityBase);
}
});
if(CollectionUtil.isNotEmpty(addshopStoreActivityBaseList)){
shopStoreActivityBaseService.saveBatch(addshopStoreActivityBaseList,addshopStoreActivityBaseList.size());
}
if(CollectionUtil.isNotEmpty(updateShopStoreActivityBaseList)){
shopStoreActivityBaseService.updateBatchById(updateShopStoreActivityBaseList);
}
}
/**
* 将商品添加到活动
* 1找出匹配的活动
* 2新增商品到活动列表
* @param appKey
* @param sign
* @param activeJsonArray
*/
@Override
@Async
public void syncActiveShops(String appKey, String sign, JSONArray activeJsonArray) {
if (StrUtil.isBlank(appKey) || StrUtil.isBlank(sign) || ObjectUtil.isEmpty(activeJsonArray)) {
logger.error("缺少必要参数!");
return;
}
// 验签appid必要参数判断
SyncApp syncAppO = syncAppService.getOne(new LambdaQueryWrapper<SyncApp>()
.select(SyncApp::getApp_key, SyncApp::getApp_secret,SyncApp::getStore_id)
.eq(SyncApp::getApp_key, appKey)
.eq(SyncApp::getApp_secret,sign));
if (syncAppO == null) {
logger.error("签名有误!");
return;
}
String storeId = syncAppO.getStore_id();
//把商品添加到活动的逻辑
batchAddActiveShopBase(activeJsonArray, Integer.valueOf(storeId));
}
/**
* 批量新增或更新活动商品数据
* @param jsonArray
*/
private void batchAddActiveShopBase(JSONArray jsonArray,Integer storeId) {
List<ShopStoreActivityBase> updateShopStoreActivityBaseList=new ArrayList<>();
Map<String, String> stringIntegerMap= checkExistingActive(jsonArray,storeId);
Map shopProduckKeyMap=shopProductBaseService.getProductBasicIdByStore(storeId);//获取货架号对应的商品id
Map shopItemKeyMap=shopProductItemService.getProductItemIdByStore(storeId);//获取商品id对应的item的id
Map<String,String> rulesChe=new HashMap();//存储rule格式activeId:rules,如果不存在则从数据库取存在则从缓存取数据
jsonArray.forEach(object->{
final JSONObject jsonObj= (JSONObject) object;
String activityName=jsonObj.getStr("activityName");
Integer activityTypeId=jsonObj.getInt("activityTypeId");
if(null==activityTypeId){
return;
}
String ruleType="";
List<org.json.JSONObject> newItems=new ArrayList<>();
ShopStoreActivityBase shopStoreActivityBase=new ShopStoreActivityBase();
Integer productId=null;
String itemNo=jsonObj.getStr("itemNo");
BigDecimal discount=jsonObj.getBigDecimal("discount");
if(shopProduckKeyMap.containsKey(itemNo)){
productId= (Integer) shopProduckKeyMap.get(itemNo);
}
if(null==productId){
return;
}
Date activityStarttime=jsonObj.getDate("activityStarttime");
Integer activityState=jsonObj.getInt("activityState");
String key=activityName+"_"+activityStarttime.getTime()+"_"+activityState;
if(stringIntegerMap.containsKey(key)){//更新
String keyVal=MapUtil.getStr(stringIntegerMap,key);
String activityId=keyVal.split("_")[0];
String rules="";
if(null!=rulesChe.get(activityId)){
rules=rulesChe.get(activityId);
}else {
rules=keyVal.split("_")[1];
}
String itemIds= (String) shopItemKeyMap.get(productId);
if(null!=itemIds){
itemIds= (String) shopItemKeyMap.get(String.valueOf(productId));
}
assert itemIds != null;
if (activityTypeId == 1) {//限时秒杀
ruleType=ActiveShopJsonUtils.SECKILL;
BigDecimal oldPrice=jsonObj.getBigDecimal("oldPrice");
BigDecimal specPrice=jsonObj.getBigDecimal("specPrice");
if(oldPrice.compareTo(BigDecimal.ZERO)>0&&specPrice.compareTo(BigDecimal.ZERO)>0){
BigDecimal newDiscout=specPrice.divide(oldPrice,4, RoundingMode.HALF_UP);
newItems.addAll(getFulReduItemList(itemIds,ruleType,newDiscout));//获取满减规则的itemid
}
}
if (activityTypeId == 2) {//折扣
if(discount.compareTo(BigDecimal.ZERO)<=0){
logger.error("商品折扣要大于0");
return;
}
ruleType=ActiveShopJsonUtils.DISCOUNT;
newItems.addAll(getFulReduItemList(itemIds,ruleType,discount));//获取满减规则的itemid
}
if (activityTypeId == 3) {//满减
ruleType=ActiveShopJsonUtils.FULLREDUCE;
newItems.addAll(getFulReduItemList(itemIds,ruleType,null));//获取满减规则的itemid
}
shopStoreActivityBase.setActivity_id(MapUtil.getInt(stringIntegerMap,activityId));
String newRules= ActiveShopJsonUtils.buildPromotionRule(ruleType,rules,newItems);
rulesChe.put(activityId,newRules);
shopStoreActivityBase.setActivity_rule(rules);
updateShopStoreActivityBaseList.add(shopStoreActivityBase);
}
});
if(CollectionUtil.isNotEmpty(updateShopStoreActivityBaseList)){
shopStoreActivityBaseService.updateBatchById(updateShopStoreActivityBaseList);
}
}
/**
* 一对多如product_id:1002,item_number:120_121;数据格式为item_id,item_id item_unit_price,item_unit_price
* 最终组合item_id,item_id_item_unit_price,item_unit_price
* 满减的切割规则的itemid
* @param itemPrice
* @return
*/
private List<org.json.JSONObject> getFulReduItemList(String itemPrice,String activeType,BigDecimal discount){
List<org.json.JSONObject> newItems=new ArrayList<>();
String [] itemPriceArray=itemPrice.split("_");
String itemIds=itemPriceArray[0];
String unitPrices=itemPriceArray[1];
switch (activeType){
case ActiveShopJsonUtils.DISCOUNT:
if(itemIds.contains(",")){
String [] itemIdsArray=itemIds.split(",");
for (String itemId : itemIdsArray) {
org.json.JSONObject jsonObject = new org.json.JSONObject();
jsonObject.put("item_id", itemId);
jsonObject.put("rate", BigDecimalFormatter.formatWithoutTrailingZeros(discount.multiply(new BigDecimal(100))));
newItems.add(jsonObject);
}
}else {
org.json.JSONObject jsonObject=new org.json.JSONObject();
jsonObject.put("item_id",itemIds);
jsonObject.put("rate", BigDecimalFormatter.formatWithoutTrailingZeros(discount.multiply(new BigDecimal(100))));
newItems.add(jsonObject);
}
break;
case ActiveShopJsonUtils.FULLREDUCE:
if(itemIds.contains(",")){
String [] itemIdsArray=itemIds.split(",");
for(String itemId:itemIdsArray){
org.json.JSONObject jsonObject=new org.json.JSONObject();
jsonObject.put("item_id",itemId);
newItems.add(jsonObject);
}
}else {
org.json.JSONObject jsonObject=new org.json.JSONObject();
jsonObject.put("item_id",itemIds);
newItems.add(jsonObject);
}
break;
case ActiveShopJsonUtils.SECKILL:
if(itemIds.contains(",")){
String [] unitPricesArray=unitPrices.split(",");
String [] itemIdsArray=itemIds.split(",");
for (int i=0;i<itemIdsArray.length;i++) {
org.json.JSONObject jsonObject = new org.json.JSONObject();
jsonObject.put("item_id", itemIdsArray[i]);
jsonObject.put("price", BigDecimalFormatter.formatWithoutTrailingZeros(discount.multiply(new BigDecimal(unitPricesArray[i]))));
newItems.add(jsonObject);
}
}else {
org.json.JSONObject jsonObject=new org.json.JSONObject();
jsonObject.put("item_id",itemIds);
jsonObject.put("price", BigDecimalFormatter.formatWithoutTrailingZeros(discount.multiply(new BigDecimal(unitPrices))));
newItems.add(jsonObject);
}
break;
}
return newItems;
}
}