Jelajahi Sumber

Merge remote-tracking branch 'origin/master'

zhujing 2 minggu lalu
induk
melakukan
67da7aa6bd

+ 5 - 0
java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/entity/MarketingCampaignSopDetailEntity.java

@@ -56,4 +56,9 @@ public class MarketingCampaignSopDetailEntity extends SysBaseField implements Se
     @ApiModelProperty(value = "SOP步骤执行状态(不写库,0未开始/1进行中/2已完成,由关联邮件发送状态判断)")
     @TableField(exist = false)
     private Integer sopStatus;
+
+    @ApiModelProperty(value = "主题模板")
+    @TableField("email_subject")
+    private String emailSubject;
+
 }

+ 83 - 5
java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/service/impl/MarketEmailsServiceImpl.java

@@ -1536,7 +1536,7 @@ public class MarketEmailsServiceImpl extends MyBaseServiceImpl<MarketEmailsMappe
         List<Long> marketingCampaignIdListWithReplyStop = marketingCampaignListWithReplyStop.stream().map(MarketingCampaignEntity::getId).collect(Collectors.toList());
         //查询已经有回复的客户
         LambdaQueryWrapper<MarketEmailsEntity> queryStopWrapper = new LambdaQueryWrapper<>();
-        queryStopWrapper.in(MarketEmailsEntity::getMarketingCampaignId, marketingCampaignIdListWithReplyStop);
+//        queryStopWrapper.in(MarketEmailsEntity::getMarketingCampaignId, marketingCampaignIdListWithReplyStop);
         queryStopWrapper.eq(MarketEmailsEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
         queryStopWrapper.eq(MarketEmailsEntity::getHasReply, 1);
         queryStopWrapper.eq(MarketEmailsEntity::getHasReader, 1);
@@ -1683,6 +1683,28 @@ public class MarketEmailsServiceImpl extends MyBaseServiceImpl<MarketEmailsMappe
         if (CollectionUtils.isEmpty(marketingCampaignList)){
             return;
         }
+        // ===== 客户级防护:一次性查出「任何营销活动中」存在已回复邮件的客户 / 收件人 =====
+        // 需求:只要某个客户在任意营销活动里有回复过的邮件,就不再给它生成二次发送邮件。
+        // 这里跑一次全量去重查询,后续生成二次发送时按 customerId / recipient 命中即跳过,
+        // 避免对已回复客户继续打扰(即便其所属营销活动未配置「回复后停止」)。
+        Set<Long> repliedCustomerIds = new HashSet<>();
+        Set<String> repliedRecipients = new HashSet<>();
+        {
+            LambdaQueryWrapper<MarketEmailsEntity> replyQuery = new LambdaQueryWrapper<>();
+            replyQuery.select(MarketEmailsEntity::getCustomerId, MarketEmailsEntity::getRecipient)
+                    .eq(MarketEmailsEntity::getIsDelete, CommonConstant.DEL_FLAG_0)
+                    .eq(MarketEmailsEntity::getHasReply, 1);
+            List<MarketEmailsEntity> repliedEmails = this.list(replyQuery);
+            for (MarketEmailsEntity replied : repliedEmails) {
+                if (replied.getCustomerId() != null) {
+                    repliedCustomerIds.add(replied.getCustomerId());
+                }
+                String r = replied.getRecipient();
+                if (r != null && !r.isEmpty()) {
+                    repliedRecipients.add(r);
+                }
+            }
+        }
         for (MarketingCampaignEntity marketingCampaignEntity : marketingCampaignList) {
             if (marketingCampaignEntity.getId().equals(43L)){
                 log.info("测试");
@@ -1716,15 +1738,35 @@ public class MarketEmailsServiceImpl extends MyBaseServiceImpl<MarketEmailsMappe
             log.info("marketEmailList: {}", marketEmailList);
 
             List<MarketEmailsEntity> newMarketEmailList = new ArrayList<>();
+            // 进程内去重:防止同一封首邮件在本次循环中(或被多次加入)被加两次
+            Set<Long> pendingFirstSendIds = new HashSet<>();
             //新增一条需要发送的邮件记录
             for (MarketEmailsEntity marketEmail : marketEmailList){
-                //如果marketEmail.getId()不在marketEmailHasFirstIdList中
-                if (marketEmailHasFirstIdList.contains(marketEmail.getId())) {
+                Long firstId = marketEmail.getId();
+                // 跳过:① 运行开始时已存在 follow-up 的;② 本次批次内已经加过一遍的(防同批重复)
+                if (firstId == null
+                        || marketEmailHasFirstIdList.contains(firstId)
+                        || pendingFirstSendIds.contains(firstId)) {
+                    continue;
+                }
+                // 客户级防护:该客户(customerId)或收件人(recipient)在任何营销活动中存在已回复邮件,
+                // 则不生成二次发送。命中即跳过,避免对已回复客户继续打扰。
+                Long cid = marketEmail.getCustomerId();
+                String recipient = marketEmail.getRecipient();
+                if ((cid != null && repliedCustomerIds.contains(cid))
+                        || (recipient != null && !recipient.isEmpty() && repliedRecipients.contains(recipient))) {
+                    log.info("[sendAgain] 客户已在任意营销活动中回复过,跳过二次发送:customerId={}, recipient={}, firstSendId={}",
+                            cid, recipient, firstId);
                     continue;
                 }
                 MarketEmailsEntity newMarketEmail = new MarketEmailsEntity();
                 BeanUtils.copyProperties(marketEmail, newMarketEmail);
-                newMarketEmail.setFirstSendId(marketEmail.getId());
+                // 注意:copyProperties 会把首邮件的 createTime/updateTime 也拷过来(非空),
+                // 导致 MyBatis-Plus 的自动填充被跳过,second 邮件的创建/更新时间变成首邮件的时间。
+                // 这里主动置空,交给自动填充写入真正的当前时间;若自动填充未生效,下方再兜底设值。
+                newMarketEmail.setCreateTime(null);
+                newMarketEmail.setUpdateTime(null);
+                newMarketEmail.setFirstSendId(firstId);
                 newMarketEmail.setId(null);
                 newMarketEmail.setEmailId(null);
                 newMarketEmail.setStatus(-1);
@@ -1737,9 +1779,45 @@ public class MarketEmailsServiceImpl extends MyBaseServiceImpl<MarketEmailsMappe
                 newMarketEmail.setHasReply(0);
 
                 newMarketEmailList.add(newMarketEmail);
+                pendingFirstSendIds.add(firstId);
             }
             if (!CollectionUtils.isEmpty(newMarketEmailList)){
-                this.saveBatch(newMarketEmailList);
+                // 二次去重(防并发 / 多实例):运行期间(含其它实例)可能已经插入了这些首邮件的 follow-up,
+                // 再查一次 DB,把已经存在的 first_send_id 过滤掉,彻底避免同一封首邮件生成两条 second。
+                // (之前 109 / 113 各被生成两条,就是两个 doSendAgain 并发、彼此没看到对方插入导致的)
+                List<Long> candidateFirstIds = newMarketEmailList.stream()
+                        .map(MarketEmailsEntity::getFirstSendId)
+                        .filter(Objects::nonNull)
+                        .collect(Collectors.toList());
+                if (!candidateFirstIds.isEmpty()) {
+                    LambdaQueryWrapper<MarketEmailsEntity> existQuery = new LambdaQueryWrapper<>();
+                    existQuery.eq(MarketEmailsEntity::getIsDelete, CommonConstant.DEL_FLAG_0)
+                            .eq(MarketEmailsEntity::getHasFirst, 2)
+                            .in(MarketEmailsEntity::getFirstSendId, candidateFirstIds);
+                    Set<Long> alreadyExistIds = this.list(existQuery).stream()
+                            .map(MarketEmailsEntity::getFirstSendId)
+                            .filter(Objects::nonNull)
+                            .collect(Collectors.toSet());
+                    if (!alreadyExistIds.isEmpty()) {
+                        newMarketEmailList = newMarketEmailList.stream()
+                                .filter(e -> !alreadyExistIds.contains(e.getFirstSendId()))
+                                .collect(Collectors.toList());
+                    }
+                }
+                if (!CollectionUtils.isEmpty(newMarketEmailList)){
+                    // 逐条插入 + 单条容错:多个应用实例并发跑 sendAgain 时,即使已经加了唯一索引
+                    // uq_second_first_send(first_send_id, has_first),仍可能因竞态让同一条 follow-up 被两个实例
+                    // 同时插入。逐条插入可以保证「一条重复键失败」不会把同批次里其它合法的 follow-up 也拖垮
+                    // (批量 insert 在多值语句下任一行的唯一约束冲突会导致整批失败)。重复键异常被静默吞掉即可。
+                    for (MarketEmailsEntity newEmail : newMarketEmailList) {
+                        try {
+                            this.save(newEmail);
+                        } catch (Exception ex) {
+                            log.warn("[sendAgain] 插入 follow-up 邮件失败(可能为并发重复键,已被唯一索引拦截,可忽略):firstSendId={}, err={}",
+                                    newEmail.getFirstSendId(), ex.getMessage());
+                        }
+                    }
+                }
             }
 
         }

+ 12 - 0
java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/service/impl/MarketingCampaignServiceImpl.java

@@ -73,6 +73,7 @@ public class MarketingCampaignServiceImpl
         IPage<MarketingCampaignEntity> page = new Page<>(marketingCampaignDTO.getPageIndex(), marketingCampaignDTO.getPageSize());
         LambdaQueryWrapper<MarketingCampaignEntity> queryWrapper = new LambdaQueryWrapper<>();
         queryWrapper.eq(MarketingCampaignEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
+        queryWrapper.orderByDesc(MarketingCampaignEntity::getCreateTime);
         IPage<MarketingCampaignEntity> pageList = this.page(page, queryWrapper);
         if (CollectionUtils.isEmpty(pageList.getRecords())){
             return Result.result(pageVO);
@@ -581,6 +582,17 @@ public class MarketingCampaignServiceImpl
         if (entity == null || CommonConstant.DEL_FLAG_1.equals(entity.getIsDelete())) {
             return Result.error("营销活动不存在");
         }
+        //如果要开启营销活动,需要先生成邮件模板(即存在待发送的邮件)
+        if (status == STATUS_RUNNING) {
+            LambdaQueryWrapper<MarketEmailsEntity> queryWrapper = new LambdaQueryWrapper<>();
+            queryWrapper.eq(MarketEmailsEntity::getMarketingCampaignId, id);
+            queryWrapper.eq(MarketEmailsEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
+            queryWrapper.eq(MarketEmailsEntity::getStatus, -1);
+            Integer emailsCount = marketEmailsService.count(queryWrapper);
+            if (emailsCount == null || emailsCount <= 0) {
+                return Result.error("请于创建/修改20分钟后,且完成邮件模板配置启动营销!");
+            }
+        }
         entity.setStatus(status);
         this.updateById(entity);
         return Result.ok();