rx
2023-12-13 923fa13e40ca7c38bb9560c0d0c37f2787b0b548
提交 | 用户 | age
a2688a 1 package com.hx.phip.controller.market;
F 2
3 import com.alibaba.fastjson.JSONObject;
4 import com.github.pagehelper.PageHelper;
5 import com.github.pagehelper.PageInfo;
6 import com.hx.common.BaseController;
7 import com.hx.exception.TipsException;
8 import com.hx.mybatisTool.SqlSentence;
f931ff 9 import com.hx.phiappt.common.*;
a2688a 10 import com.hx.phiappt.constants.tool.employee.EmployeeTool;
F 11 import com.hx.phiappt.constants.tool.shop.ShopTool;
12 import com.hx.phiappt.dao.mapper.*;
13 import com.hx.phiappt.model.BaseEntity;
14 import com.hx.phiappt.model.EmployeeRole;
15 import com.hx.phiappt.model.User;
16 import com.hx.phiappt.model.coupon.Coupon;
7111ca 17 import com.hx.phiappt.model.limit.LimitOther;
a2688a 18 import com.hx.phiappt.model.limit.LimitTotal;
074aee 19 import com.hx.phiappt.model.market.*;
a2688a 20 import com.hx.phip.service.EmployeeRoleService;
F 21 import com.hx.phip.service.market.MarketActivityService;
22 import com.hx.resultTool.Result;
23 import com.hx.util.DateUtil;
24 import com.hx.util.StringUtils;
ec5116 25 import com.hz.his.dto.marketing.MarketActivityDto;
026734 26 import com.hz.his.dto.marketing.common.MarCommonReturnDto;
F 27 import com.hz.his.dto.marketing.common.MarketingReturnDto;
a2688a 28 import com.platform.exception.PlatTipsException;
F 29 import com.platform.resultTool.PlatformCode;
30 import lombok.extern.slf4j.Slf4j;
31 import org.springframework.web.bind.annotation.PostMapping;
32 import org.springframework.web.bind.annotation.RequestBody;
33 import org.springframework.web.bind.annotation.RequestMapping;
34 import org.springframework.web.bind.annotation.RestController;
35
36 import javax.annotation.Resource;
37 import java.math.BigDecimal;
38 import java.util.*;
7111ca 39 import java.util.stream.Collectors;
a2688a 40
F 41 /**
42  * 营销活动(热门活动)
43  * @USER: fhx
44  * @DATE: 2023/7/3
45  **/
46 @Slf4j
47 @RestController
ec5116 48 @RequestMapping("/market/activity")
a2688a 49 public class MarketActivityController extends BaseController {
F 50
51     @Resource
52     private MarketActivityService marketActivityService;
53     @Resource
54     private EmployeeRoleService employeeRoleService;
55
56     /** 列表 */
57     @PostMapping("/list")
58     public Result list(@RequestBody(required = false) MarketActivityDto dto) {
59
60         if(dto == null){
61             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "请求对象为空!");
62         }
63
64         SqlSentence sqlSentence = new SqlSentence();
65         Map<String, Object> values = new HashMap<>();
66         sqlSentence.setM(values);
67
68         StringBuffer sql = new StringBuffer();
f931ff 69         sql.append(" select a.id, a.title, a.intro, a.managerName, a.isUp, a.couponNum, a.isLimitShop  ")
a2688a 70                 .append(" , date_format(a.startTime, '%Y/%m/%d') as startTime ")
f931ff 71                 .append(" , date_format(a.endTime, '%Y/%m/%d %H:%i:%s') as endTime ");
a2688a 72                 //子查询第一张轮播图
f931ff 73 //              .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 ")
F 74         //用户领取
7111ca 75         if(StringUtils.noNull(dto.getUserId())){
f931ff 76             values.put("userId", dto.getUserId());
F 77             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 ");
78         }else{
79             sql.append(" , 0 as receiveNum ");
a2688a 80         }
f931ff 81
F 82         sql.append(" from market_activity a where a.isDel = 0  ");
83
84         //处理列表条件查询sql
85         handleListConditionQuerysSql(dto, sql, values);
a2688a 86
F 87         sql.append(" order by a.createTime desc ");
88         sqlSentence.setSqlSentence(sql.toString());
89
90         PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
91         List<Map<String, Object>> list = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
92         PageInfo pageInfo = new PageInfo(list);
93
94         return Result.success(pageInfo);
95     }
f931ff 96
F 97     /** 分类tab列表 */
98     @RequestMapping("/tabData")
99     public Result tabData(@RequestBody MarketActivityDto dto){
100
101         //查询活动分类
102         SqlSentence sqlSentence = new SqlSentence();
103         Map<String, Object> values = new HashMap<>();
104         sqlSentence.setM(values);
105         values.put("type", BaseClassifyConstants.TYPE_MARKET_ACTIVITY);
106         sqlSentence.setSqlSentence(" select id, name, 0 as num from base_classify where isDel = 0 and type = #{m.type} order by sortNo asc ");
107         List<Map<String, Object>> list = commonService.selectListMap(BaseClassifyMapper.class, sqlSentence);
108
109         StringBuffer sql = new StringBuffer();
110         sql.append(" select a.id, a.classifyId from market_activity a where a.isDel = 0  ");
111         //处理列表条件查询sql
112         handleListConditionQuerysSql(dto, sql, values);
113         sqlSentence.setSqlSentence(sql.toString());
114         List<Map<String, Object>> activityList = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
115
116         if(activityList != null && activityList.size() > 0){
117             //按分类id分组计算
118             Map<String, Long> countMap = activityList.stream().collect(Collectors.groupingBy(s->s.get("classifyId").toString(), Collectors.counting()));
119             //遍历赋值对应数量
120             for(Map<String, Object> m : list){
121                 if(countMap.containsKey(m.get("id").toString())){
122                     m.put("num", countMap.get(m.get("id").toString()));
123                 }
124             }
125         }
126
127         JSONObject data = new JSONObject();
128         data.put("list", list);
129         data.put("allNum", activityList.size());
130         return Result.success(data);
131     }
132
133     /** 顶部轮播图数据 */
134     @RequestMapping("/topBannerData")
135     public Result topBannerData(@RequestBody MarketActivityDto dto){
136
137         //用户为空直接返回空数据
138         if(StringUtils.isEmpty(dto.getUserId())){
139             return Result.success();
140         }
141
142         SqlSentence sqlSentence = new SqlSentence();
143         Map<String, Object> values = new HashMap<>();
144         sqlSentence.setM(values);
145         StringBuffer sql = new StringBuffer();
146         sql.append(" select a.id, bc.name as classifyName, a.title, a.intro ")
147                 .append(" , date_format(a.startTime, '%Y.%m.%d') as startTime ")
148                 .append(" , date_format(a.endTime, '%Y.%m.%d') as endTime ")
149                 .append(" from market_activity a  ")
150                 .append(" left join base_classify bc on bc.id = a.classifyId ")
151                 .append(" where a.isDel = 0 ");
152
153         //设置只查询上架的
154         dto.setIsUp(BaseEntity.YES);
155         //处理列表条件查询sql
156         handleListConditionQuerysSql(dto, sql, values);
157         //查询用户未查看过的活动
158         values.put("userId", dto.getUserId());
159         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 ");
160         sql.append(" order by a.createTime desc ");
161         sqlSentence.setSqlSentence(sql.toString());
162         List<Map<String, Object>> list = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
163
164         JSONObject data = new JSONObject();
165         data.put("list", list);
166         return Result.success(data);
167     }
168
a2688a 169     /** 详情 */
F 170     @PostMapping("/detail")
171     public Result detail(@RequestBody(required = false) MarketActivityDto dto){
172
173         if(dto == null || StringUtils.isEmpty(dto.getId())){
174             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询标识不能为空!");
175         }
176
177         MarketActivity marketActivity = commonService.selectOneByKey(MarketActivityMapper.class, dto.getId());
178         if(marketActivity == null){
179             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到活动信息!");
180         }
181
182         User user = null;
183         if(StringUtils.noNull(dto.getUserId())){
184             user = commonService.selectOneByKey(UserMapper.class, dto.getUserId());
185         }
186
187         SqlSentence sqlSentence = new SqlSentence();
188         Map<String, Object> values = new HashMap<>();
189         sqlSentence.setM(values);
190         values.put("marketActivityId", marketActivity.getId());
191         StringBuffer sql = new StringBuffer();
192
193         //营销活动关联轮播图--------------------------------------------------
194         sqlSentence.setSqlSentence(" select imgUrl from market_activity_banner where isDel = 0 and marketActivityId = #{m.marketActivityId} order by sortNo asc ");
195         List<Map<String, Object>> bannerList = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
196
197         //营销活动关联优惠券--------------------------------------------------
198         //查询用户优惠券码判断用户是否已领取过
199         String receiveNumSql = " 0 as receiveNum ";
70497c 200         //查询用户对应优惠券是否有待审核数量
F 201         String waitApproveSql = " 0 as waitApproveNum ";
a2688a 202
F 203         if(StringUtils.noNull(dto.getUserId())){
204             values.put("userId", dto.getUserId());
f931ff 205 //            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 ";
F 206             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 ";
70497c 207             //是否有待审核数量
43563a 208 //            values.put("approveStatus", MarketActivityReceiveRecordItem.APPROVE_STATUS_WAIT);
70497c 209             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 ";
a2688a 210         }
F 211
212         sql.setLength(0);
213         values.put("commonType", MarketActivityConstants.COMMON_TYPE_COUPON);
733bd8 214         sql.append(" select ai.marketActivityId, ai.id as activityCouponId, ai.commonId as couponId")
F 215                 .append(" , ai.limitRecNum, ai.groupId, ai.isApprove  ")
a2688a 216                 .append(" , c.title, c.type, c.discountAmount, c.discountNum ")
F 217                 .append(" , c.conditionType, c.amountSatisfied, c.platformType, c.issueType ")
218                 .append(" , c.useProjectType, c.useGoodsType, c.usePromotionType, c.useCardType ")
219                 .append(" , date_format(c.issueStartTime, '%Y-%m-%d %H:%i:%s') as issueStartTime ")
220                 .append(" , date_format(c.issueEndTime, '%Y-%m-%d %H:%i:%s') as issueEndTime ")
221                 .append(" , date_format(c.startTime, '%Y-%m-%d %H:%i:%s') as startTime ")
222                 .append(" , date_format(c.endTime, '%Y-%m-%d %H:%i:%s') as endTime ")
223                 .append(" , ").append(receiveNumSql)
70497c 224                 .append(" , ").append(waitApproveSql)
a2688a 225                 .append(" from market_activity_item ai  ")
F 226                 .append(" left join coupon c on c.id = ai.commonId ")
227                 .append(" where ai.isDel = 0 and ai.marketActivityId = #{m.marketActivityId} ")
228                 .append(" and ai.commonType = #{m.commonType} ");
229         sqlSentence.setSqlSentence(sql.toString());
230         List<Map<String, Object>> couponList = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
f931ff 231         //遍历判断用户是可领取
366d7c 232         Integer receiveNum, limitRecNum;
a2688a 233         for(Map<String, Object> m : couponList){
F 234             m.put("isReceive", BaseEntity.YES);
5f5875 235             receiveNum = m.get("receiveNum") != null ? new BigDecimal(m.get("receiveNum").toString()).intValue() : 0;
366d7c 236             limitRecNum = m.get("limitRecNum") != null ? new BigDecimal(m.get("limitRecNum").toString()).intValue() : 0;
F 237             //判断用户对应优惠券领取数量是否超过活动优惠券限制次数
238             if(limitRecNum > 0 && receiveNum >= limitRecNum){
a2688a 239                 m.put("isReceive", BaseEntity.NO);
F 240             }
f931ff 241         }
F 242
243         //根据groupId分组转换后面分组匹配
244         Map<String, List<Map<String, Object>>> couponListMap = couponList.stream().collect(Collectors.groupingBy(s->s.get("groupId").toString()));
245         //查询活动分组,然后遍历匹配分组的优惠券
246         sqlSentence.setSqlSentence(" select id, limitRctNum from market_activity_group where isDel = 0 and marketActivityId = #{m.marketActivityId} order by sortNum asc ");
247         List<Map<String, Object>> groupList = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
df358d 248         //查询用户对应活动分组领取过的优惠券种类数量
F 249         values.put("commonType", MarketActivityConstants.COMMON_TYPE_COUPON);
250         sql.setLength(0);
251         sql.append(" select count(DISTINCT i.commonId) ")
252                 .append(" from market_activity_receive_record_item i ")
edffd3 253                 .append(" join market_activity_receive_record r on r.id = i.receiveRecordId ")
df358d 254                 .append(" where i.isDel = 0 and r.userId = #{m.userId} and i.commonType = #{m.commonType} ")
F 255                 .append(" and r.marketActivityId = #{m.marketActivityId} and i.groupId = #{m.groupId} ");
256         sqlSentence.setSqlSentence(sql.toString());
257         //遍历分组
f931ff 258         for(Map<String, Object> groupMap : groupList){
F 259             groupMap.put("couponList", couponListMap.get(groupMap.get("id").toString()));
df358d 260             groupMap.put("rctNum", BaseEntity.NO);
F 261             if(user != null){
262                 values.put("userId", user.getId());
263                 values.put("groupId", groupMap.get("id"));
264                 groupMap.put("rctNum", commonService.selectCountSql(sqlSentence));
265             }
a2688a 266         }
F 267
268         //活动限制门店信息-----------------------------------------------------------
269         sql.setLength(0);
33db03 270         sql.append(" select lo.commonId, lo.commonName, lo.type ")
a2688a 271                 .append(" from limit_total lt  ")
e7c1e6 272                 .append(" join limit_other lo on lo.limitTotalId = lt.id  ")
a2688a 273                 .append(" where lt.isDel = 0 and lo.isDel = 0 and lt.foreignKey = #{m.marketActivityId} ");
F 274         sqlSentence.setSqlSentence(sql.toString());
33db03 275         List<Map<String, Object>> limitList = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
F 276         //过滤限制门店的信息
277         List<Map<String, Object>> limitShopList = limitList.stream().filter(s-> LimitOther.TYPE_SHOP.toString().equals(s.get("type").toString())).collect(Collectors.toList());
278         //过滤限制渠道的信息
acbf34 279 //        List<Map<String, Object>> limitUCList = limitList.stream().filter(s-> LimitOther.TYPE_CHANNEL.toString().equals(s.get("type").toString())).collect(Collectors.toList());
a2688a 280
F 281
282         //------------------------------------------------------------------------
283
284         JSONObject data = new JSONObject();
285         //活动信息
1009d6 286         data.put("title", marketActivity.getTitle());
a2688a 287         data.put("ruleInfo", marketActivity.getRuleInfo());
F 288         data.put("startTime", DateUtil.formatDate_2(marketActivity.getStartTime()));
289         data.put("endTime", DateUtil.formatDate_2(marketActivity.getEndTime()));
290         data.put("joinNum", marketActivity.getJoinNum());
291         data.put("limitPeNum", marketActivity.getLimitPeNum());
292         data.put("managerName", marketActivity.getManagerName());
f931ff 293 //        data.put("limitRctNum", marketActivity.getLimitRctNum());
a2688a 294         //用户信息
F 295         if(user != null){
296             data.put("userShopId", user.getShopId());
297         }
298         //活动轮播图
299         data.put("bannerList", bannerList);
f931ff 300         //活动优惠分组
F 301         data.put("groupList", groupList);
a2688a 302         //活动优惠券
70497c 303 //        data.put("couponList", couponList);
a2688a 304         //限制参与门店
F 305         data.put("limitShopList", limitShopList);
306         //用户是否参与过活动,默认0没有
307         data.put("isUserJoin", BaseEntity.NO);
733bd8 308         //用户是否有查看记录
1b7576 309         data.put("isView", BaseEntity.NO);
a2688a 310
F 311         values.put("marketActivityId", marketActivity.getId());
312         //用户不为空则查询用户是否参与过活动
313         if(StringUtils.noNull(dto.getUserId())){
314             values.put("userId", dto.getUserId());
733bd8 315             sqlSentence.setSqlSentence(" select id from market_activity_join_record where isDel = 0 and marketActivityId = #{m.marketActivityId} and userId = #{m.userId} ");
acbf34 316             MarketActivityJoinRecord joinRecord = commonService.selectOne(MarketActivityJoinRecordMapper.class, sqlSentence);
F 317             if(joinRecord != null){
a2688a 318                 data.put("isUserJoin", BaseEntity.YES);
F 319             }
1b7576 320
F 321             //查询是否有查看记录
322             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} ");
323             int count = commonService.selectCountSql(sqlSentence);
324             data.put("isView", count > 0 ? BaseEntity.YES : BaseEntity.NO);
a2688a 325         }
F 326
327         //查询总参与人数
328         sqlSentence.setSqlSentence(" select count(DISTINCT userId) from market_activity_join_record where isDel = 0 and marketActivityId = #{m.marketActivityId} ");
329         int totalJoinNum = commonService.selectCountSql(sqlSentence);
330         data.put("totalJoinNum", totalJoinNum);
f931ff 331
be4795 332 //        //更新查看记录(处理报错不抛出,避免影响流程)
F 333 //        if(user != null){
334 //            try{
335 //                marketActivityService.updateViewRecord(marketActivity.getId(), dto.getPlatformType(), user);
336 //            }catch (Exception e){
337 //                log.error("营销活动更新查看记录失败:{}", GlobalExceptionHandler.getExceptionInformation(e));
338 //            }
339 //        }
a2688a 340
F 341         return Result.success(data);
342     }
343
be4795 344     /** 确认已查看 */
F 345     @RequestMapping("/confirmView")
346     public Result confirmView(@RequestBody MarketActivityDto dto){
347
348         if(dto == null || StringUtils.isEmpty(dto.getId())){
349             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "活动标识不能为空!");
350         }
351
352         if(StringUtils.isEmpty(dto.getUserId())){
353             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "用户标识不能为空!");
354         }
355
356         MarketActivity marketActivity = commonService.selectOneByKey(MarketActivityMapper.class, dto.getId());
357         if(marketActivity == null){
358             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到活动信息!");
359         }
360
361         User user =  commonService.selectOneByKey(UserMapper.class, dto.getUserId());
362         if(user == null){
363             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到用户信息!");
364         }
365
366         marketActivityService.updateViewRecord(marketActivity.getId(), dto.getPlatformType(), user);
367
368         return Result.success();
369     }
370
a2688a 371     /** 领取优惠券 */
F 372     @PostMapping("/receiveCoupon")
733bd8 373     public Result receiveCoupon(@RequestBody(required = false) MarketActivityDto dto){
f931ff 374
F 375         log.info("营销活动领取优惠券参数:{}", JSONObject.toJSONString(dto));
376
377         //检查领取参数
378         MarketActivity marketActivity = checkReceiveParams(dto);
379         String errMsg = marketActivity.getErrMsg();
380
15e4e0 381         MarketActivityGroup group = commonService.selectOneByKey(MarketActivityGroupMapper.class, dto.getGroupId());
f931ff 382         if(group == null){
026734 383             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到活动分组信息!");
f931ff 384         }
F 385
386         EmployeeRole employeeRole = null;
387         if(dto.getOpType() == OperatorConstants.OP_TYPE_EMPLOYEE && StringUtils.noNull(dto.getOpRoleId())){
388             employeeRole = employeeRoleService.selectOneByKey(dto.getOpRoleId());
389         }
390
391         User user = commonService.selectOneByKey(UserMapper.class, dto.getUserId());
392         if(user == null){
393             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到用户信息!");
394         }
395         //领取检查参与限制逻辑
396         receiveCheckJoinLimit(marketActivity, user, errMsg);
397
398         SqlSentence sqlSentence = new SqlSentence();
399         Map<String, Object> values = new HashMap<>();
400         sqlSentence.setM(values);
401         StringBuffer sql = new StringBuffer();
402         values.put("marketActivityId", marketActivity.getId());
403
404         //查询用户是否又参与记录
405         values.put("userId", dto.getUserId());
406         sqlSentence.setSqlSentence(" select * from market_activity_join_record where isDel = 0 and marketActivityId = #{m.marketActivityId} and userId = #{m.userId} ");
407         MarketActivityJoinRecord joinRecord = commonService.selectOne(MarketActivityJoinRecordMapper.class, sqlSentence);
408
409         //判断如果活动限制参与人数
410         if(marketActivity.getLimitPeNum() > 0){
411             //没有参与记录则判断活动总参与人数是否超过了限制数量
412             if(joinRecord == null){
413                 sqlSentence.setSqlSentence(" select count(1) from market_activity_join_record where isDel = 0 and marketActivityId = #{m.marketActivityId} ");
414                 int joinNum = commonService.selectCountSql(sqlSentence);
415                 if(joinNum >= marketActivity.getLimitPeNum()){
416                     throw new PlatTipsException(PlatformCode.ERROR_TIPS, "活动优惠券已领取完," + errMsg);
417                 }
418             }
419         }
420
421         //查询活动领取的优惠券信息
422         sql.setLength(0);
423         values.put("groupId", group.getId());
424         values.put("commonType", MarketActivityConstants.COMMON_TYPE_COUPON);
425         sql.append(" select * from market_activity_item where isDel = 0 and marketActivityId = #{m.marketActivityId} and groupId = #{m.groupId} and commonType = #{m.commonType} ");
426         //单张优惠券领取则需要传这个值
427         if(StringUtils.noNull(dto.getActivityCouponId())){
428             values.put("id", dto.getActivityCouponId());
429             sql.append(" and id = #{m.id} ");
430         }
431
432         sqlSentence.setSqlSentence(sql.toString());
433         List<MarketActivityItem> list = commonService.selectList(MarketActivityItemMapper.class, sqlSentence);
434         if(list == null || list.size() < 1){
435             throw new PlatTipsException(PlatformCode.ERROR_TIPS, "查询不到活动优惠券信息!");
436         }
437
438         Date now = new Date();
439         List<MarketActivityItem> receiveList = new ArrayList<>();
440         //存储已领取完的优惠券名
441         List<String> cNameList = new ArrayList<>();
442         //是否全部领取
443         boolean isAll = StringUtils.isEmpty(dto.getActivityCouponId()) ? true : false;
444         //最小可领取间隔时长
445         int minInterval = 0;
446
447         //查询用户分组下领取过的优惠券种类数量
448         values.clear();
449         values.put("userId", dto.getUserId());
450         values.put("marketActivityId", marketActivity.getId());
451         values.put("groupId", group.getId());
452         values.put("commonType", MarketActivityConstants.COMMON_TYPE_COUPON);
453         sql.setLength(0);
454         sql.append(" select count(DISTINCT i.commonId) ")
455                 .append(" from market_activity_receive_record_item i ")
edffd3 456                 .append(" join market_activity_receive_record r on r.id = i.receiveRecordId ")
f931ff 457                 .append(" where i.isDel = 0 and r.userId = #{m.userId} and i.commonType = #{m.commonType} ")
F 458                 .append(" and r.marketActivityId = #{m.marketActivityId} and i.groupId = #{m.groupId} ");
459         sqlSentence.setSqlSentence(sql.toString());
460         int rctNum = commonService.selectCountSql(sqlSentence);
de16bd 461         //记录是否有新的领药优惠券种类数量
F 462         int rctNewNum = 0;
f931ff 463
F 464         //查询对应活动优惠券用户是否已领取(要根据优惠券id来,不可根据活动优惠券id来)
465         sql.setLength(0);
b283e4 466         values.put("approveStatus", MarketActivityReceiveRecordItem.APPROVE_STATUS_WAIT);
62ccfe 467         sql.append(" select count(if(i.groupId = #{m.groupId}, 1, null)) as receiveNum ")
b283e4 468                 .append(" , count(if(i.approveStatus = #{m.approveStatus}, 1, null)) as waitApproveNum ")
733bd8 469                 .append(" , date_format(max(i.createTime), '%Y-%m-%d %H:%i:%s') as receiveTime ")
f931ff 470                 .append(" from market_activity_receive_record_item i ")
F 471                 .append(" join market_activity_receive_record r on r.id = i.receiveRecordId ")
472                 .append(" where i.isDel = 0 and r.userId = #{m.userId} and i.commonType = #{m.commonType} ")
473                 .append(" and r.marketActivityId = #{m.marketActivityId} and i.activityItemId = #{m.activityItemId} ");
474         sqlSentence.setSqlSentence(sql.toString());
475
476         int receiveNum = 0;     //领取数量
477         int diffInterval = 0;   //相差间隔时长
b283e4 478         int waitApproveNum = 0; //待审批数量
f931ff 479         Date receiveTime = null;//最后领取时间
F 480         Map<String, Object> receiveMap;
481         Coupon coupon;
482
483         log.info("领取种类数量:{}", rctNum);
484         for(MarketActivityItem activityItem : list){
485
486             receiveNum = 0;
487             receiveTime = null;
488
489             values.put("activityItemId", activityItem.getId());
490             receiveMap = commonService.selectOneMap(MarketActivityMapper.class, sqlSentence);
491             if(receiveMap != null && receiveMap.size() > 0){
492                 receiveNum = receiveMap.get("receiveNum") != null ? Integer.parseInt(receiveMap.get("receiveNum").toString()) : 0;
493                 receiveTime = receiveMap.get("receiveTime") != null ? DateUtil.parseString_1(receiveMap.get("receiveTime").toString()) : null;
b283e4 494                 waitApproveNum = receiveMap.get("waitApproveNum") != null ? Integer.parseInt(receiveMap.get("waitApproveNum").toString()) : 0;
f931ff 495             }
b283e4 496
F 497
f931ff 498
F 499             //如果领取数量为0,则领取种类数量+1
500             if(receiveNum == 0){
de16bd 501                 rctNewNum++;
f931ff 502                 rctNum ++;
F 503             }
504
505             //用户没有领取记录,判断活动是否限制了N选M,然后判断用户领取是否超过N选M设置数量
506             if(group.getLimitRctNum() > 0 && rctNum > group.getLimitRctNum()){
507                 if(isAll){
508                     continue;
509                 }
510                 throw new PlatTipsException(PlatformCode.ERROR_TIPS, "领取的优惠券种类已超过活动分组设置的数量,不可继续领取其他优惠券," + errMsg);
511             }
de16bd 512             log.info("领取种类数量:{},{}", rctNum, rctNewNum);
f931ff 513
F 514
515             //判断活动限制参与次数,且领取超过限制次数(原为活动joinNum字段判断,现在按优惠券设置字段来判断)
516             if(activityItem.getLimitRecNum() > 0 && receiveNum >= activityItem.getLimitRecNum()){
517                 if(isAll){
518                     continue;
519                 }
520                 throw new PlatTipsException(PlatformCode.ERROR_TIPS, "当前活动优惠券每人仅限领取"+activityItem.getLimitRecNum()+"次," + errMsg);
521             }
522
523             //判断活动是否限制了领取间隔
524 //            log.info("receiveNum:{}", receiveNum);
525 //            log.info("最后领取时间:{}", DateUtil.formatDate_2(receiveTime));
526 //            log.info("限制领取间隔:{}", marketActivity.getRecInterval());
527             if(marketActivity.getRecInterval() > BaseEntity.NO && receiveTime != null){
528                 //计算相差间隔时长 = 活动限制间隔时长 - 领取间隔时长
529                 diffInterval =  marketActivity.changeRecInterval() - differHour(receiveTime, now).intValue();
530 //                log.info("相差间隔:{}", diffInterval);
531                 if(diffInterval > 0){
532                     if(isAll){
533                         //赋值最小间隔时长
534                         minInterval = minInterval == 0 ? diffInterval : diffInterval < minInterval ? diffInterval : minInterval;
535                         continue;
536                     }
537                     throw new PlatTipsException(PlatformCode.ERROR_TIPS, "活动优惠券还需等待" + diffInterval + "小时才可继续领取!");
538                 }
539             }
540
541             //查询优惠券信息,判断是否到了领取时间
542             coupon = commonService.selectOneByKey(CouponMapper.class, activityItem.getCommonId());
543             if(coupon == null){
544                 throw new PlatTipsException(PlatformCode.ERROR_TIPS, "查询不到领取的优惠券信息!");
545             }
546
547             if(coupon.getIsDel() == BaseEntity.YES){
548                 if(isAll){
549                     continue;
550                 }
551                 throw new PlatTipsException(PlatformCode.ERROR_TIPS, "领取的优惠券已被删除," + errMsg);
552             }
553
554             if(coupon.getIsUp() == BaseEntity.NO){
555                 if(isAll){
556                     continue;
557                 }
558                 throw new PlatTipsException(PlatformCode.ERROR_TIPS, "领取的优惠券已下架,"+ errMsg);
559             }
560
561             if(coupon.getIssueStartTime() != null && now.compareTo(coupon.getIssueStartTime()) < 0){
562                 if(isAll){
563                     continue;
564                 }
565                 throw new PlatTipsException(PlatformCode.ERROR_TIPS, "活动优惠券还未到领取时间," + errMsg);
566             }
567
568             if(coupon.getIssueEndTime() != null && now.compareTo(coupon.getIssueEndTime()) > 0){
569                 if(isAll){
570                     continue;
571                 }
572                 throw new PlatTipsException(PlatformCode.ERROR_TIPS, "活动优惠券已过领取时间," + errMsg);
573             }
574
b283e4 575             //判断待审批的不能领取
F 576             if(waitApproveNum > 0){
577                 if(isAll){
578                     throw new PlatTipsException(PlatformCode.ERROR_TIPS, "优惠券["+activityItem.getCommonName()+"]上次领取还未审批,不可全部领取," + errMsg);
579                 }
580                 throw new PlatTipsException(PlatformCode.ERROR_TIPS, "当前优惠券上次领取还未审批,不可继续领取," + errMsg);
581             }
582
f931ff 583             //判断优惠券剩余数量是否小于等于0,存储名称后面抛错提示
F 584             if(couponSurplusNum(coupon) <= 0){
585                 cNameList.add(coupon.getTitle());
586             }
587
588             receiveList.add(activityItem);
589         }
590
591         if(cNameList.size() > 0){
592             StringBuffer errSb = new StringBuffer();
593             errSb.append("活动爆满,优惠券【");
594             for(String name : cNameList){
595                 errSb.append(name).append("、");
596             }
597             errSb.delete(errSb.length() - 1, errSb.length()).append("】已领取完,").append(errMsg);
598             throw new PlatTipsException(PlatformCode.ERROR_TIPS, errSb.toString());
599         }
600
601         if(receiveList.size() == 0){
602             if(isAll){
603                 if(minInterval > 0){
604                     throw new PlatTipsException(PlatformCode.ERROR_TIPS, "活动全部领取还需等待" + minInterval + "小时才可继续领取!");
605                 }
606                 throw new PlatTipsException(PlatformCode.ERROR_TIPS, "暂无可领取的优惠券," + errMsg);
607             }
608 //            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "活动每人仅限参与"+marketActivity.getJoinNum()+"次," + errMsg);
609         }
610
611         //处理参与记录逻辑
612         if(joinRecord == null){
613             joinRecord = new MarketActivityJoinRecord();
614             joinRecord.setDateStr(Integer.parseInt(DateUtil.formatDate(now)));
615             joinRecord.setMarketActivityId(marketActivity.getId());
616             joinRecord.setPlatformType(dto.getPlatformType());
617             //领取次数
618             joinRecord.setReceiveNum(1);
619             //用户信息
620             joinRecord.setUserId(user.getId());
621             joinRecord.setUserName(user.getName());
622             joinRecord.setCIQ(user.getCIQ());
623             joinRecord.setUserLevel(user.getUserLevel());
624             joinRecord.setUserStatus(user.getUserStatus());
625             joinRecord.setUserConsultantId(user.getHisCorpUserId());
626             joinRecord.setUserConsultantName(EmployeeTool.getCnName(joinRecord.getUserConsultantId(), commonService));
627             joinRecord.setUserShopId(user.getShopId());
628             joinRecord.setUserShopName(ShopTool.getShopName(joinRecord.getUserShopId(), commonService));
629             //通过用户创建日期
630             if(DateUtil.formatDate(user.getCreateTime()).equals(joinRecord.getDateStr())){
631                 joinRecord.setIsNewUser(BaseEntity.YES);
632             }
633         }
634
635         //每次都新增领取记录
636         MarketActivityReceiveRecord receiveRecord = new MarketActivityReceiveRecord();
637         receiveRecord.setMarketActivityId(marketActivity.getId());
638         receiveRecord.setPlatformType(dto.getPlatformType());
639         //操作人
640         receiveRecord.setOpId(dto.getOpId());
641         receiveRecord.setOpName(dto.getOpName());
642         receiveRecord.setOpType(dto.getOpType());
643         if(employeeRole != null){
644             receiveRecord.setOpShopId(employeeRole.getShopId());
645             receiveRecord.setOpRoleId(employeeRole.getId());
646             receiveRecord.setOpRoleStr(employeeRole.getRoleUniqueStr());
647         }
648         //没有指定领取对应关联优惠券时,则是全部领取
649         receiveRecord.setIsAll(isAll ? 1 : 0);
650         //用户信息
651         receiveRecord.setUserId(user.getId());
652         receiveRecord.setUserName(user.getName());
653         receiveRecord.setCIQ(user.getCIQ());
654         receiveRecord.setUserLevel(user.getUserLevel());
655         receiveRecord.setUserStatus(user.getUserStatus());
656         receiveRecord.setUserConsultantId(user.getHisCorpUserId());
657         receiveRecord.setUserConsultantName(EmployeeTool.getCnName(receiveRecord.getUserConsultantId(), commonService));
658         receiveRecord.setUserShopId(user.getShopId());
659         receiveRecord.setUserShopName(ShopTool.getShopName(receiveRecord.getUserShopId(), commonService));
a2688a 660
F 661         //累加领取优惠券数量
662         joinRecord.setCouponNum(joinRecord.getCouponNum() + receiveList.size());
663
664         synchronized (MarketActivityController.class){
665             marketActivityService.receiveCoupon(marketActivity, receiveList, user, joinRecord, receiveRecord);
666         }
667
668         return Result.success();
669     }
026734 670
F 671     /** 领取审批回调 */
672     @RequestMapping("/receiveApproveCallback")
673     public Result receiveApproveCallback(@RequestBody MarCommonReturnDto returnDto){
39113f 674         log.info("营销活动领取审批回调:{}", JSONObject.toJSONString(returnDto));
026734 675
F 676         if(StringUtils.isEmpty(returnDto.getData())){
677             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "请求数据为空!");
678         }
679
680         MarketingReturnDto dto = JSONObject.parseObject(returnDto.getData(), MarketingReturnDto.class);
681         if(dto == null){
682             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "返回结果数据为空!");
683         }
684
685         if(StringUtils.isEmpty(dto.getResult())){
686             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "审批结果为空!");
687         }
688
689         if(StringUtils.isEmpty(dto.getUniqueId())){
690             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "唯一值标识为空!");
691         }
692
693         MarketActivityReceiveRecordItem recordItem = commonService.selectOneByKey(MarketActivityReceiveRecordItemMapper.class, dto.getUniqueId());
694         if(recordItem == null){
695             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到领取记录信息1!");
696         }
697
698         if(recordItem.getApproveStatus() != MarketActivityReceiveRecordItem.APPROVE_STATUS_WAIT){
699             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "领取记录审批状态异常!");
700         }
701
702         if(MarketingReturnDto.AGREE.equals(dto.getResult())){
703             recordItem.setApproveStatus(MarketActivityReceiveRecordItem.APPROVE_STATUS_SUC);
62ccfe 704         }else if(MarketingReturnDto.REJECT.equals(dto.getResult())){
026734 705             recordItem.setApproveStatus(MarketActivityReceiveRecordItem.APPROVE_STATUS_FAIL);
F 706         }else{
707             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "审批状态异常!");
708         }
62ccfe 709         recordItem.setApproveRemark(dto.getApplyRemarks());
026734 710
F 711         MarketActivityReceiveRecord receiveRecord = commonService.selectOneByKey(MarketActivityReceiveRecordMapper.class, recordItem.getReceiveRecordId());
712         if(receiveRecord == null){
713             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到领取记录信息2!");
714         }
715
733bd8 716         MarketActivityJoinRecord joinRecord = commonService.selectOneByKey(MarketActivityJoinRecordMapper.class, receiveRecord.getJoinRecordId());
F 717         if(joinRecord == null){
718             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到活动参与记录信息!");
719         }
720
721         marketActivityService.receiveApproveHandle(joinRecord, receiveRecord, recordItem);
026734 722
F 723         return Result.success();
724     }
a2688a 725
9aad48 726     /**审批列表*/
R 727     @RequestMapping("/approve/list")
43563a 728     public Result pendingApproveCoupon(@RequestBody MarketActivityDto dto) {
R 729
730         log.info("营销活动获取待审核优惠券参数:{}", JSONObject.toJSONString(dto));
731
732         //检查
733         if(StringUtils.isEmpty(dto.getMarketActivityId())){
734             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "营销活动标识为空!");
735         }
736
737         MarketActivity marketActivity = commonService.selectOneByKeyBlob(MarketActivityMapper.class,dto.getMarketActivityId());
738         if(marketActivity == null){
739             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到营销活动信息!");
740         }
741
742         SqlSentence sqlSentence = new SqlSentence();
743         Map<String, Object> values = new HashMap<>();
744         sqlSentence.setM(values);
745
746         values.put("isDel", BaseEntity.NO);
747         values.put("commonType", MarketActivityConstants.COMMON_TYPE_COUPON);
748         values.put("marketActivityId", dto.getMarketActivityId());
749
750         StringBuffer sql = new StringBuffer();
751         sql.append(" SELECT ri.id as recordItemId,ri.approveStatus, c.id AS couponId, c.title AS couponName")
752                 .append(" , c.type,c.platformType, mai.limitRecNum , ma.id as marketActivityId, mai.id as marketActivityItemId")
9aad48 753                 .append(" , date_format( c.issueStartTime, '%Y-%m-%d %H:%i:%s') as issueStartTime ")
R 754                 .append(" , date_format( c.issueEndTime, '%Y-%m-%d %H:%i:%s') as issueEndTime ")
43563a 755                 .append(" , CASE c.type WHEN 0 THEN c.discountNum ELSE c.discountAmount END AS couponPrice")
923fa1 756                 .append(" , rr.opName,rr.userName,rr.CIQ,ri.approveRemark as remark ")
43563a 757                 .append(" FROM market_activity ma")
R 758                 .append(" LEFT JOIN market_activity_item mai ON ma.id = mai.marketActivityId")
759                 .append(" LEFT JOIN coupon c ON mai.commonId = c.id AND mai.commonType = #{m.commonType} ")
760                 .append(" LEFT JOIN market_activity_receive_record_item ri on ri.activityItemId = mai.id ")
ad8097 761                 .append(" LEFT JOIN market_activity_receive_record rr on ri.receiveRecordId = rr.id ")
43563a 762                 .append(" WHERE ma.isDel = #{m.isDel} AND ma.id = #{m.marketActivityId} ");
R 763         //审批状态查询
764         if (dto.getApprovalStatus()!= null) {
765             values.put("approveStatus", dto.getApprovalStatus());
766             sql.append(" AND ri.approveStatus = #{m.approveStatus}");
7d1b51 767         }else {
R 768             sql.append(" AND ri.approveStatus in (0,1,2,3)");
43563a 769         }
R 770
923fa1 771         sql.append(" ORDER BY ri.createTime DESC ");
43563a 772         sqlSentence.setSqlSentence(sql.toString());
R 773
774         PageHelper.startPage(dto.getPageNum() == null ? 1 : dto.getPageNum(), dto.getPageSize() == null ? 10 : dto.getPageSize());
775         List<Map<String, Object>> list = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
776         PageInfo pageInfo = new PageInfo(list);
777
778         return Result.success(pageInfo);
779
780     }
781
782     /** 后台领取审批 */
783     @RequestMapping("/receive/approve/callback/admin")
784     public Result receiveApproveCallbackAdmin(@RequestBody MarketActivityDto dto){
785
786         log.info("营销活动审核操作传值参数:{}", JSONObject.toJSONString(dto));
787
788         if(StringUtils.isEmpty(dto.getRecordItemId())){
789             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "标识为空!");
790         }
791
792         if(StringUtils.isEmpty(dto.getOpId())){
793             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "操作人为空!");
794         }
795
22e3af 796         if(StringUtils.isEmpty(dto.getStatusStr())){
43563a 797             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "审核状态为空!");
R 798         }
799
800         MarketActivityReceiveRecordItem recordItem = commonService.selectOneByKeyBlob(MarketActivityReceiveRecordItemMapper.class, dto.getRecordItemId());
801         if(recordItem == null){
802             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到领取记录信息!");
803         }
804
805         if(recordItem.getApproveStatus() != MarketActivityReceiveRecordItem.APPROVE_STATUS_WAIT){
806             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "领取记录审批状态异常!");
807         }
808
809         if(MarketingReturnDto.AGREE.equals(dto.getStatusStr())){
810             recordItem.setApproveStatus(MarketActivityReceiveRecordItem.APPROVE_STATUS_SUC);
811         }else if(MarketingReturnDto.REJECT.equals(dto.getStatusStr())){
812             recordItem.setApproveStatus(MarketActivityReceiveRecordItem.APPROVE_STATUS_FAIL);
813         }else{
814             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "审批状态异常!");
815         }
6ee8f8 816         recordItem.setApproveRemark(dto.getRemark());
43563a 817         MarketActivity marketActivity = commonService.selectOneByKeyBlob(MarketActivityMapper.class,recordItem.getMarketActivityId());
R 818         if(marketActivity == null){
819             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到活动信息!");
820         }
821
22e3af 822         if(!marketActivity.getManagerId().equals(dto.getOpId())){
43563a 823             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "当前操作审批人与负责人不一致!");
R 824         }
825
826         MarketActivityReceiveRecord receiveRecord = commonService.selectOneByKey(MarketActivityReceiveRecordMapper.class, recordItem.getReceiveRecordId());
827         if(receiveRecord == null){
828             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到领取记录信息!");
829         }
830
831         MarketActivityJoinRecord joinRecord = commonService.selectOneByKey(MarketActivityJoinRecordMapper.class, receiveRecord.getJoinRecordId());
832         if(joinRecord == null){
833             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到活动参与记录信息!");
834         }
835
836         marketActivityService.receiveApproveHandle(joinRecord, receiveRecord, recordItem);
837
22e3af 838         return Result.success();
43563a 839     }
a2688a 840
F 841     ///////////////////////////////////////////////////////////////////////////
6eb6fb 842
F 843     /** 检查校验领取参数 */
844     private MarketActivity checkReceiveParams(MarketActivityDto dto){
845         if(dto == null){
846             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "请求对象不能为空!");
847         }
848
849         if(StringUtils.isEmpty(dto.getMarketActivityId())){
850             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "活动标识不能为空!");
851         }
f931ff 852
F 853         if(StringUtils.isEmpty(dto.getGroupId())){
854             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "活动分组标识不能为空!");
855         }
856
6eb6fb 857
F 858         if(StringUtils.isEmpty(dto.getUserId())){
859             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "领取用户不能为空!");
860         }
861
862         if(StringUtils.isEmpty(dto.getPlatformType())){
863             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "平台类型不能为空!");
864         }
865
866         if(dto.getOpType() == null){
867             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "操作人类型不能为空!");
868         }
869
870         if(StringUtils.isEmpty(dto.getOpId())){
871             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "操作人标识不能为空!");
872         }
873
874         if(StringUtils.isEmpty(dto.getOpName())){
875             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "操作人名称不能为空!");
876         }
877
878         MarketActivity marketActivity = commonService.selectOneByKey(MarketActivityMapper.class, dto.getMarketActivityId());
879         if(marketActivity == null){
880             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到活动信息!");
881         }
882
883         String errMsg = "请联系活动负责人"+marketActivity.getManagerName()+"咨询情况";
884         marketActivity.setErrMsg(errMsg);
885
886         if(marketActivity.getIsUp() == BaseEntity.NO){
887             throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "活动已下架," + errMsg);
888         }
889
890         if(marketActivity.getTimeType() == MarketActivity.TIME_TYPE_APPOINT_TIME){
891             Date now = new Date();
892             if(now.compareTo(marketActivity.getStartTime()) < 0){
893                 throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "活动还未开始," + errMsg);
894             }
895             if(now.compareTo(marketActivity.getEndTime()) > 0){
896                 throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "活动已结束," + errMsg);
897             }
898         }
899
900         return marketActivity;
901     }
a2688a 902
F 903     //获取优惠券剩余数量
904     public int couponSurplusNum(Coupon coupon){
905         // 查询已发送的数量
906         SqlSentence sqlSentence = new SqlSentence();
907         Map<String, Object> sqlValues = new HashMap<>();
908         sqlValues.put("isDel", BaseEntity.NO);
909         sqlValues.put("validState", BaseEntity.YES);
910         sqlValues.put("couponId", coupon.getId());
911         sqlSentence.sqlWhere(" couponId = #{m.couponId} AND validState = #{m.validState} AND isDel = #{m.isDel}", sqlValues);
912         int count = commonService.selectCount(CouponNumberMapper.class,sqlSentence);
913         if (coupon.getIssueNum() != null) {
914             return coupon.getIssueNum() - count;
915         } else {
916            return 0;
917         }
918     }
919
7111ca 920     //查询用户渠道inSql
F 921     public String queryUserChannelInSql(User user){
922         StringBuffer channelInSql = new StringBuffer();
923         if(StringUtils.noNull(user.getChannelId())){
924             channelInSql.append("'").append(user.getChannelId()).append("',");
925         }
926         if(StringUtils.noNull(user.getChannel2Id())){
927             channelInSql.append("'").append(user.getChannel2Id()).append("',");
928         }
929         if(StringUtils.noNull(user.getChannelAssistId())){
930             channelInSql.append("'").append(user.getChannelAssistId()).append("',");
931         }
932         if(StringUtils.noNull(user.getChannelAssist2Id())){
933             channelInSql.append("'").append(user.getChannelAssist2Id()).append("',");
934         }
935         if(channelInSql.length() > 0){
936             channelInSql.delete(channelInSql.length()-1, channelInSql.length());
937         }
938         return channelInSql.toString();
939     }
940
941     //领取检查参与限制逻辑
942     public void receiveCheckJoinLimit(MarketActivity marketActivity, User user, String errMsg){
943
074aee 944         //判断用户会员等级是否符合限制--------------------------------------------------
7111ca 945         if(StringUtils.noNull(marketActivity.getLimitUserLevel())){
F 946             if(StringUtils.isEmpty(user.getUserLevel())
947                     || marketActivity.getLimitUserLevel().indexOf(user.getUserLevel()) == -1){
948                 throw new PlatTipsException(PlatformCode.ERROR_TIPS, "用户会员等级不在活动范围内," + errMsg);
949             }
950         }
951
952         SqlSentence sqlSentence = new SqlSentence();
953         Map<String, Object> values = new HashMap<>();
954         sqlSentence.setM(values);
955         StringBuffer sql = new StringBuffer();
956         values.put("marketActivityId", marketActivity.getId());
957
074aee 958         //查询活动限制总表限制信息------------------------------------------------------
7111ca 959         sql.append(" select lo.commonId, lo.commonName, lo.type ")
F 960                 .append(" from limit_total lt  ")
961                 .append(" join limit_other lo on lo.limitTotalId = lt.id  ")
962                 .append(" where lt.isDel = 0 and lo.isDel = 0 and lt.foreignKey = #{m.marketActivityId} ");
963         sqlSentence.setSqlSentence(sql.toString());
964         List<Map<String, Object>> limitList = commonService.selectListMap(MarketActivityMapper.class, sqlSentence);
965
966         //过滤限制门店的信息判断用户是否符合限制门店
33db03 967         List<Map<String, Object>> limitShopList = limitList.stream().filter(s-> LimitOther.TYPE_SHOP.toString().equals(s.get("type").toString())).collect(Collectors.toList());
7111ca 968         if(limitShopList != null && limitShopList.size() > 0){
F 969             boolean canReceive = false;
970             for(Map<String, Object> m : limitShopList){
971                 if(m.get("commonId").toString().equals(user.getShopId())){
972                     canReceive = true;
973                     break;
974                 }
975             }
976             if(!canReceive){
977                 throw new PlatTipsException(PlatformCode.ERROR_TIPS, "用户所属门店不在活动范围内," + errMsg);
978             }
979         }
980
074aee 981         //过滤限制渠道的信息判断用户是否符合限制渠道---------------------------------------------
33db03 982         List<Map<String, Object>> limitUcList = limitList.stream().filter(s-> LimitOther.TYPE_CHANNEL.toString().equals(s.get("type").toString())).collect(Collectors.toList());
7111ca 983         if(limitUcList != null && limitUcList.size() > 0){
F 984             boolean canReceive = false;
985             //用户渠道id
986             String userChannelIds = queryUserChannelInSql(user);
987             for(Map<String, Object> m : limitUcList){
988                 //用户渠道包含的就算
989                 if(userChannelIds.indexOf(m.get("commonId").toString()) != -1){
990                     canReceive = true;
991                     break;
992                 }
993             }
994             if(!canReceive){
995                 throw new PlatTipsException(PlatformCode.ERROR_TIPS, "用户所属渠道不在活动范围内," + errMsg);
996             }
997         }
998
074aee 999         //执行或消费限制判断----------------------------------------------------------
F 1000         if(marketActivity.getLimitEcNum() > 0){
1001             //查询出限制条件
1002             sqlSentence.setSqlSentence(" select * from market_activity_limit_ec where isDel = 0 and marketActivityId = #{m.marketActivityId} order by moduleNo asc ");
1003             List<MarketActivityLimitEc> limitEcList = commonService.selectList(MarketActivityLimitEcMapper.class, sqlSentence);
1004             if(limitEcList != null && limitEcList.size() > 0)
1005             {
1006
1007                 //查询用户项目执行次数sql(已执行、汇总执行次数)
a7e7ee 1008                 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} ";
074aee 1009                 //查询用户消费次数sql(已支付、汇总时购买数量-已退款数量)
a7e7ee 1010                 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} ";
074aee 1011
F 1012                 //按模块编号过滤分组数据
1013                 Map<Integer, List<MarketActivityLimitEc>> ecMap = limitEcList.stream().collect(Collectors.groupingBy(MarketActivityLimitEc::getModuleNo));
a7e7ee 1014                 log.info("限制消费模块数据:{}", JSONObject.toJSONString(ecMap));
074aee 1015                 //最终是否符合
F 1016                 boolean isConform = false;
1017                 //遍历是否满足模块所有条件
1018                 boolean isOk = false;
1019                 //遍历
1020                 for(Map.Entry<Integer, List<MarketActivityLimitEc>> entry : ecMap.entrySet())
1021                 {
1022                     //按模块遍历,默认是满足,下面遍历如果有条件不符合,就是false
1023                     isOk = true;
1024                     values.put("userId", user.getId());
1025
1026                     //遍历模块下的限制条件
1027                     for(MarketActivityLimitEc limitEc : entry.getValue())
1028                     {
1029                         if(limitEc.getActionType() == MarketActivityLimitEc.ACTION_TYPE_EXECUTE){
1030                             //执行-项目
1031                             values.put("status", DeductionSingleConstants.STATUS_DONE_EXECUTE);
1032                             sqlSentence.setSqlSentence(executeSql);
1033                         }else if(limitEc.getActionType() == MarketActivityLimitEc.ACTION_TYPE_CONSUME){
1034                             //消费-项目、促销、卡项
1035                             values.put("payStatus", OrderTotalConstants.PAY_STATUS_SUC);
1036                             sqlSentence.setSqlSentence(consumeSql);
1037                         }else{
1038                             //没有对应类型,直接不满足跳出循环
1039                             isOk = false;
1040                             break;
1041                         }
1042
1043                         //根据时间单位+时间范围数值换算出有效日期
1044                         values.put("dateTime", limitEc.convertDateTime());
1045                         values.put("commonId", limitEc.getCommonId());
1046
1047                         //判断如果用户不满足限制数量,直接跳出循环,用户不满足模块限制
1048                         if(commonService.selectCountSql(sqlSentence) < limitEc.getNum()){
1049                             isOk = false;
1050                             break;
1051                         }
1052                     }
1053
1054                     //其中一个满足,直接跳出循环,然后标记为符合领取
1055                     if(isOk){
1056                         isConform = true;
1057                         break;
1058                     }
1059                 }
1060                 //全部遍历完成后,如果不符合则提示不能领取
1061                 if(!isConform){
1062                     throw new PlatTipsException(PlatformCode.ERROR_TIPS, "用户不满足执行或消费条件限制无法领取," + errMsg);
1063                 }
1064             }
1065         }
96c4e1 1066
F 1067         //END--------------------------------------------------------------
7111ca 1068     }
074aee 1069
6eb6fb 1070     //间隔时长
F 1071     public static Long differHour(Date startTime, Date endTime) {
1072         if(startTime == null || endTime == null){
1073             return 0L;
1074         }
1075         long sTime = startTime.getTime();
1076         long eTime = endTime.getTime();
1077         return (eTime - sTime) / 1000L / 60L / 60L;
1078     }
1079
f931ff 1080     /** 处理列表条件查询sql */
F 1081     public void handleListConditionQuerysSql(MarketActivityDto dto, StringBuffer sql, Map<String, Object> values){
1082
1083         if (!StringUtils.isEmpty(dto.getKeyWord())) {
1084             sql.append(" and a.title like #{m.keyWord} ");
1085             values.put("keyWord", "%" + dto.getKeyWord() + "%");
1086         }
1087
1088         if(dto.getIsUp() != null){
1089             sql.append(" and a.isUp = #{m.isUp} ");
1090             values.put("isUp", dto.getIsUp());
1091         }
1092
1093         if(dto.getIsCoupon() != null){
1094             if(dto.getIsCoupon() == BaseEntity.NO){
1095                 sql.append(" and a.couponNum = 0 ");
1096             }else{
1097                 sql.append(" and a.couponNum > 0 ");
1098             }
1099         }
1100
1101         if (!StringUtils.isEmpty(dto.getClassifyId())) {
1102             sql.append(" and a.classifyId = #{m.classifyId} ");
1103             values.put("classifyId", dto.getClassifyId());
1104         }
1105
1106         if (!StringUtils.isEmpty(dto.getStartTime())) {
1107             sql.append(" and a.startTime >= date_format(#{m.startTime}, '%Y-%m-%d %00:%00:%00') ");
1108             values.put("startTime", dto.getStartTime());
1109         }
1110
1111         if (!StringUtils.isEmpty(dto.getEndTime())) {
1112             sql.append(" and a.endTime <= date_format(#{m.endTime}, '%Y-%m-%d %23:%59:%59') ");
1113             values.put("endTime", dto.getEndTime());
1114         }
1115
1116         if(StringUtils.noNull(dto.getShopIds())){
1117             //遍历拼接门店in查询sql
1118             String [] shopArr = dto.getShopIds().split(",");
1119             StringBuffer shopInSql = new StringBuffer();
1120             for(String shopId : shopArr){
1121                 shopInSql.append("'").append(shopId).append("',");
1122             }
1123             shopInSql.delete(shopInSql.length() - 1, shopInSql.length());
1124
1125             //对应子查询限制总表符合的活动id,再in查询对应符合的
1126             values.put("ltType", LimitTotal.LIMIT_MARKET_ACTIVITY);
1127             values.put("loType", LimitOther.TYPE_SHOP);
1128             sql.append(" and ( ")
1129                     .append(" a.id in ( ")
1130                     .append(" select lt.foreignKey from limit_total lt ")
1131                     .append(" join limit_other lo on lo.limitTotalId = lt.id and lo.isDel = 0 ")
1132                     .append(" where lt.isDel = 0 and lt.type = #{m.ltType} and lo.type = #{m.loType}  ")
1133                     .append(" and lo.commonId in (").append(shopInSql).append(") group by lt.foreignKey ")
1134                     .append(" )  ")
1135                     .append(" or a.isLimitShop = 0  )   ");
1136         }
1137
1138         //如果用户id不为空,处理限制用户逻辑
1139         if(StringUtils.noNull(dto.getUserId())){
1140             User user = commonService.selectOneByKey(UserMapper.class, dto.getUserId());
1141             if(user == null){
1142                 throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "查询不到用户信息!");
1143             }
1144
1145             //查询符合用户会员等级的活动
1146             values.put("userLevel", user.getUserLevel());
1147             sql.append(" and ( limitUserLevel is null  or ( #{m.userLevel} is not null and #{m.userLevel} != '' and LOCATE( #{m.userLevel}, limitUserLevel) > 0) ) ");
1148
1149             //对应子查询限制总表符合用户渠道的活动id,再in查询对应符合的
1150             String channelInSql = queryUserChannelInSql(user);
1151             sql.append(" and ( a.isLimitUC = 0 ");
1152             if(StringUtils.noNull(channelInSql)){
1153                 values.put("ltType2", LimitTotal.LIMIT_MARKET_ACTIVITY);
1154                 values.put("loType2", LimitOther.TYPE_CHANNEL);
1155                 sql.append(" or a.id in ( ")
1156                         .append(" select lt.foreignKey from limit_total lt ")
1157                         .append(" join limit_other lo on lo.limitTotalId = lt.id and lo.isDel = 0 ")
1158                         .append(" where lt.isDel = 0 and lt.type = #{m.ltType2} and lo.type = #{m.loType2}  ")
1159                         .append(" and lo.commonId in (").append(channelInSql).append(") group by lt.foreignKey ")
1160                         .append(" )  ");
1161             }
1162             sql.append(" ) ");
1163         }
1164     }
1165
6eb6fb 1166     public static void main(String args[]){
074aee 1167 //        Date startTime = DateUtil.parseString_1("2023-08-21 16:00:00");
F 1168 //        Date endTime = new Date();
1169 //        System.out.println(differHour(startTime, endTime));
1170
f931ff 1171 //        List<MarketActivityLimitEc> limitEcList = new ArrayList<>();
F 1172 //        limitEcList.add(new MarketActivityLimitEc(1, "1001"));
1173 //        limitEcList.add(new MarketActivityLimitEc(1, "1002"));
1174 //        limitEcList.add(new MarketActivityLimitEc(1, "1003"));
1175 //
1176 //        limitEcList.add(new MarketActivityLimitEc(2, "2001"));
1177 //        limitEcList.add(new MarketActivityLimitEc(2, "2002"));
1178 //
1179 //        limitEcList.add(new MarketActivityLimitEc(3, "3001"));
1180 //
1181 //        Map<Integer, List<MarketActivityLimitEc>> ecMap =limitEcList.stream().collect(Collectors.groupingBy(MarketActivityLimitEc::getModuleNo));
1182 //        System.out.println(ecMap.entrySet());
074aee 1183
f931ff 1184         List<Map<String, Object>> list = new ArrayList<>();
F 1185         Map<String, Object> map = new HashMap<>();
1186         map.put("id", "1");
1187         list.add(map);
074aee 1188
F 1189
f931ff 1190         map = new HashMap<>();
F 1191         map.put("id", "2");
1192         list.add(map);
1193         map = new HashMap<>();
1194         map.put("id", "2");
1195         list.add(map);
074aee 1196
f931ff 1197         map = new HashMap<>();
F 1198         map.put("id", "3");
1199         list.add(map);
1200         map = new HashMap<>();
1201         map.put("id", "3");
1202         list.add(map);
1203         map = new HashMap<>();
1204         map.put("id", "3");
1205         list.add(map);
1206
1207         Map<String, Long> map2 = list.stream().filter(s->s.get("id1") != null).collect(Collectors.groupingBy(s->s.get("id1").toString(), Collectors.counting()));
1208         System.out.println(map2.entrySet());
1209
6eb6fb 1210     }
a2688a 1211 }