rx
2024-01-09 11c481fb398685a8a73d33bcbec4c9f984c5d899
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
package com.hx.phip.service.market.impl;
 
import com.hx.common.service.CommonService;
import com.hx.exception.TipsException;
import com.hx.guide.util.CommonQueryUtil;
import com.hx.guide.util.mp.WeiXinCorpMpUtil;
import com.hx.mybatisTool.SqlSentence;
import com.hx.phiappt.common.OperatorConstants;
import com.hx.phiappt.constants.tool.CouponTool;
import com.hx.phiappt.constants.tool.SendMessageTool;
import com.hx.phiappt.constants.tool.employee.EmployeeTool;
import com.hx.phiappt.constants.tool.model.MessageTemplate;
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.Employee;
import com.hx.phiappt.model.Shop;
import com.hx.phiappt.model.User;
import com.hx.phiappt.model.coupon.Coupon;
import com.hx.phiappt.model.coupon.CouponReleaseRecordItem;
import com.hx.phiappt.model.market.*;
import com.hx.phip.config.GlobalExceptionHandler;
import com.hx.phip.config.ProcessBean;
import com.hx.phip.service.market.MarketActivityService;
import com.hx.resultTool.Result;
import com.hx.util.DateUtil;
import com.hz.his.dto.marketing.common.*;
import com.hz.his.feign.service.marketing.MCommonService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.hx.phip.config.CustomParameter;
import javax.annotation.Resource;
import java.util.*;
 
 
@Slf4j
@Transactional
@Service
public class MarketActivityServiceImpl implements MarketActivityService {
 
    @Resource
    private CommonService commonService;
    @Resource
    private MCommonService mCommonService;
    @Resource
    private ProcessBean processBean;
    @Resource
    private CustomParameter customParameter;
 
    /** 领取优惠券 */
    @Override
    public void receiveCoupon(MarketActivity marketActivity, List<MarketActivityItem> list, User user
            , MarketActivityJoinRecord joinRecord, MarketActivityReceiveRecord receiveRecord) {
 
        //优惠券操作人类型,默认员工
        int couponOpType = OperatorConstants.changeCouponOpType(receiveRecord.getOpType());
 
        //拼接用户数据
        JSONArray userArr = new JSONArray();
        JSONObject json = new JSONObject();
        json.put("id", user.getId());
        json.put("amount", 1);
        userArr.add(json);
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> values = new HashMap<>();
        sqlSentence.setM(values);
 
        //领取记录子项list
        MarketActivityReceiveRecordItem recordItem = null;
        List<MarketActivityReceiveRecordItem> recordItemList = new ArrayList<>();
 
        //遍历领取
        String couponName = "";
        Integer isApprove = BaseEntity.NO;
        for(MarketActivityItem activityCoupon : list)
        {
            //新增
            recordItem = new MarketActivityReceiveRecordItem(activityCoupon);
            recordItemList.add(recordItem);
            //获取优惠券名称
            couponName = activityCoupon.getCommonName();
            //判断是否需要审批,如果需要审批先跳过不发放优惠券
            if(activityCoupon.getIsApprove() == BaseEntity.YES){
                isApprove = activityCoupon.getIsApprove();
                continue;
            }
 
            //发放优惠券
            try{
                sendCoupon(couponOpType, userArr, receiveRecord, recordItem);
            }catch (Exception e){
                log.error("参数:{}", JSONObject.fromObject(activityCoupon));
                log.error("遍历发放优惠券失败:{}", GlobalExceptionHandler.getExceptionInformation(e));
                //统一提示
                throw new TipsException("活动爆满【"+activityCoupon.getCommonName()+"】已领取完,请联系活动负责人"+marketActivity.getManagerName()+"咨询情况");
            }
 
        }
 
        //处理参与记录--------------------------------------------------------------------------------
        if(StringUtils.isEmpty(joinRecord.getId())){
            if(commonService.insert(MarketActivityJoinRecordMapper.class, joinRecord) != 1){
                throw new TipsException("新增活动参与记录失败!");
            }
        }else{
            values.clear();
            values.put("id", joinRecord.getId());
            values.put("couponNum", list.size());
            sqlSentence.setSqlSentence(" couponNum = couponNum + #{m.couponNum}, receiveNum = receiveNum + 1, editTime = now() where id = #{m.id} ");
            if(commonService.updateWhere(MarketActivityJoinRecordMapper.class, sqlSentence) != 1){
                throw new TipsException("更新活动参与记录失败!");
            }
         }
 
        //处理领取记录---------------------------------------------------------------------------------
 
        receiveRecord.setJoinRecordId(joinRecord.getId());
        if(commonService.insert(MarketActivityReceiveRecordMapper.class, receiveRecord) != 1){
            throw new TipsException("新增领取记录失败1!");
        }
 
        //遍历新增子项
        for(MarketActivityReceiveRecordItem receiveRecordItem : recordItemList){
            receiveRecordItem.setReceiveRecordId(receiveRecord.getId());
            if(commonService.insert(MarketActivityReceiveRecordItemMapper.class, receiveRecordItem) != 1){
                throw new TipsException("新增领取记录失败2!");
            }
 
            //如果状态是待审核的,创建营销助手审批记录
//            if(receiveRecordItem.getApproveStatus() == MarketActivityReceiveRecordItem.APPROVE_STATUS_WAIT){
//                handleApprove(joinRecord, receiveRecord, receiveRecordItem);
//            }
        }
 
        //发送审批通知给活动负责人-------------------------------------------------------------------------------------
//        if(isApprove == BaseEntity.YES) {
            try {
                String empUserId;
                Shop shop = commonService.selectOneByKey(ShopMapper.class, receiveRecord.getOpShopId());
                //正式环境发给对应的负责人 测试服发给彭程
                if ("prod".equals(customParameter.getPlatformPattern())) {
                    //查询员工数据
                    Employee employee = commonService.selectOneByKey(EmployeeMapper.class, marketActivity.getManagerId());
                    if (employee == null) {
                        throw new TipsException("找不到活动负责人!");
                    }
                    empUserId = employee.getUserId();
                } else {
                    empUserId = "18023612893";
                }
 
                String sendDate = MessageTemplate.receiveCouponSendToManager(isApprove,empUserId, user.getName(), receiveRecord.getOpName(), shop.getName(), marketActivity.getTitle(), couponName, customParameter.getCorpMpAppId());
                log.info("小程序营销活动领取优惠券通知活动负责人,userId为:{}", empUserId);
                String token = WeiXinCorpMpUtil.getApplicationAccessToken(commonService, customParameter.getCorpAppId(), customParameter.getCorpMpSecret());
                SendMessageTool.sendMessge(sendDate, token);
            } catch (Exception e) {
                log.info("小程序用户营销活动发送通知失败");
                log.info(GlobalExceptionHandler.getExceptionInformation(e));
            }
//        }
        //-------------------------------------------------------------------------------------------
    }
 
