package com.hx.phip.controller.market;
|
|
import com.alibaba.fastjson.JSONObject;
|
import com.github.pagehelper.PageHelper;
|
import com.github.pagehelper.PageInfo;
|
import com.hx.common.BaseController;
|
import com.hx.exception.TipsException;
|
import com.hx.mybatisTool.SqlSentence;
|
import com.hx.phiappt.common.*;
|
import com.hx.phiappt.constants.tool.employee.EmployeeTool;
|
import com.hx.phiappt.constants.tool.shop.ShopTool;
|
import com.hx.phiappt.dao.mapper.*;
|
import com.hx.phiappt.model.BaseEntity;
|
import com.hx.phiappt.model.EmployeeRole;
|
import com.hx.phiappt.model.User;
|
import com.hx.phiappt.model.coupon.Coupon;
|
import com.hx.phiappt.model.limit.LimitOther;
|
import com.hx.phiappt.model.limit.LimitTotal;
|
import com.hx.phiappt.model.market.*;
|
import com.hx.phip.service.EmployeeRoleService;
|
import com.hx.phip.service.market.MarketActivityService;
|
import com.hx.resultTool.Result;
|
import com.hx.util.DateUtil;
|
import com.hx.util.StringUtils;
|
import com.hz.his.dto.marketing.MarketActivityDto;
|
import com.hz.his.dto.marketing.common.MarCommonReturnDto;
|
import com.hz.his.dto.marketing.common.MarketingReturnDto;
|
import com.platform.exception.PlatTipsException;
|
import com.platform.resultTool.PlatformCode;
|
import lombok.extern.slf4j.Slf4j;
|
import org.springframework.web.bind.annotation.PostMapping;
|
import org.springframework.web.bind.annotation.RequestBody;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RestController;
|
|
import javax.annotation.Resource;
|
import java.math.BigDecimal;
|
import java.util.*;
|
import java.util.stream.Collectors;
|
|
/**
|
* 营销活动(热门活动)
|
* @USER: fhx
|
* @DATE: 2023/7/3
|
**/
|
@Slf4j
|
@RestController
|
@RequestMapping("/market/activity")
|
public class MarketActivityController extends BaseController {
|
|
@Resource
|
private MarketActivityService marketActivityService;
|
@Resource
|
private EmployeeRoleService employeeRoleService;
|
|
/** 列表 */
|
@PostMapping("/list")
|
public Result list(@RequestBody(required = false) MarketActivityDto dto) {
|
|
if(dto == null){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "请求对象为空!");
|
}
|
|
SqlSentence sqlSentence = new SqlSentence();
|
Map<String, Object> values = new HashMap<>();
|
sqlSentence.setM(values);
|
|
StringBuffer sql = new StringBuffer();
|
sql.append(" select a.id, a.title, a.intro, a.managerName, a.isUp, a.couponNum, a.isLimitShop ")
|
.append(" , date_format(a.startTime, '%Y/%m/%d') as startTime ")
|
.append(" , date_format(a.endTime, '%Y/%m/%d %H:%i:%s') as endTime ");
|
//子查询第一张轮播图
|
// .append(" , (select imgUrl from market_activity_banner ab where ab.isDel = 0 and ab.marketActivityId = a.id order by sortNo asc limit 1) as imgUrl ")
|
//用户领取
|
if(StringUtils.noNull(dto.getUserId())){
|
values.put("userId", dto.getUserId());
|
sql.append(" , ( select ifnull(sum(jr.receiveNum), 0) from market_activity_join_record jr where jr.isDel = 0 and jr.marketActivityId = a.id and jr.userId = #{m.userId} ) as receiveNum ");
|
}else{
|
sql.append(" , 0 as receiveNum ");
|
}
|
|
sql.append(" from market_activity a where a.isDel = 0 ");
|
|
//处理列表条件查询sql
|
handleListConditionQuerysSql(dto, sql, values);
|
|
sql.append(" order by a.createTime desc ");
|
sqlSentence.setSqlSentence(sql.toString());
|
|
PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
|
List<Map<String, Object>> list = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
|
PageInfo pageInfo = new PageInfo(list);
|
|
return Result.success(pageInfo);
|
}
|
|
/** 分类tab列表 */
|
@RequestMapping("/tabData")
|
public Result tabData(@RequestBody MarketActivityDto dto){
|
|
//查询活动分类
|
SqlSentence sqlSentence = new SqlSentence();
|
Map<String, Object> values = new HashMap<>();
|
sqlSentence.setM(values);
|
values.put("type", BaseClassifyConstants.TYPE_MARKET_ACTIVITY);
|
sqlSentence.setSqlSentence(" select id, name, 0 as num from base_classify where isDel = 0 and type = #{m.type} order by sortNo asc ");
|
List<Map<String, Object>> list = commonService.selectListMap(BaseClassifyMapper.class, sqlSentence);
|
|
StringBuffer sql = new StringBuffer();
|
sql.append(" select a.id, a.classifyId from market_activity a where a.isDel = 0 ");
|
//处理列表条件查询sql
|
handleListConditionQuerysSql(dto, sql, values);
|
sqlSentence.setSqlSentence(sql.toString());
|
List<Map<String, Object>> activityList = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
|
|
if(activityList != null && activityList.size() > 0){
|
//按分类id分组计算
|
Map<String, Long> countMap = activityList.stream().collect(Collectors.groupingBy(s->s.get("classifyId").toString(), Collectors.counting()));
|
//遍历赋值对应数量
|
for(Map<String, Object> m : list){
|
if(countMap.containsKey(m.get("id").toString())){
|
m.put("num", countMap.get(m.get("id").toString()));
|
}
|
}
|
}
|
|
JSONObject data = new JSONObject();
|
data.put("list", list);
|
data.put("allNum", activityList.size());
|
return Result.success(data);
|
}
|
|
/** 顶部轮播图数据 */
|
@RequestMapping("/topBannerData")
|
public Result topBannerData(@RequestBody MarketActivityDto dto){
|
|
//用户为空直接返回空数据
|
if(StringUtils.isEmpty(dto.getUserId())){
|
return Result.success();
|
}
|
|
SqlSentence sqlSentence = new SqlSentence();
|
Map<String, Object> values = new HashMap<>();
|
sqlSentence.setM(values);
|
StringBuffer sql = new StringBuffer();
|
sql.append(" select a.id, bc.name as classifyName, a.title, a.intro ")
|
.append(" , date_format(a.startTime, '%Y.%m.%d') as startTime ")
|
.append(" , date_format(a.endTime, '%Y.%m.%d') as endTime ")
|
.append(" from market_activity a ")
|
.append(" left join base_classify bc on bc.id = a.classifyId ")
|
.append(" where a.isDel = 0 ");
|
|
//设置只查询上架的
|
dto.setIsUp(BaseEntity.YES);
|
//处理列表条件查询sql
|
handleListConditionQuerysSql(dto, sql, values);
|
//查询用户未查看过的活动
|
values.put("userId", dto.getUserId());
|
sql.append(" and (select count(1) from market_activity_view_record vr where vr.isDel = 0 and vr.marketActivityId = a.id and vr.userId = #{m.userId} ) = 0 ");
|
sql.append(" order by a.createTime desc ");
|
sqlSentence.setSqlSentence(sql.toString());
|
List<Map<String, Object>> list = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
|
|
JSONObject data = new JSONObject();
|
data.put("list", list);
|
return Result.success(data);
|
}
|
|
/** 详情 */
|
@PostMapping("/detail")
|
public Result detail(@RequestBody(required = false) MarketActivityDto dto){
|
|
if(dto == null || StringUtils.isEmpty(dto.getId())){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询标识不能为空!");
|
}
|
|
MarketActivity marketActivity = commonService.selectOneByKey(MarketActivityMapper.class, dto.getId());
|
if(marketActivity == null){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到活动信息!");
|
}
|
|
User user = null;
|
if(StringUtils.noNull(dto.getUserId())){
|
user = commonService.selectOneByKey(UserMapper.class, dto.getUserId());
|
}
|
|
SqlSentence sqlSentence = new SqlSentence();
|
Map<String, Object> values = new HashMap<>();
|
sqlSentence.setM(values);
|
values.put("marketActivityId", marketActivity.getId());
|
StringBuffer sql = new StringBuffer();
|
|
//营销活动关联轮播图--------------------------------------------------
|
sqlSentence.setSqlSentence(" select imgUrl from market_activity_banner where isDel = 0 and marketActivityId = #{m.marketActivityId} order by sortNo asc ");
|
List<Map<String, Object>> bannerList = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
|
|
//营销活动关联优惠券--------------------------------------------------
|
//查询用户优惠券码判断用户是否已领取过
|
String receiveNumSql = " 0 as receiveNum ";
|
//查询用户对应优惠券是否有待审核数量
|
String waitApproveSql = " 0 as waitApproveNum ";
|
|
if(StringUtils.noNull(dto.getUserId())){
|
values.put("userId", dto.getUserId());
|
// receiveNumSql = "( select count(1) from market_activity_receive_record_item i join market_activity_receive_record r on r.id = i.receiveRecordId where i.isDel = 0 and r.userId = #{m.userId} and i.marketActivityId = ai.marketActivityId and i.commonId = ai.commonId ) as receiveNum ";
|
receiveNumSql = "( select count(1) from market_activity_receive_record_item i join market_activity_receive_record r on r.id = i.receiveRecordId where i.isDel = 0 and r.userId = #{m.userId} and i.marketActivityId = ai.marketActivityId and i.activityItemId = ai.id ) as receiveNum ";
|
//是否有待审核数量
|
// values.put("approveStatus", MarketActivityReceiveRecordItem.APPROVE_STATUS_WAIT);
|
waitApproveSql = "( select count(1) from market_activity_receive_record_item i join market_activity_receive_record r on r.id = i.receiveRecordId where i.isDel = 0 and r.userId = #{m.userId} and i.marketActivityId = ai.marketActivityId and i.activityItemId = ai.id and i.approveStatus = #{m.approveStatus} ) as waitApproveNum ";
|
}
|
|
sql.setLength(0);
|
values.put("commonType", MarketActivityConstants.COMMON_TYPE_COUPON);
|
sql.append(" select ai.marketActivityId, ai.id as activityCouponId, ai.commonId as couponId")
|
.append(" , ai.limitRecNum, ai.groupId, ai.isApprove ")
|
.append(" , c.title, c.type, c.discountAmount, c.discountNum ")
|
.append(" , c.conditionType, c.amountSatisfied, c.platformType, c.issueType ")
|
.append(" , c.useProjectType, c.useGoodsType, c.usePromotionType, c.useCardType ")
|
.append(" , date_format(c.issueStartTime, '%Y-%m-%d %H:%i:%s') as issueStartTime ")
|
.append(" , date_format(c.issueEndTime, '%Y-%m-%d %H:%i:%s') as issueEndTime ")
|
.append(" , date_format(c.startTime, '%Y-%m-%d %H:%i:%s') as startTime ")
|
.append(" , date_format(c.endTime, '%Y-%m-%d %H:%i:%s') as endTime ")
|
.append(" , ").append(receiveNumSql)
|
.append(" , ").append(waitApproveSql)
|
.append(" from market_activity_item ai ")
|
.append(" left join coupon c on c.id = ai.commonId ")
|
.append(" where ai.isDel = 0 and ai.marketActivityId = #{m.marketActivityId} ")
|
.append(" and ai.commonType = #{m.commonType} ");
|
sqlSentence.setSqlSentence(sql.toString());
|
List<Map<String, Object>> couponList = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
|
//遍历判断用户是可领取
|
Integer receiveNum, limitRecNum;
|
for(Map<String, Object> m : couponList){
|
m.put("isReceive", BaseEntity.YES);
|
receiveNum = m.get("receiveNum") != null ? new BigDecimal(m.get("receiveNum").toString()).intValue() : 0;
|
limitRecNum = m.get("limitRecNum") != null ? new BigDecimal(m.get("limitRecNum").toString()).intValue() : 0;
|
//判断用户对应优惠券领取数量是否超过活动优惠券限制次数
|
if(limitRecNum > 0 && receiveNum >= limitRecNum){
|
m.put("isReceive", BaseEntity.NO);
|
}
|
}
|
|
//根据groupId分组转换后面分组匹配
|
Map<String, List<Map<String, Object>>> couponListMap = couponList.stream().collect(Collectors.groupingBy(s->s.get("groupId").toString()));
|
//查询活动分组,然后遍历匹配分组的优惠券
|
sqlSentence.setSqlSentence(" select id, limitRctNum from market_activity_group where isDel = 0 and marketActivityId = #{m.marketActivityId} order by sortNum asc ");
|
List<Map<String, Object>> groupList = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
|
//查询用户对应活动分组领取过的优惠券种类数量
|
values.put("commonType", MarketActivityConstants.COMMON_TYPE_COUPON);
|
sql.setLength(0);
|
sql.append(" select count(DISTINCT i.commonId) ")
|
.append(" from market_activity_receive_record_item i ")
|
.append(" join market_activity_receive_record r on r.id = i.receiveRecordId ")
|
.append(" where i.isDel = 0 and r.userId = #{m.userId} and i.commonType = #{m.commonType} ")
|
.append(" and r.marketActivityId = #{m.marketActivityId} and i.groupId = #{m.groupId} ");
|
sqlSentence.setSqlSentence(sql.toString());
|
//遍历分组
|
for(Map<String, Object> groupMap : groupList){
|
groupMap.put("couponList", couponListMap.get(groupMap.get("id").toString()));
|
groupMap.put("rctNum", BaseEntity.NO);
|
if(user != null){
|
values.put("userId", user.getId());
|
values.put("groupId", groupMap.get("id"));
|
groupMap.put("rctNum", commonService.selectCountSql(sqlSentence));
|
}
|
}
|
|
//活动限制门店信息-----------------------------------------------------------
|
sql.setLength(0);
|
sql.append(" select lo.commonId, lo.commonName, lo.type ")
|
.append(" from limit_total lt ")
|
.append(" join limit_other lo on lo.limitTotalId = lt.id ")
|
.append(" where lt.isDel = 0 and lo.isDel = 0 and lt.foreignKey = #{m.marketActivityId} ");
|
sqlSentence.setSqlSentence(sql.toString());
|
List<Map<String, Object>> limitList = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
|
//过滤限制门店的信息
|
List<Map<String, Object>> limitShopList = limitList.stream().filter(s-> LimitOther.TYPE_SHOP.toString().equals(s.get("type").toString())).collect(Collectors.toList());
|
//过滤限制渠道的信息
|
// List<Map<String, Object>> limitUCList = limitList.stream().filter(s-> LimitOther.TYPE_CHANNEL.toString().equals(s.get("type").toString())).collect(Collectors.toList());
|
|
|
//------------------------------------------------------------------------
|
|
JSONObject data = new JSONObject();
|
//活动信息
|
data.put("title", marketActivity.getTitle());
|
data.put("ruleInfo", marketActivity.getRuleInfo());
|
data.put("startTime", DateUtil.formatDate_2(marketActivity.getStartTime()));
|
data.put("endTime", DateUtil.formatDate_2(marketActivity.getEndTime()));
|
data.put("joinNum", marketActivity.getJoinNum());
|
data.put("limitPeNum", marketActivity.getLimitPeNum());
|
data.put("managerName", marketActivity.getManagerName());
|
// data.put("limitRctNum", marketActivity.getLimitRctNum());
|
//用户信息
|
if(user != null){
|
data.put("userShopId", user.getShopId());
|
}
|
//活动轮播图
|
data.put("bannerList", bannerList);
|
//活动优惠分组
|
data.put("groupList", groupList);
|
//活动优惠券
|
// data.put("couponList", couponList);
|
//限制参与门店
|
data.put("limitShopList", limitShopList);
|
//用户是否参与过活动,默认0没有
|
data.put("isUserJoin", BaseEntity.NO);
|
//用户是否有查看记录
|
data.put("isView", BaseEntity.NO);
|
|
values.put("marketActivityId", marketActivity.getId());
|
//用户不为空则查询用户是否参与过活动
|
if(StringUtils.noNull(dto.getUserId())){
|
values.put("userId", dto.getUserId());
|
sqlSentence.setSqlSentence(" select id from market_activity_join_record where isDel = 0 and marketActivityId = #{m.marketActivityId} and userId = #{m.userId} ");
|
MarketActivityJoinRecord joinRecord = commonService.selectOne(MarketActivityJoinRecordMapper.class, sqlSentence);
|
if(joinRecord != null){
|
data.put("isUserJoin", BaseEntity.YES);
|
}
|
|
//查询是否有查看记录
|
sqlSentence.setSqlSentence(" select count(1) from market_activity_view_record vr where vr.isDel = 0 and vr.marketActivityId = #{m.marketActivityId} and vr.userId = #{m.userId} ");
|
int count = commonService.selectCountSql(sqlSentence);
|
data.put("isView", count > 0 ? BaseEntity.YES : BaseEntity.NO);
|
}
|
|
//查询总参与人数
|
sqlSentence.setSqlSentence(" select count(DISTINCT userId) from market_activity_join_record where isDel = 0 and marketActivityId = #{m.marketActivityId} ");
|
int totalJoinNum = commonService.selectCountSql(sqlSentence);
|
data.put("totalJoinNum", totalJoinNum);
|
|
// //更新查看记录(处理报错不抛出,避免影响流程)
|
// if(user != null){
|
// try{
|
// marketActivityService.updateViewRecord(marketActivity.getId(), dto.getPlatformType(), user);
|
// }catch (Exception e){
|
// log.error("营销活动更新查看记录失败:{}", GlobalExceptionHandler.getExceptionInformation(e));
|
// }
|
// }
|
|
return Result.success(data);
|
}
|
|
/** 确认已查看 */
|
@RequestMapping("/confirmView")
|
public Result confirmView(@RequestBody MarketActivityDto dto){
|
|
if(dto == null || StringUtils.isEmpty(dto.getId())){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "活动标识不能为空!");
|
}
|
|
if(StringUtils.isEmpty(dto.getUserId())){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "用户标识不能为空!");
|
}
|
|
MarketActivity marketActivity = commonService.selectOneByKey(MarketActivityMapper.class, dto.getId());
|
if(marketActivity == null){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到活动信息!");
|
}
|
|
User user = commonService.selectOneByKey(UserMapper.class, dto.getUserId());
|
if(user == null){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到用户信息!");
|
}
|
|
marketActivityService.updateViewRecord(marketActivity.getId(), dto.getPlatformType(), user);
|
|
return Result.success();
|
}
|
|
/** 领取优惠券 */
|
@PostMapping("/receiveCoupon")
|
public Result receiveCoupon(@RequestBody(required = false) MarketActivityDto dto){
|
|
log.info("营销活动领取优惠券参数:{}", JSONObject.toJSONString(dto));
|
|
//检查领取参数
|
MarketActivity marketActivity = checkReceiveParams(dto);
|
String errMsg = marketActivity.getErrMsg();
|
|
MarketActivityGroup group = commonService.selectOneByKey(MarketActivityGroupMapper.class, dto.getGroupId());
|
if(group == null){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到活动分组信息!");
|
}
|
|
EmployeeRole employeeRole = null;
|
if(dto.getOpType() == OperatorConstants.OP_TYPE_EMPLOYEE && StringUtils.noNull(dto.getOpRoleId())){
|
employeeRole = employeeRoleService.selectOneByKey(dto.getOpRoleId());
|
}
|
|
User user = commonService.selectOneByKey(UserMapper.class, dto.getUserId());
|
if(user == null){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到用户信息!");
|
}
|
//领取检查参与限制逻辑
|
receiveCheckJoinLimit(marketActivity, user, errMsg);
|
|
SqlSentence sqlSentence = new SqlSentence();
|
Map<String, Object> values = new HashMap<>();
|
sqlSentence.setM(values);
|
StringBuffer sql = new StringBuffer();
|
values.put("marketActivityId", marketActivity.getId());
|
|
//查询用户是否又参与记录
|
values.put("userId", dto.getUserId());
|
sqlSentence.setSqlSentence(" select * from market_activity_join_record where isDel = 0 and marketActivityId = #{m.marketActivityId} and userId = #{m.userId} ");
|
MarketActivityJoinRecord joinRecord = commonService.selectOne(MarketActivityJoinRecordMapper.class, sqlSentence);
|
|
//判断如果活动限制参与人数
|
if(marketActivity.getLimitPeNum() > 0){
|
//没有参与记录则判断活动总参与人数是否超过了限制数量
|
if(joinRecord == null){
|
sqlSentence.setSqlSentence(" select count(1) from market_activity_join_record where isDel = 0 and marketActivityId = #{m.marketActivityId} ");
|
int joinNum = commonService.selectCountSql(sqlSentence);
|
if(joinNum >= marketActivity.getLimitPeNum()){
|
throw new PlatTipsException(PlatformCode.ERROR_TIPS, "活动优惠券已领取完," + errMsg);
|
}
|
}
|
}
|
|
//查询活动领取的优惠券信息
|
sql.setLength(0);
|
values.put("groupId", group.getId());
|
values.put("commonType", MarketActivityConstants.COMMON_TYPE_COUPON);
|
sql.append(" select * from market_activity_item where isDel = 0 and marketActivityId = #{m.marketActivityId} and groupId = #{m.groupId} and commonType = #{m.commonType} ");
|
//单张优惠券领取则需要传这个值
|
if(StringUtils.noNull(dto.getActivityCouponId())){
|
values.put("id", dto.getActivityCouponId());
|
sql.append(" and id = #{m.id} ");
|
}
|
|
sqlSentence.setSqlSentence(sql.toString());
|
List<MarketActivityItem> list = commonService.selectList(MarketActivityItemMapper.class, sqlSentence);
|
if(list == null || list.size() < 1){
|
throw new PlatTipsException(PlatformCode.ERROR_TIPS, "查询不到活动优惠券信息!");
|
}
|
|
Date now = new Date();
|
List<MarketActivityItem> receiveList = new ArrayList<>();
|
//存储已领取完的优惠券名
|
List<String> cNameList = new ArrayList<>();
|
//是否全部领取
|
boolean isAll = StringUtils.isEmpty(dto.getActivityCouponId()) ? true : false;
|
//最小可领取间隔时长
|
int minInterval = 0;
|
|
//查询用户分组下领取过的优惠券种类数量
|
values.clear();
|
values.put("userId", dto.getUserId());
|
values.put("marketActivityId", marketActivity.getId());
|
values.put("groupId", group.getId());
|
values.put("commonType", MarketActivityConstants.COMMON_TYPE_COUPON);
|
sql.setLength(0);
|
sql.append(" select count(DISTINCT i.commonId) ")
|
.append(" from market_activity_receive_record_item i ")
|
.append(" join market_activity_receive_record r on r.id = i.receiveRecordId ")
|
.append(" where i.isDel = 0 and r.userId = #{m.userId} and i.commonType = #{m.commonType} ")
|
.append(" and r.marketActivityId = #{m.marketActivityId} and i.groupId = #{m.groupId} ");
|
sqlSentence.setSqlSentence(sql.toString());
|
int rctNum = commonService.selectCountSql(sqlSentence);
|
//记录是否有新的领药优惠券种类数量
|
int rctNewNum = 0;
|
|
//查询对应活动优惠券用户是否已领取(要根据优惠券id来,不可根据活动优惠券id来)
|
sql.setLength(0);
|
values.put("approveStatus", MarketActivityReceiveRecordItem.APPROVE_STATUS_WAIT);
|
sql.append(" select count(if(i.groupId = #{m.groupId}, 1, null)) as receiveNum ")
|
.append(" , count(if(i.approveStatus = #{m.approveStatus}, 1, null)) as waitApproveNum ")
|
.append(" , date_format(max(i.createTime), '%Y-%m-%d %H:%i:%s') as receiveTime ")
|
.append(" from market_activity_receive_record_item i ")
|
.append(" join market_activity_receive_record r on r.id = i.receiveRecordId ")
|
.append(" where i.isDel = 0 and r.userId = #{m.userId} and i.commonType = #{m.commonType} ")
|
.append(" and r.marketActivityId = #{m.marketActivityId} and i.activityItemId = #{m.activityItemId} ");
|
sqlSentence.setSqlSentence(sql.toString());
|
|
int receiveNum = 0; //领取数量
|
int diffInterval = 0; //相差间隔时长
|
int waitApproveNum = 0; //待审批数量
|
Date receiveTime = null;//最后领取时间
|
Map<String, Object> receiveMap;
|
Coupon coupon;
|
|
log.info("领取种类数量:{}", rctNum);
|
for(MarketActivityItem activityItem : list){
|
|
receiveNum = 0;
|
receiveTime = null;
|
|
values.put("activityItemId", activityItem.getId());
|
receiveMap = commonService.selectOneMap(MarketActivityMapper.class, sqlSentence);
|
if(receiveMap != null && receiveMap.size() > 0){
|
receiveNum = receiveMap.get("receiveNum") != null ? Integer.parseInt(receiveMap.get("receiveNum").toString()) : 0;
|
receiveTime = receiveMap.get("receiveTime") != null ? DateUtil.parseString_1(receiveMap.get("receiveTime").toString()) : null;
|
waitApproveNum = receiveMap.get("waitApproveNum") != null ? Integer.parseInt(receiveMap.get("waitApproveNum").toString()) : 0;
|
}
|
|
|
|
//如果领取数量为0,则领取种类数量+1
|
if(receiveNum == 0){
|
rctNewNum++;
|
rctNum ++;
|
}
|
|
//用户没有领取记录,判断活动是否限制了N选M,然后判断用户领取是否超过N选M设置数量
|
if(group.getLimitRctNum() > 0 && rctNum > group.getLimitRctNum()){
|
if(isAll){
|
continue;
|
}
|
throw new PlatTipsException(PlatformCode.ERROR_TIPS, "领取的优惠券种类已超过活动分组设置的数量,不可继续领取其他优惠券," + errMsg);
|
}
|
log.info("领取种类数量:{},{}", rctNum, rctNewNum);
|
|
|
//判断活动限制参与次数,且领取超过限制次数(原为活动joinNum字段判断,现在按优惠券设置字段来判断)
|
if(activityItem.getLimitRecNum() > 0 && receiveNum >= activityItem.getLimitRecNum()){
|
if(isAll){
|
continue;
|
}
|
throw new PlatTipsException(PlatformCode.ERROR_TIPS, "当前活动优惠券每人仅限领取"+activityItem.getLimitRecNum()+"次," + errMsg);
|
}
|
|
//判断活动是否限制了领取间隔
|
// log.info("receiveNum:{}", receiveNum);
|
// log.info("最后领取时间:{}", DateUtil.formatDate_2(receiveTime));
|
// log.info("限制领取间隔:{}", marketActivity.getRecInterval());
|
if(marketActivity.getRecInterval() > BaseEntity.NO && receiveTime != null){
|
//计算相差间隔时长 = 活动限制间隔时长 - 领取间隔时长
|
diffInterval = marketActivity.changeRecInterval() - differHour(receiveTime, now).intValue();
|
// log.info("相差间隔:{}", diffInterval);
|
if(diffInterval > 0){
|
if(isAll){
|
//赋值最小间隔时长
|
minInterval = minInterval == 0 ? diffInterval : diffInterval < minInterval ? diffInterval : minInterval;
|
continue;
|
}
|
throw new PlatTipsException(PlatformCode.ERROR_TIPS, "活动优惠券还需等待" + diffInterval + "小时才可继续领取!");
|
}
|
}
|
|
//查询优惠券信息,判断是否到了领取时间
|
coupon = commonService.selectOneByKey(CouponMapper.class, activityItem.getCommonId());
|
if(coupon == null){
|
throw new PlatTipsException(PlatformCode.ERROR_TIPS, "查询不到领取的优惠券信息!");
|
}
|
|
if(coupon.getIsDel() == BaseEntity.YES){
|
if(isAll){
|
continue;
|
}
|
throw new PlatTipsException(PlatformCode.ERROR_TIPS, "领取的优惠券已被删除," + errMsg);
|
}
|
|
if(coupon.getIsUp() == BaseEntity.NO){
|
if(isAll){
|
continue;
|
}
|
throw new PlatTipsException(PlatformCode.ERROR_TIPS, "领取的优惠券已下架,"+ errMsg);
|
}
|
|
if(coupon.getIssueStartTime() != null && now.compareTo(coupon.getIssueStartTime()) < 0){
|
if(isAll){
|
continue;
|
}
|
throw new PlatTipsException(PlatformCode.ERROR_TIPS, "活动优惠券还未到领取时间," + errMsg);
|
}
|
|
if(coupon.getIssueEndTime() != null && now.compareTo(coupon.getIssueEndTime()) > 0){
|
if(isAll){
|
continue;
|
}
|
throw new PlatTipsException(PlatformCode.ERROR_TIPS, "活动优惠券已过领取时间," + errMsg);
|
}
|
|
//判断待审批的不能领取
|
if(waitApproveNum > 0){
|
if(isAll){
|
throw new PlatTipsException(PlatformCode.ERROR_TIPS, "优惠券["+activityItem.getCommonName()+"]上次领取还未审批,不可全部领取," + errMsg);
|
}
|
throw new PlatTipsException(PlatformCode.ERROR_TIPS, "当前优惠券上次领取还未审批,不可继续领取," + errMsg);
|
}
|
|
//判断优惠券剩余数量是否小于等于0,存储名称后面抛错提示
|
if(couponSurplusNum(coupon) <= 0){
|
cNameList.add(coupon.getTitle());
|
}
|
|
receiveList.add(activityItem);
|
}
|
|
if(cNameList.size() > 0){
|
StringBuffer errSb = new StringBuffer();
|
errSb.append("活动爆满,优惠券【");
|
for(String name : cNameList){
|
errSb.append(name).append("、");
|
}
|
errSb.delete(errSb.length() - 1, errSb.length()).append("】已领取完,").append(errMsg);
|
throw new PlatTipsException(PlatformCode.ERROR_TIPS, errSb.toString());
|
}
|
|
if(receiveList.size() == 0){
|
if(isAll){
|
if(minInterval > 0){
|
throw new PlatTipsException(PlatformCode.ERROR_TIPS, "活动全部领取还需等待" + minInterval + "小时才可继续领取!");
|
}
|
throw new PlatTipsException(PlatformCode.ERROR_TIPS, "暂无可领取的优惠券," + errMsg);
|
}
|
// throw new PlatTipsException(PlatformCode.ERROR_TIPS, "活动每人仅限参与"+marketActivity.getJoinNum()+"次," + errMsg);
|
}
|
|
//处理参与记录逻辑
|
if(joinRecord == null){
|
joinRecord = new MarketActivityJoinRecord();
|
joinRecord.setDateStr(Integer.parseInt(DateUtil.formatDate(now)));
|
joinRecord.setMarketActivityId(marketActivity.getId());
|
joinRecord.setPlatformType(dto.getPlatformType());
|
//领取次数
|
joinRecord.setReceiveNum(1);
|
//用户信息
|
joinRecord.setUserId(user.getId());
|
joinRecord.setUserName(user.getName());
|
joinRecord.setCIQ(user.getCIQ());
|
joinRecord.setUserLevel(user.getUserLevel());
|
joinRecord.setUserStatus(user.getUserStatus());
|
joinRecord.setUserConsultantId(user.getHisCorpUserId());
|
joinRecord.setUserConsultantName(EmployeeTool.getCnName(joinRecord.getUserConsultantId(), commonService));
|
joinRecord.setUserShopId(user.getShopId());
|
joinRecord.setUserShopName(ShopTool.getShopName(joinRecord.getUserShopId(), commonService));
|
//通过用户创建日期
|
if(DateUtil.formatDate(user.getCreateTime()).equals(joinRecord.getDateStr())){
|
joinRecord.setIsNewUser(BaseEntity.YES);
|
}
|
}
|
|
//每次都新增领取记录
|
MarketActivityReceiveRecord receiveRecord = new MarketActivityReceiveRecord();
|
receiveRecord.setMarketActivityId(marketActivity.getId());
|
receiveRecord.setPlatformType(dto.getPlatformType());
|
//操作人
|
receiveRecord.setOpId(dto.getOpId());
|
receiveRecord.setOpName(dto.getOpName());
|
receiveRecord.setOpType(dto.getOpType());
|
if(employeeRole != null){
|
receiveRecord.setOpShopId(employeeRole.getShopId());
|
receiveRecord.setOpRoleId(employeeRole.getId());
|
receiveRecord.setOpRoleStr(employeeRole.getRoleUniqueStr());
|
}
|
//没有指定领取对应关联优惠券时,则是全部领取
|
receiveRecord.setIsAll(isAll ? 1 : 0);
|
//用户信息
|
receiveRecord.setUserId(user.getId());
|
receiveRecord.setUserName(user.getName());
|
receiveRecord.setCIQ(user.getCIQ());
|
receiveRecord.setUserLevel(user.getUserLevel());
|
receiveRecord.setUserStatus(user.getUserStatus());
|
receiveRecord.setUserConsultantId(user.getHisCorpUserId());
|
receiveRecord.setUserConsultantName(EmployeeTool.getCnName(receiveRecord.getUserConsultantId(), commonService));
|
receiveRecord.setUserShopId(user.getShopId());
|
receiveRecord.setUserShopName(ShopTool.getShopName(receiveRecord.getUserShopId(), commonService));
|
|
//累加领取优惠券数量
|
joinRecord.setCouponNum(joinRecord.getCouponNum() + receiveList.size());
|
|
synchronized (MarketActivityController.class){
|
marketActivityService.receiveCoupon(marketActivity, receiveList, user, joinRecord, receiveRecord);
|
}
|
|
return Result.success();
|
}
|
|
/** 领取审批回调 */
|
@RequestMapping("/receiveApproveCallback")
|
public Result receiveApproveCallback(@RequestBody MarCommonReturnDto returnDto){
|
log.info("营销活动领取审批回调:{}", JSONObject.toJSONString(returnDto));
|
|
if(StringUtils.isEmpty(returnDto.getData())){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "请求数据为空!");
|
}
|
|
MarketingReturnDto dto = JSONObject.parseObject(returnDto.getData(), MarketingReturnDto.class);
|
if(dto == null){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "返回结果数据为空!");
|
}
|
|
if(StringUtils.isEmpty(dto.getResult())){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "审批结果为空!");
|
}
|
|
if(StringUtils.isEmpty(dto.getUniqueId())){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "唯一值标识为空!");
|
}
|
|
MarketActivityReceiveRecordItem recordItem = commonService.selectOneByKey(MarketActivityReceiveRecordItemMapper.class, dto.getUniqueId());
|
if(recordItem == null){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到领取记录信息1!");
|
}
|
|
if(recordItem.getApproveStatus() != MarketActivityReceiveRecordItem.APPROVE_STATUS_WAIT){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "领取记录审批状态异常!");
|
}
|
|
if(MarketingReturnDto.AGREE.equals(dto.getResult())){
|
recordItem.setApproveStatus(MarketActivityReceiveRecordItem.APPROVE_STATUS_SUC);
|
}else if(MarketingReturnDto.REJECT.equals(dto.getResult())){
|
recordItem.setApproveStatus(MarketActivityReceiveRecordItem.APPROVE_STATUS_FAIL);
|
}else{
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "审批状态异常!");
|
}
|
recordItem.setApproveRemark(dto.getApplyRemarks());
|
|
MarketActivityReceiveRecord receiveRecord = commonService.selectOneByKey(MarketActivityReceiveRecordMapper.class, recordItem.getReceiveRecordId());
|
if(receiveRecord == null){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到领取记录信息2!");
|
}
|
|
MarketActivityJoinRecord joinRecord = commonService.selectOneByKey(MarketActivityJoinRecordMapper.class, receiveRecord.getJoinRecordId());
|
if(joinRecord == null){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到活动参与记录信息!");
|
}
|
|
marketActivityService.receiveApproveHandle(joinRecord, receiveRecord, recordItem);
|
|
return Result.success();
|
}
|
|
/**审批列表*/
|
@RequestMapping("/approve/list")
|
public Result pendingApproveCoupon(@RequestBody MarketActivityDto dto) {
|
|
log.info("营销活动获取待审核优惠券参数:{}", JSONObject.toJSONString(dto));
|
|
//检查
|
if(StringUtils.isEmpty(dto.getMarketActivityId())){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "营销活动标识为空!");
|
}
|
|
MarketActivity marketActivity = commonService.selectOneByKeyBlob(MarketActivityMapper.class,dto.getMarketActivityId());
|
if(marketActivity == null){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到营销活动信息!");
|
}
|
|
SqlSentence sqlSentence = new SqlSentence();
|
Map<String, Object> values = new HashMap<>();
|
sqlSentence.setM(values);
|
|
values.put("isDel", BaseEntity.NO);
|
values.put("commonType", MarketActivityConstants.COMMON_TYPE_COUPON);
|
values.put("marketActivityId", dto.getMarketActivityId());
|
|
StringBuffer sql = new StringBuffer();
|
sql.append(" SELECT ri.id as recordItemId,ri.approveStatus, c.id AS couponId, c.title AS couponName")
|
.append(" , c.type,c.platformType, mai.limitRecNum , ma.id as marketActivityId, mai.id as marketActivityItemId")
|
.append(" , date_format( c.issueStartTime, '%Y-%m-%d %H:%i:%s') as issueStartTime ")
|
.append(" , date_format( c.issueEndTime, '%Y-%m-%d %H:%i:%s') as issueEndTime ")
|
.append(" , CASE c.type WHEN 0 THEN c.discountNum ELSE c.discountAmount END AS couponPrice")
|
.append(" , rr.opName,rr.userName,rr.CIQ,ri.approveRemark as remark ")
|
.append(" FROM market_activity ma")
|
.append(" LEFT JOIN market_activity_item mai ON ma.id = mai.marketActivityId")
|
.append(" LEFT JOIN coupon c ON mai.commonId = c.id AND mai.commonType = #{m.commonType} ")
|
.append(" LEFT JOIN market_activity_receive_record_item ri on ri.activityItemId = mai.id ")
|
.append(" LEFT JOIN market_activity_receive_record rr on ri.receiveRecordId = rr.id ")
|
.append(" WHERE ma.isDel = #{m.isDel} AND ma.id = #{m.marketActivityId} ");
|
//审批状态查询
|
if (dto.getApprovalStatus()!= null) {
|
values.put("approveStatus", dto.getApprovalStatus());
|
sql.append(" AND ri.approveStatus = #{m.approveStatus}");
|
}else {
|
sql.append(" AND ri.approveStatus in (0,1,2,3)");
|
}
|
|
sql.append(" ORDER BY ri.createTime DESC ");
|
sqlSentence.setSqlSentence(sql.toString());
|
|
PageHelper.startPage(dto.getPageNum() == null ? 1 : dto.getPageNum(), dto.getPageSize() == null ? 10 : dto.getPageSize());
|
List<Map<String, Object>> list = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
|
PageInfo pageInfo = new PageInfo(list);
|
|
return Result.success(pageInfo);
|
|
}
|
|
/** 后台领取审批 */
|
@RequestMapping("/receive/approve/callback/admin")
|
public Result receiveApproveCallbackAdmin(@RequestBody MarketActivityDto dto){
|
|
log.info("营销活动审核操作传值参数:{}", JSONObject.toJSONString(dto));
|
|
if(StringUtils.isEmpty(dto.getRecordItemId())){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "标识为空!");
|
}
|
|
if(StringUtils.isEmpty(dto.getOpId())){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "操作人为空!");
|
}
|
|
if(StringUtils.isEmpty(dto.getStatusStr())){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "审核状态为空!");
|
}
|
|
MarketActivityReceiveRecordItem recordItem = commonService.selectOneByKeyBlob(MarketActivityReceiveRecordItemMapper.class, dto.getRecordItemId());
|
if(recordItem == null){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到领取记录信息!");
|
}
|
|
if(recordItem.getApproveStatus() != MarketActivityReceiveRecordItem.APPROVE_STATUS_WAIT){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "领取记录审批状态异常!");
|
}
|
|
if(MarketingReturnDto.AGREE.equals(dto.getStatusStr())){
|
recordItem.setApproveStatus(MarketActivityReceiveRecordItem.APPROVE_STATUS_SUC);
|
}else if(MarketingReturnDto.REJECT.equals(dto.getStatusStr())){
|
recordItem.setApproveStatus(MarketActivityReceiveRecordItem.APPROVE_STATUS_FAIL);
|
}else{
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "审批状态异常!");
|
}
|
recordItem.setApproveRemark(dto.getRemark());
|
MarketActivity marketActivity = commonService.selectOneByKeyBlob(MarketActivityMapper.class,recordItem.getMarketActivityId());
|
if(marketActivity == null){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到活动信息!");
|
}
|
|
if(!marketActivity.getManagerId().equals(dto.getOpId())){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "当前操作审批人与负责人不一致!");
|
}
|
|
MarketActivityReceiveRecord receiveRecord = commonService.selectOneByKey(MarketActivityReceiveRecordMapper.class, recordItem.getReceiveRecordId());
|
if(receiveRecord == null){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到领取记录信息!");
|
}
|
|
MarketActivityJoinRecord joinRecord = commonService.selectOneByKey(MarketActivityJoinRecordMapper.class, receiveRecord.getJoinRecordId());
|
if(joinRecord == null){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到活动参与记录信息!");
|
}
|
|
marketActivityService.receiveApproveHandle(joinRecord, receiveRecord, recordItem);
|
|
return Result.success();
|
}
|
|
///////////////////////////////////////////////////////////////////////////
|
|
/** 检查校验领取参数 */
|
private MarketActivity checkReceiveParams(MarketActivityDto dto){
|
if(dto == null){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "请求对象不能为空!");
|
}
|
|
if(StringUtils.isEmpty(dto.getMarketActivityId())){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "活动标识不能为空!");
|
}
|
|
if(StringUtils.isEmpty(dto.getGroupId())){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "活动分组标识不能为空!");
|
}
|
|
|
if(StringUtils.isEmpty(dto.getUserId())){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "领取用户不能为空!");
|
}
|
|
if(StringUtils.isEmpty(dto.getPlatformType())){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "平台类型不能为空!");
|
}
|
|
if(dto.getOpType() == null){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "操作人类型不能为空!");
|
}
|
|
if(StringUtils.isEmpty(dto.getOpId())){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "操作人标识不能为空!");
|
}
|
|
if(StringUtils.isEmpty(dto.getOpName())){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "操作人名称不能为空!");
|
}
|
|
MarketActivity marketActivity = commonService.selectOneByKey(MarketActivityMapper.class, dto.getMarketActivityId());
|
if(marketActivity == null){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到活动信息!");
|
}
|
|
String errMsg = "请联系活动负责人"+marketActivity.getManagerName()+"咨询情况";
|
marketActivity.setErrMsg(errMsg);
|
|
if(marketActivity.getIsUp() == BaseEntity.NO){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "活动已下架," + errMsg);
|
}
|
|
if(marketActivity.getTimeType() == MarketActivity.TIME_TYPE_APPOINT_TIME){
|
Date now = new Date();
|
if(now.compareTo(marketActivity.getStartTime()) < 0){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "活动还未开始," + errMsg);
|
}
|
if(now.compareTo(marketActivity.getEndTime()) > 0){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "活动已结束," + errMsg);
|
}
|
}
|
|
return marketActivity;
|
}
|
|
//获取优惠券剩余数量
|
public int couponSurplusNum(Coupon coupon){
|
// 查询已发送的数量
|
SqlSentence sqlSentence = new SqlSentence();
|
Map<String, Object> sqlValues = new HashMap<>();
|
sqlValues.put("isDel", BaseEntity.NO);
|
sqlValues.put("validState", BaseEntity.YES);
|
sqlValues.put("couponId", coupon.getId());
|
sqlSentence.sqlWhere(" couponId = #{m.couponId} AND validState = #{m.validState} AND isDel = #{m.isDel}", sqlValues);
|
int count = commonService.selectCount(CouponNumberMapper.class,sqlSentence);
|
if (coupon.getIssueNum() != null) {
|
return coupon.getIssueNum() - count;
|
} else {
|
return 0;
|
}
|
}
|
|
//查询用户渠道inSql
|
public String queryUserChannelInSql(User user){
|
StringBuffer channelInSql = new StringBuffer();
|
if(StringUtils.noNull(user.getChannelId())){
|
channelInSql.append("'").append(user.getChannelId()).append("',");
|
}
|
if(StringUtils.noNull(user.getChannel2Id())){
|
channelInSql.append("'").append(user.getChannel2Id()).append("',");
|
}
|
if(StringUtils.noNull(user.getChannelAssistId())){
|
channelInSql.append("'").append(user.getChannelAssistId()).append("',");
|
}
|
if(StringUtils.noNull(user.getChannelAssist2Id())){
|
channelInSql.append("'").append(user.getChannelAssist2Id()).append("',");
|
}
|
if(channelInSql.length() > 0){
|
channelInSql.delete(channelInSql.length()-1, channelInSql.length());
|
}
|
return channelInSql.toString();
|
}
|
|
//领取检查参与限制逻辑
|
public void receiveCheckJoinLimit(MarketActivity marketActivity, User user, String errMsg){
|
|
//判断用户会员等级是否符合限制--------------------------------------------------
|
if(StringUtils.noNull(marketActivity.getLimitUserLevel())){
|
if(StringUtils.isEmpty(user.getUserLevel())
|
|| marketActivity.getLimitUserLevel().indexOf(user.getUserLevel()) == -1){
|
throw new PlatTipsException(PlatformCode.ERROR_TIPS, "用户会员等级不在活动范围内," + errMsg);
|
}
|
}
|
|
SqlSentence sqlSentence = new SqlSentence();
|
Map<String, Object> values = new HashMap<>();
|
sqlSentence.setM(values);
|
StringBuffer sql = new StringBuffer();
|
values.put("marketActivityId", marketActivity.getId());
|
|
//查询活动限制总表限制信息------------------------------------------------------
|
sql.append(" select lo.commonId, lo.commonName, lo.type ")
|
.append(" from limit_total lt ")
|
.append(" join limit_other lo on lo.limitTotalId = lt.id ")
|
.append(" where lt.isDel = 0 and lo.isDel = 0 and lt.foreignKey = #{m.marketActivityId} ");
|
sqlSentence.setSqlSentence(sql.toString());
|
List<Map<String, Object>> limitList = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
|
|
//过滤限制门店的信息判断用户是否符合限制门店
|
List<Map<String, Object>> limitShopList = limitList.stream().filter(s-> LimitOther.TYPE_SHOP.toString().equals(s.get("type").toString())).collect(Collectors.toList());
|
if(limitShopList != null && limitShopList.size() > 0){
|
boolean canReceive = false;
|
for(Map<String, Object> m : limitShopList){
|
if(m.get("commonId").toString().equals(user.getShopId())){
|
canReceive = true;
|
break;
|
}
|
}
|
if(!canReceive){
|
throw new PlatTipsException(PlatformCode.ERROR_TIPS, "用户所属门店不在活动范围内," + errMsg);
|
}
|
}
|
|
//过滤限制渠道的信息判断用户是否符合限制渠道---------------------------------------------
|
List<Map<String, Object>> limitUcList = limitList.stream().filter(s-> LimitOther.TYPE_CHANNEL.toString().equals(s.get("type").toString())).collect(Collectors.toList());
|
if(limitUcList != null && limitUcList.size() > 0){
|
boolean canReceive = false;
|
//用户渠道id
|
String userChannelIds = queryUserChannelInSql(user);
|
for(Map<String, Object> m : limitUcList){
|
//用户渠道包含的就算
|
if(userChannelIds.indexOf(m.get("commonId").toString()) != -1){
|
canReceive = true;
|
break;
|
}
|
}
|
if(!canReceive){
|
throw new PlatTipsException(PlatformCode.ERROR_TIPS, "用户所属渠道不在活动范围内," + errMsg);
|
}
|
}
|
|
//执行或消费限制判断----------------------------------------------------------
|
if(marketActivity.getLimitEcNum() > 0){
|
//查询出限制条件
|
sqlSentence.setSqlSentence(" select * from market_activity_limit_ec where isDel = 0 and marketActivityId = #{m.marketActivityId} order by moduleNo asc ");
|
List<MarketActivityLimitEc> limitEcList = commonService.selectList(MarketActivityLimitEcMapper.class, sqlSentence);
|
if(limitEcList != null && limitEcList.size() > 0)
|
{
|
|
//查询用户项目执行次数sql(已执行、汇总执行次数)
|
String executeSql = "select ifnull( sum(dp.num), 0) from deduction_project dp join deduction_single ds on ds.id = dp.deductionSingleId where ds.isDel = 0 and dp.isDel = 0 and ds.status = #{m.status} and ds.userId = #{m.userId} and dp.projectId = #{m.commonId} and ds.createTime >= #{m.dateTime} ";
|
//查询用户消费次数sql(已支付、汇总时购买数量-已退款数量)
|
String consumeSql = "select ifnull( sum(oi.buyNum - oi.hasReNum), 0) from order_item oi join orders_total ot on ot.id = oi.orderId where ot.isDel = 0 and oi.isDel = 0 and ot.payStatus = #{m.payStatus} and ot.userId = #{m.userId} and oi.commonId = #{m.commonId} and ot.payTime >= #{m.dateTime} ";
|
|
//按模块编号过滤分组数据
|
Map<Integer, List<MarketActivityLimitEc>> ecMap = limitEcList.stream().collect(Collectors.groupingBy(MarketActivityLimitEc::getModuleNo));
|
log.info("限制消费模块数据:{}", JSONObject.toJSONString(ecMap));
|
//最终是否符合
|
boolean isConform = false;
|
//遍历是否满足模块所有条件
|
boolean isOk = false;
|
//遍历
|
for(Map.Entry<Integer, List<MarketActivityLimitEc>> entry : ecMap.entrySet())
|
{
|
//按模块遍历,默认是满足,下面遍历如果有条件不符合,就是false
|
isOk = true;
|
values.put("userId", user.getId());
|
|
//遍历模块下的限制条件
|
for(MarketActivityLimitEc limitEc : entry.getValue())
|
{
|
if(limitEc.getActionType() == MarketActivityLimitEc.ACTION_TYPE_EXECUTE){
|
//执行-项目
|
values.put("status", DeductionSingleConstants.STATUS_DONE_EXECUTE);
|
sqlSentence.setSqlSentence(executeSql);
|
}else if(limitEc.getActionType() == MarketActivityLimitEc.ACTION_TYPE_CONSUME){
|
//消费-项目、促销、卡项
|
values.put("payStatus", OrderTotalConstants.PAY_STATUS_SUC);
|
sqlSentence.setSqlSentence(consumeSql);
|
}else{
|
//没有对应类型,直接不满足跳出循环
|
isOk = false;
|
break;
|
}
|
|
//根据时间单位+时间范围数值换算出有效日期
|
values.put("dateTime", limitEc.convertDateTime());
|
values.put("commonId", limitEc.getCommonId());
|
|
//判断如果用户不满足限制数量,直接跳出循环,用户不满足模块限制
|
if(commonService.selectCountSql(sqlSentence) < limitEc.getNum()){
|
isOk = false;
|
break;
|
}
|
}
|
|
//其中一个满足,直接跳出循环,然后标记为符合领取
|
if(isOk){
|
isConform = true;
|
break;
|
}
|
}
|
//全部遍历完成后,如果不符合则提示不能领取
|
if(!isConform){
|
throw new PlatTipsException(PlatformCode.ERROR_TIPS, "用户不满足执行或消费条件限制无法领取," + errMsg);
|
}
|
}
|
}
|
|
//END--------------------------------------------------------------
|
}
|
|
//间隔时长
|
public static Long differHour(Date startTime, Date endTime) {
|
if(startTime == null || endTime == null){
|
return 0L;
|
}
|
long sTime = startTime.getTime();
|
long eTime = endTime.getTime();
|
return (eTime - sTime) / 1000L / 60L / 60L;
|
}
|
|
/** 处理列表条件查询sql */
|
public void handleListConditionQuerysSql(MarketActivityDto dto, StringBuffer sql, Map<String, Object> values){
|
|
if (!StringUtils.isEmpty(dto.getKeyWord())) {
|
sql.append(" and a.title like #{m.keyWord} ");
|
values.put("keyWord", "%" + dto.getKeyWord() + "%");
|
}
|
|
if(dto.getIsUp() != null){
|
sql.append(" and a.isUp = #{m.isUp} ");
|
values.put("isUp", dto.getIsUp());
|
}
|
|
if(dto.getIsCoupon() != null){
|
if(dto.getIsCoupon() == BaseEntity.NO){
|
sql.append(" and a.couponNum = 0 ");
|
}else{
|
sql.append(" and a.couponNum > 0 ");
|
}
|
}
|
|
if (!StringUtils.isEmpty(dto.getClassifyId())) {
|
sql.append(" and a.classifyId = #{m.classifyId} ");
|
values.put("classifyId", dto.getClassifyId());
|
}
|
|
if (!StringUtils.isEmpty(dto.getStartTime())) {
|
sql.append(" and a.startTime >= date_format(#{m.startTime}, '%Y-%m-%d %00:%00:%00') ");
|
values.put("startTime", dto.getStartTime());
|
}
|
|
if (!StringUtils.isEmpty(dto.getEndTime())) {
|
sql.append(" and a.endTime <= date_format(#{m.endTime}, '%Y-%m-%d %23:%59:%59') ");
|
values.put("endTime", dto.getEndTime());
|
}
|
|
if(StringUtils.noNull(dto.getShopIds())){
|
//遍历拼接门店in查询sql
|
String [] shopArr = dto.getShopIds().split(",");
|
StringBuffer shopInSql = new StringBuffer();
|
for(String shopId : shopArr){
|
shopInSql.append("'").append(shopId).append("',");
|
}
|
shopInSql.delete(shopInSql.length() - 1, shopInSql.length());
|
|
//对应子查询限制总表符合的活动id,再in查询对应符合的
|
values.put("ltType", LimitTotal.LIMIT_MARKET_ACTIVITY);
|
values.put("loType", LimitOther.TYPE_SHOP);
|
sql.append(" and ( ")
|
.append(" a.id in ( ")
|
.append(" select lt.foreignKey from limit_total lt ")
|
.append(" join limit_other lo on lo.limitTotalId = lt.id and lo.isDel = 0 ")
|
.append(" where lt.isDel = 0 and lt.type = #{m.ltType} and lo.type = #{m.loType} ")
|
.append(" and lo.commonId in (").append(shopInSql).append(") group by lt.foreignKey ")
|
.append(" ) ")
|
.append(" or a.isLimitShop = 0 ) ");
|
}
|
|
//如果用户id不为空,处理限制用户逻辑
|
if(StringUtils.noNull(dto.getUserId())){
|
User user = commonService.selectOneByKey(UserMapper.class, dto.getUserId());
|
if(user == null){
|
throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到用户信息!");
|
}
|
|
//查询符合用户会员等级的活动
|
values.put("userLevel", user.getUserLevel());
|
sql.append(" and ( limitUserLevel is null or ( #{m.userLevel} is not null and #{m.userLevel} != '' and LOCATE( #{m.userLevel}, limitUserLevel) > 0) ) ");
|
|
//对应子查询限制总表符合用户渠道的活动id,再in查询对应符合的
|
String channelInSql = queryUserChannelInSql(user);
|
sql.append(" and ( a.isLimitUC = 0 ");
|
if(StringUtils.noNull(channelInSql)){
|
values.put("ltType2", LimitTotal.LIMIT_MARKET_ACTIVITY);
|
values.put("loType2", LimitOther.TYPE_CHANNEL);
|
sql.append(" or a.id in ( ")
|
.append(" select lt.foreignKey from limit_total lt ")
|
.append(" join limit_other lo on lo.limitTotalId = lt.id and lo.isDel = 0 ")
|
.append(" where lt.isDel = 0 and lt.type = #{m.ltType2} and lo.type = #{m.loType2} ")
|
.append(" and lo.commonId in (").append(channelInSql).append(") group by lt.foreignKey ")
|
.append(" ) ");
|
}
|
sql.append(" ) ");
|
}
|
}
|
|
public static void main(String args[]){
|
// Date startTime = DateUtil.parseString_1("2023-08-21 16:00:00");
|
// Date endTime = new Date();
|
// System.out.println(differHour(startTime, endTime));
|
|
// List<MarketActivityLimitEc> limitEcList = new ArrayList<>();
|
// limitEcList.add(new MarketActivityLimitEc(1, "1001"));
|
// limitEcList.add(new MarketActivityLimitEc(1, "1002"));
|
// limitEcList.add(new MarketActivityLimitEc(1, "1003"));
|
//
|
// limitEcList.add(new MarketActivityLimitEc(2, "2001"));
|
// limitEcList.add(new MarketActivityLimitEc(2, "2002"));
|
//
|
// limitEcList.add(new MarketActivityLimitEc(3, "3001"));
|
//
|
// Map<Integer, List<MarketActivityLimitEc>> ecMap =limitEcList.stream().collect(Collectors.groupingBy(MarketActivityLimitEc::getModuleNo));
|
// System.out.println(ecMap.entrySet());
|
|
List<Map<String, Object>> list = new ArrayList<>();
|
Map<String, Object> map = new HashMap<>();
|
map.put("id", "1");
|
list.add(map);
|
|
|
map = new HashMap<>();
|
map.put("id", "2");
|
list.add(map);
|
map = new HashMap<>();
|
map.put("id", "2");
|
list.add(map);
|
|
map = new HashMap<>();
|
map.put("id", "3");
|
list.add(map);
|
map = new HashMap<>();
|
map.put("id", "3");
|
list.add(map);
|
map = new HashMap<>();
|
map.put("id", "3");
|
list.add(map);
|
|
Map<String, Long> map2 = list.stream().filter(s->s.get("id1") != null).collect(Collectors.groupingBy(s->s.get("id1").toString(), Collectors.counting()));
|
System.out.println(map2.entrySet());
|
|
}
|
}
|