    /** 更新查看记录 */
    @Override
    public void updateViewRecord(String marketActivityId, String platformType, User user) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> values = new HashMap<>();
        sqlSentence.setM(values);
        values.put("userId", user.getId());
        values.put("marketActivityId", marketActivityId);
        sqlSentence.setSqlSentence(" select id from market_activity_view_record where isDel = 0 and userId = #{m.userId} and marketActivityId = #{m.marketActivityId} ");
        Map<String, Object> map = commonService.selectOneMap(MarketActivityViewRecordMapper.class, sqlSentence);
        if(map != null && map.get("id") != null){
            //更新查看次数和时间
            values.clear();
            values.put("id", map.get("id"));
            sqlSentence.setSqlSentence(" viewNum = viewNum + 1, editTime = now() where id = #{m.id} ");
            if(commonService.updateWhere(MarketActivityViewRecordMapper.class, sqlSentence) != 1){
                throw new TipsException("更新营销活动查看记录的查看次数和时间失败!");
            }
        }else{
            //新增查看记录
            MarketActivityViewRecord viewRecord = new MarketActivityViewRecord();
            viewRecord.setMarketActivityId(marketActivityId);
            viewRecord.setPlatformType(platformType);
            viewRecord.setViewNum(1);
            //用户信息
            viewRecord.setUserId(user.getId());
            viewRecord.setUserName(user.getName());
            viewRecord.setCIQ(user.getCIQ());
            viewRecord.setUserLevel(user.getUserLevel());
            viewRecord.setUserStatus(user.getUserStatus());
            viewRecord.setUserConsultantId(user.getHisCorpUserId());
            viewRecord.setUserConsultantName(EmployeeTool.getCnName(viewRecord.getUserConsultantId(), commonService));
            viewRecord.setUserShopId(user.getShopId());
            viewRecord.setUserShopName(ShopTool.getShopName(viewRecord.getUserShopId(), commonService));
            if(commonService.insert(MarketActivityViewRecordMapper.class, viewRecord) != 1){
                throw new TipsException("新增营销活动查看记录失败!");
            }
        }
    }
 
 
    /** 营销助手审批回调处理 */
    @Override
    public void receiveApproveHandle(MarketActivityJoinRecord joinRecord, MarketActivityReceiveRecord receiveRecord
            , MarketActivityReceiveRecordItem recordItem) {
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> values = new HashMap<>();
        sqlSentence.setM(values);
 
        String result = "";
 
        //审批成功
        if(recordItem.getApproveStatus() == MarketActivityReceiveRecordItem.APPROVE_STATUS_SUC){
 
            //优惠券操作人类型,默认员工
            int couponOpType = OperatorConstants.changeCouponOpType(receiveRecord.getOpType());
 
            //拼接用户数据
            JSONArray userArr = new JSONArray();
            JSONObject json = new JSONObject();
            json.put("id", receiveRecord.getUserId());
            json.put("amount", 1);
            userArr.add(json);
 
            //发放优惠券
            try{
               sendCoupon(couponOpType, userArr, receiveRecord, recordItem);
            }catch (Exception e){
                log.error("参数:{}", JSONObject.fromObject(recordItem));
                log.error("营销助手审批回调处理,发放优惠券失败:{}", GlobalExceptionHandler.getExceptionInformation(e));
                //统一提示
                throw new TipsException("营销助手审批回调处理,发放优惠券失败," + e.getMessage());
            }
 
            //更新状态
            values.put("approveStatus", recordItem.getApproveStatus());
            values.put("approveRemark", recordItem.getApproveRemark());
            values.put("id", recordItem.getId());
            sqlSentence.setSqlSentence(" approveStatus = #{m.approveStatus}, approveRemark = #{m.approveRemark}, editTime = now() where id = #{m.id} ");
            if(commonService.updateWhere(MarketActivityReceiveRecordItemMapper.class, sqlSentence) != 1){
                throw new TipsException("更新领取记录审批状态失败!");
            }
            result = "通过";
        }
        //审批失败-------------------------------------------------------------------------------------
        else if(recordItem.getApproveStatus() == MarketActivityReceiveRecordItem.APPROVE_STATUS_FAIL){
            //更新状态和删除状态
            values.put("approveStatus", recordItem.getApproveStatus());
            values.put("approveRemark", recordItem.getApproveRemark());
            values.put("id", recordItem.getId());
            sqlSentence.setSqlSentence(" approveStatus = #{m.approveStatus}, approveRemark = #{m.approveRemark}, isDel = 2, editTime = now() where id = #{m.id} ");
            if(commonService.updateWhere(MarketActivityReceiveRecordItemMapper.class, sqlSentence) != 1){
                throw new TipsException("更新领取记录审批状态失败!");
            }
 
            //更新减少用户参与记录领取优惠券数量
            values.clear();
            values.put("couponNum", joinRecord.getCouponNum());
            values.put("id", joinRecord.getId());
            sqlSentence.setSqlSentence(" couponNum = couponNum - 1 where id = #{m.id} and couponNum = #{m.couponNum} ");
            if(commonService.updateWhere(MarketActivityJoinRecordMapper.class, sqlSentence) != 1){
                throw new TipsException("更新活动参与记录信息失败!");
            }
 
            result = "拒绝";
        }
 
        //发送审批结果通知-------------------------------------------------------------------------------------
        MarketActivity activity = commonService.selectOneByKey(MarketActivityMapper.class,receiveRecord.getMarketActivityId());
        if(activity == null){
            throw new TipsException("找不到活动!");
        }
 
        //查询员工数据
        String empUserId;
        //正式环境发给对应的 测试服发给彭程
        if("prod".equals(customParameter.getPlatformPattern())) {
            Employee employee = commonService.selectOneByKey(EmployeeMapper.class,receiveRecord.getOpId());
            if(employee == null){
                throw new TipsException("找不到活动负责人!");
            }
            empUserId = employee.getUserId();
        }else {
            empUserId = "18023612893";
        }
 
        String sendDate = MessageTemplate.receiveResultSendToAdvice(activity.getManagerName(), empUserId, activity.getTitle(), recordItem.getCommonName(),result, customParameter.getCorpMpAppId());
        log.info("小程序营销活动领取优惠券审核结果通知,userId为:{}", empUserId);
        String token = WeiXinCorpMpUtil.getApplicationAccessToken(commonService, customParameter.getCorpAppId(), customParameter.getCorpMpSecret());
        SendMessageTool.sendMessge(sendDate, token);
    }
 
    ///////////////////////////////////////////////////////////////////////////////
 
    /** 统一发送优惠券逻辑 */
    private void sendCoupon(Integer couponOpType, JSONArray userArr, MarketActivityReceiveRecord receiveRecord, MarketActivityReceiveRecordItem recordItem){
 
        Coupon coupon = commonService.selectOneByKeyBlob(CouponMapper.class, recordItem.getCommonId());
        if(coupon!=null && BaseEntity.YES==coupon.getIsBirthday()){
            for(int i=0;i<userArr.size();i++){
                JSONObject object = userArr.getJSONObject(i);
                object.put("startTime", DateUtil.formatDate_2(new Date()));
                object.put("endTime", DateUtil.formatDate_2(DateUtil.addMonth(new Date(),1)));
            }
        }
 
        CouponReleaseRecordItem couponReleaseRecordItem = new CouponReleaseRecordItem();
        couponReleaseRecordItem.setCouponId(recordItem.getCommonId());
        couponReleaseRecordItem.setCommonType(CouponReleaseRecordItem.TYPE_COMMON_MARKET_ACTIVITY);
        couponReleaseRecordItem.setCommonId(recordItem.getMarketActivityId());
        couponReleaseRecordItem.setCommonItemId(recordItem.getActivityItemId());
        couponReleaseRecordItem.setRecordName("门店助手热门活动领取");
        //调用方法优惠券方法
        CouponTool.sendCoupon(couponReleaseRecordItem, receiveRecord.getOpId(),receiveRecord.getOpName()
                , couponOpType,receiveRecord.getOpRoleId(),userArr
                , receiveRecord.getPlatformType(),commonService);
 
    }
 
    /** 处理营销助手申请 */
    private void handleApprove(MarketActivityJoinRecord joinRecord, MarketActivityReceiveRecord receiveRecord, MarketActivityReceiveRecordItem recordItem){
        MarketingTotalDto marketingTotalDto = new MarketingTotalDto();
        marketingTotalDto.setTitle(processBean.getMarcaTitle());
        marketingTotalDto.setTypeStr(processBean.getMarcaTypeStr());
        marketingTotalDto.setType(processBean.getMarcaWorkflowCode());
        marketingTotalDto.setUniqueId(recordItem.getId());
        marketingTotalDto.setOperatorId(receiveRecord.getOpId());
        marketingTotalDto.setOpName(receiveRecord.getOpName());
        marketingTotalDto.setShopId(receiveRecord.getOpShopId());
        marketingTotalDto.setShopName(CommonQueryUtil.getShopName(marketingTotalDto.getShopId(), commonService));
        marketingTotalDto.setRoleId(CommonQueryUtil.getEmployeeRoleTypeId(receiveRecord.getOpRoleStr(), commonService));
        marketingTotalDto.setRoleUniqueStr(receiveRecord.getOpRoleStr());
        marketingTotalDto.setUserId(receiveRecord.getUserId());
        marketingTotalDto.setRemark("领取申请");
        marketingTotalDto.setCallbackUrl(processBean.getMarcaNotifyUrl());
 
        //---审核信息组拼
        MarketingContentDto marketingContentDto = new MarketingContentDto();
        List<MarketingMsgItemDto> contentList = new ArrayList<>();
 
        MarketingMsgItemDto marketingMsgItemDto = new MarketingMsgItemDto();
        marketingMsgItemDto.setKey("审核类型");
        marketingMsgItemDto.setValue("营销活动领取优惠券");
        contentList.add(marketingMsgItemDto);
 
        marketingMsgItemDto = new MarketingMsgItemDto();
        marketingMsgItemDto.setKey("优惠券");
        marketingMsgItemDto.setValue(recordItem.getCommonName());
        contentList.add(marketingMsgItemDto);
 
        marketingContentDto.setContentList(contentList);
        marketingTotalDto.setMarketingContentDto(marketingContentDto);
        //审核信息组拼结束
 
        //---企业微信信息组拼
        MarketingMsgDto marketingMsgDto = new MarketingMsgDto();
        marketingMsgDto.setEmphasisFirstItem(true);
        List<MarketingMsgItemDto> contentItem = new ArrayList<>();
        contentItem.addAll(contentList);
        marketingMsgDto.setContentItem(contentItem);
        marketingTotalDto.setMarketingMsgDto(marketingMsgDto);
        //---企业微信信息结束
 
        log.info("请求创建审批记录参数:{}", com.alibaba.fastjson.JSONObject.toJSONString(marketingTotalDto));
        Result result =  mCommonService.commonApply(marketingTotalDto);
        log.info("请求创建审批记录返回结果:{}", com.alibaba.fastjson.JSONObject.toJSONString(result));
        if(!result.checkCode()){
            log.info("领取优惠券失败,新增领取审批记录失败,返回结果:{}", JSONObject.fromObject(result));
            throw new TipsException("领取优惠券失败,新增领取审批记录失败!");
        }
 
        //获取返回值,判断是否直接审核通过
        MarketingResultDto marketingResultDto = result.getObject(result.getData(),MarketingResultDto.class);
        if(marketingResultDto == null){
            throw new TipsException("创建审批记录返回信息为空!");
        }
 
        //如果这里发券失败,目前会对应记录都没有创建,但是营销助手会有一条记录的情况
        if(marketingResultDto != null && marketingResultDto.getIsPass() == 1){
            recordItem.setApproveStatus(MarketActivityReceiveRecordItem.APPROVE_STATUS_SUC);
            recordItem.setApproveRemark("审批直接通过");
            receiveApproveHandle(joinRecord, receiveRecord, recordItem);
        }
 
    }
 
 
}