Jelajahi Sumber

Merge remote-tracking branch 'origin/master_rule_engine' into master_rule_engine

# Conflicts:
#	jeecg-boot-module-system/src/test/java/org/jeecg/SampleTest.java
syh 4 tahun lalu
induk
melakukan
3819ba50ce
18 mengubah file dengan 861 tambahan dan 247 penghapusan
  1. 151 59
      module-alarm/src/main/java/cn/com/ctop/alarm/modules/constant/MatchLogic.java
  2. 51 0
      module-alarm/src/main/java/cn/com/ctop/alarm/modules/controller/RuleAccountTemplateController.java
  3. 6 3
      module-alarm/src/main/java/cn/com/ctop/alarm/modules/controller/RuleGroupController.java
  4. 24 0
      module-alarm/src/main/java/cn/com/ctop/alarm/modules/controller/RuleTemplateController.java
  5. 2 0
      module-alarm/src/main/java/cn/com/ctop/alarm/modules/entity/RuleBase.java
  6. 5 0
      module-alarm/src/main/java/cn/com/ctop/alarm/modules/entity/RuleGroup.java
  7. 90 0
      module-alarm/src/main/java/cn/com/ctop/alarm/modules/entity/vo/TemplateAppliedVo.java
  8. 3 0
      module-alarm/src/main/java/cn/com/ctop/alarm/modules/mapper/RuleAccountTemplateMapper.java
  9. 42 0
      module-alarm/src/main/java/cn/com/ctop/alarm/modules/mapper/xml/RuleAccountTemplateMapper.xml
  10. 7 0
      module-alarm/src/main/java/cn/com/ctop/alarm/modules/service/IRuleAccountTemplateService.java
  11. 2 0
      module-alarm/src/main/java/cn/com/ctop/alarm/modules/service/IRuleTemplateService.java
  12. 14 0
      module-alarm/src/main/java/cn/com/ctop/alarm/modules/service/impl/RuleAccountTemplateServiceImpl.java
  13. 199 77
      module-alarm/src/main/java/cn/com/ctop/alarm/modules/service/impl/RuleGroupServiceImpl.java
  14. 108 10
      module-alarm/src/main/java/cn/com/ctop/alarm/modules/service/impl/RuleTemplateServiceImpl.java
  15. 112 96
      module-common/src/main/java/cn/com/ctop/common/module/mapper/SysUserMapper.java
  16. 7 0
      module-common/src/main/java/cn/com/ctop/common/module/mapper/xml/SysUserMapper.xml
  17. 3 1
      module-common/src/main/java/cn/com/ctop/common/module/service/IRuleDataAccountService.java
  18. 35 1
      module-common/src/main/java/cn/com/ctop/common/module/service/impl/RuleDataAccountServiceImpl.java

+ 151 - 59
module-alarm/src/main/java/cn/com/ctop/alarm/modules/constant/MatchLogic.java

@@ -1,10 +1,14 @@
 package cn.com.ctop.alarm.modules.constant;
 
-import cn.com.ctop.alarm.modules.entity.AlarmEventRule;
+import cn.com.ctop.alarm.modules.entity.RuleGroup;
+import cn.com.ctop.common.module.utils.Check;
+import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
 import lombok.extern.slf4j.Slf4j;
 
 import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.List;
 
 /**
  * TODO
@@ -26,55 +30,64 @@ public class MatchLogic {
      * @author ZHAOXA
      */
     public static boolean matchCondition(String type, String condition, String threshold, String value) {
-        if ("number".equals(type)) {
-            BigDecimal bigThr = new BigDecimal(threshold);
-            BigDecimal bigVal = new BigDecimal(value);
-            switch (condition) {
-                case "equal":
-                    return bigVal.compareTo(bigThr) == 0;
-                case "not_equal":
-                    return bigVal.compareTo(bigThr) != 0;
-                case "greater":
-                    return bigVal.compareTo(bigThr) > 0;
-                case "less":
-                    return bigVal.compareTo(bigThr) < 0;
-                case "greater_equal":
-                    return bigVal.compareTo(bigThr) >= 0;
-                case "less_equal":
-                    return bigVal.compareTo(bigThr) <= 0;
-                default:
-                    log.warn("关系不匹配");
-                    break;
-            }
-        } else if ("string".equals(type)) {
-            switch (condition) {
-                case "equal":
-                    return value.equals(threshold);
-                case "not_equal":
-                    return !value.equals(threshold);
-                case "contain":
-                    return !value.contains(threshold);
-                case "no_contain":
-                    return !value.contains(threshold);
-                default:
-                    log.warn("关系不匹配");
-                    break;
-            }
-        } else {
-            String[] strings = threshold.split(",");
-            if ("contain".equals(condition)) {
-                for (String string : strings) {
-                    if (value.contains(string)) {
-                        return true;
-                    }
+        try {
+            if ("number".equals(type)) {
+                BigDecimal bigThr = new BigDecimal(threshold);
+                BigDecimal bigVal = new BigDecimal(value);
+                switch (condition) {
+                    case "equal":
+                        return bigVal.compareTo(bigThr) == 0;
+                    case "not_equal":
+                        return bigVal.compareTo(bigThr) != 0;
+                    case "greater":
+                        return bigVal.compareTo(bigThr) > 0;
+                    case "less":
+                        return bigVal.compareTo(bigThr) < 0;
+                    case "greater_equal":
+                        return bigVal.compareTo(bigThr) >= 0;
+                    case "less_equal":
+                        return bigVal.compareTo(bigThr) <= 0;
+                    default:
+                        log.warn("关系不匹配");
+                        break;
+                }
+            } else if ("string".equals(type)) {
+                switch (condition) {
+                    case "equal":
+                        return value.equals(threshold);
+                    case "not_equal":
+                        return !value.equals(threshold);
+                    case "contain":
+                        return !value.contains(threshold);
+                    case "no_contain":
+                        return !value.contains(threshold);
+                    default:
+                        log.warn("关系不匹配");
+                        break;
                 }
             } else {
-                for (String string : strings) {
-                    if (!value.contains(string)) {
-                        return true;
+                List<String> thresholdArr = strToList(threshold);
+                List<String> values = strToList(value);
+                if ("contain".equals(condition)) {
+                    for (String t : thresholdArr) {
+                        for (String v : values) {
+                            if (v.contains(t)) {
+                                return true;
+                            }
+                        }
+                    }
+                } else {
+                    for (String t : thresholdArr) {
+                        for (String v : values) {
+                            if (!v.contains(t)) {
+                                return true;
+                            }
+                        }
                     }
                 }
             }
+        } catch (Exception e) {
+            log.error("条件匹配", e);
         }
         return false;
     }
@@ -82,26 +95,105 @@ public class MatchLogic {
     /**
      * 整理发送的消息
      */
-    public static String getMsg(String level, String detail, JSONObject cost, AlarmEventRule rule) {
+    public static String getMsg(RuleGroup ruleGroup, JSONObject user, Long accountId, Long planId, Long creativeId, boolean isPause) {
         StringBuffer header = new StringBuffer();
-        header.append(rule.getMetricValueName()).append("预警").append("<br/>").
-                append("您的账户:").append(cost.getString("accountId")).append(",授权名称为:").append(rule.getAccountName()).append("<br/>");
-        if ("ACCOUNT".equals(level)) {
-            header.append(detail);
-        } else if ("CAMPAIGN".equals(level)) {
-            header.append("计划ID:").append(rule.getCampaignId()).append(",计划名称为:").append(rule.getCampaignName()).append("<br/>").append(detail);
-        } else {
-            header.append("计划ID:").append(rule.getCampaignId()).append(",计划名称为:").append(rule.getCampaignName()).append("<br/>")
-                    .append("组ID:").append(rule.getUnitId()).append(",组名称为:").append(rule.getUnitName()).append("<br/>").append(detail);
+        header.append(ruleGroup.getGroupName()).append("预警").append("<br/>").
+                append("预警账户:").append(accountId).append("<br/>");
+        if (!Check.isNull(planId) && !Check.isNull(creativeId)) {
+            header.append("预警计划:").append(planId).append("<br/>").append("预警创意:").append(creativeId).append("<br/>");
+        } else if (!Check.isNull(creativeId) && Check.isNull(creativeId)) {
+            header.append("预警计划:").append(planId).append("<br/>");
+        } else if (!Check.isNull(creativeId)) {
+            header.append("预警创意:").append(creativeId).append("<br/>");
         }
-        String msg = null;
-        if ("PAUSE".equals(rule.getProcessMethod())) {
+        if (isPause) {
             header.append("现已被关停,请您及时查看并调整!");
         } else {
             header.append("请您及时查看并调整!");
-            msg = header.toString();
         }
-        return msg;
+        return header.toString();
+    }
+
+    //拆分逗号拼接数据
+    public static List<String> strToList(String strings) {
+        List<String> ids = null;
+        try {
+            if (Check.isNull(strings)) {
+                return null;
+            }
+            JSONObject job = new JSONObject();
+            job.put("list", strings);
+            ids = new ArrayList<>();
+            JSONArray idList = job.getJSONArray("list");
+            for (Object id : idList) {
+                ids.add(String.valueOf(id));
+            }
+        } catch (Exception e) {
+            log.error("ids格式转换异常", e);
+        }
+        return ids;
+    }
+
+    public static JSONArray getSendData(JSONArray accountDatas, JSONArray planDatas, JSONArray creativeDatas, JSONArray targetDatas) {
+        JSONArray sendData = new JSONArray();
+        if (!Check.isNull(accountDatas) && Check.isNull(planDatas) && Check.isNull(creativeDatas) && Check.isNull(targetDatas)) {
+            sendData = accountDatas;
+        } else {
+            if (!Check.isNull(planDatas) && Check.isNull(creativeDatas) && Check.isNull(targetDatas)) {
+                sendData = planDatas;
+            } else if (!Check.isNull(creativeDatas) && Check.isNull(planDatas) && Check.isNull(targetDatas)) {
+                sendData = creativeDatas;
+            } else if (!Check.isNull(targetDatas) && Check.isNull(planDatas) && Check.isNull(creativeDatas)) {
+                sendData = targetDatas;
+            } else if (!Check.isNull(planDatas) && !Check.isNull(creativeDatas) && !Check.isNull(targetDatas)) {
+                for (int i = 0; i < planDatas.size(); i++) {
+                    Long pplanId = planDatas.getJSONObject(i).getLong("planId");
+                    for (int k = 0; k < targetDatas.size(); k++) {
+                        Long tplanId = targetDatas.getJSONObject(k).getLong("planId");
+                        for (int j = 0; j < creativeDatas.size(); j++) {
+                            Long cplanId = creativeDatas.getJSONObject(j).getLong("planId");
+                            if (cplanId == tplanId && cplanId == pplanId) {
+                                sendData.add(creativeDatas.getJSONObject(j));
+                            }
+                        }
+                    }
+                }
+            } else if (!Check.isNull(planDatas) && !Check.isNull(targetDatas) && Check.isNull(creativeDatas)) {
+                for (int i = 0; i < planDatas.size(); i++) {
+                    Long pplanId = planDatas.getJSONObject(i).getLong("planId");
+                    for (int k = 0; k < targetDatas.size(); k++) {
+                        Long tplanId = targetDatas.getJSONObject(k).getLong("planId");
+                        if (tplanId == pplanId) {
+                            sendData.add(targetDatas.getJSONObject(k));
+                        }
+                    }
+                }
+            } else if (!Check.isNull(planDatas) && Check.isNull(targetDatas) && !Check.isNull(creativeDatas)) {
+                for (int i = 0; i < planDatas.size(); i++) {
+                    Long pplanId = planDatas.getJSONObject(i).getLong("planId");
+                    for (int k = 0; k < creativeDatas.size(); k++) {
+                        Long cplanId = creativeDatas.getJSONObject(k).getLong("planId");
+                        if (cplanId == pplanId) {
+                            sendData.add(creativeDatas.getJSONObject(k));
+                        }
+                    }
+                }
+            } else if (Check.isNull(planDatas) && !Check.isNull(targetDatas) && !Check.isNull(creativeDatas)) {
+                for (int i = 0; i < targetDatas.size(); i++) {
+                    Long tplanId = targetDatas.getJSONObject(i).getLong("planId");
+                    for (int k = 0; k < creativeDatas.size(); k++) {
+                        Long cplanId = creativeDatas.getJSONObject(k).getLong("planId");
+                        if (cplanId == tplanId) {
+                            sendData.add(creativeDatas.getJSONObject(k));
+                        }
+                    }
+                }
+            }
+        }
+        return sendData;
+
+
     }
 
+
 }

+ 51 - 0
module-alarm/src/main/java/cn/com/ctop/alarm/modules/controller/RuleAccountTemplateController.java

@@ -2,21 +2,27 @@ package cn.com.ctop.alarm.modules.controller;
 
 import cn.com.ctop.alarm.modules.entity.RuleAccountTemplate;
 import cn.com.ctop.alarm.modules.entity.RuleTemplate;
+import cn.com.ctop.alarm.modules.entity.vo.TemplateAppliedVo;
 import cn.com.ctop.alarm.modules.service.IRuleAccountTemplateService;
 import cn.com.ctop.alarm.modules.service.IRuleAccountThresholdService;
 import cn.com.ctop.alarm.modules.service.IRuleTemplateService;
 import cn.com.ctop.common.module.annotation.AutoLog;
+import cn.com.ctop.common.module.service.ISysRoleExtService;
 import cn.com.ctop.common.module.utils.Check;
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.baomidou.mybatisplus.core.metadata.IPage;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.github.pagehelper.PageHelper;
+import com.github.pagehelper.PageInfo;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.shiro.SecurityUtils;
 import org.jeecg.common.api.vo.Result;
 import org.jeecg.common.system.query.QueryGenerator;
+import org.jeecg.common.system.vo.LoginUser;
 import org.jeecg.common.util.oConvertUtils;
 import org.jeecgframework.poi.excel.ExcelImportUtil;
 import org.jeecgframework.poi.excel.def.NormalExcelConstants;
@@ -58,6 +64,51 @@ public class RuleAccountTemplateController {
     @Autowired
     private IRuleAccountThresholdService accountThresholdService;
 
+    @Autowired
+    private ISysRoleExtService sysRoleService;
+
+    /**
+     * 查询账户下关联的模板
+     *
+     * @param page
+     * @param pageSize
+     * @return
+     */
+    @GetMapping(value = "/getTemplateApplied")
+    public Result<PageInfo<TemplateAppliedVo>> getTemplateApplied(int page, int pageSize, Long accountId, String projectName, String userName) {
+        Result<PageInfo<TemplateAppliedVo>> result = new Result<>();
+        try {
+            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
+            String roleCode = sysRoleService.getRoleCodeByUserId(sysUser.getId());
+            Map<String, Object> requestMap = new JSONObject();
+            if (!"admin".equals(roleCode)) {
+                requestMap.put("userId", sysUser.getId());
+            }
+            if (!Check.isNull(accountId)) {
+                requestMap.put("accountId", accountId);
+            }
+
+            if (!Check.isNull(projectName)) {
+                requestMap.put("projectName", projectName);
+            }
+            if (!Check.isNull(userName)) {
+                requestMap.put("userName", userName);
+            }
+            PageHelper.startPage(page, pageSize);
+            List<TemplateAppliedVo> list = ruleAccountTemplateService.getTemplateApplied(requestMap);
+
+            PageInfo<TemplateAppliedVo> pageInfo = new PageInfo<>(list);
+            result.setSuccess(true);
+            result.setResult(pageInfo);
+        } catch (Exception e) {
+            e.printStackTrace();
+            result.setSuccess(false);
+            result.setMessage(e.getMessage());
+        }
+        return result;
+    }
+
+
     @GetMapping(value = "/checkAccountTemplate")
     public Result<JSONObject> checkAccountTemplate(Long accountId) {
         Result<JSONObject> result = new Result<>();

+ 6 - 3
module-alarm/src/main/java/cn/com/ctop/alarm/modules/controller/RuleGroupController.java

@@ -116,27 +116,30 @@ public class RuleGroupController {
                 Long templateId = ruleGroup.getTemplateId();
                 RuleTemplate ruleTemplate = ruleTemplateService.getById(templateId);
                 if (!Check.isNull(ruleTemplate)) {
+                    JSONArray newGroupIds = new JSONArray();
                     JSONArray groupIds = JSONArray.parseArray(ruleTemplate.getGroupIds());
                     Iterator<Object> o = groupIds.iterator();
                     while (o.hasNext()) {
-                        System.err.println(o.next());
                         String groupId = String.valueOf(o.next());
                         if (groupId.equals(id)) {
-                            o.remove();
+                            continue;
                         }
+                        newGroupIds.add(Long.valueOf(groupId));
                     }
-                    ruleTemplate.setGroupIds(groupIds.toJSONString());
+                    ruleTemplate.setGroupIds(newGroupIds.toJSONString());
                     ruleTemplateService.updateById(ruleTemplate);
                 }
                 ruleGroupService.removeById(id);
             }
         } catch (Exception e) {
+            e.printStackTrace();
             log.error("删除失败", e.getMessage());
             return Result.error("删除失败!");
         }
         return Result.ok("删除成功!");
     }
 
+
     /**
      * 分页列表查询
      *

+ 24 - 0
module-alarm/src/main/java/cn/com/ctop/alarm/modules/controller/RuleTemplateController.java

@@ -88,6 +88,30 @@ public class RuleTemplateController {
 
 
     /**
+     * 根据 模板id  账户id 查询详情
+     *
+     * @param
+     * @return
+     */
+
+    @GetMapping(value = "/queryDetailByAccountIdAndTemplateId")
+    public Result<JSONObject> queryDetailByAccountIdAndTemplateId(Long accountId, Long templateId) {
+        Result<JSONObject> result = new Result<>();
+        try {
+            JSONObject ruleTemplateJson = ruleTemplateService.queryDetailByAccountIdAndTemplateId(accountId, templateId);
+            result.setSuccess(true);
+            result.setResult(ruleTemplateJson);
+        } catch (Exception e) {
+            e.printStackTrace();
+            result.setSuccess(false);
+            result.setMessage(e.getMessage());
+        }
+
+        return result;
+    }
+
+
+    /**
      * 分页列表查询
      *
      * @param ruleTemplate

+ 2 - 0
module-alarm/src/main/java/cn/com/ctop/alarm/modules/entity/RuleBase.java

@@ -67,6 +67,8 @@ public class RuleBase {
     private String ruleDimension;
 
     private Integer variableType;// 变量类型
+    private Integer judgeFormat;// 判断类型
+    private Integer isUnlimited;//  是否支持不限  true 是 false 否
 
     /**
      * createTime

+ 5 - 0
module-alarm/src/main/java/cn/com/ctop/alarm/modules/entity/RuleGroup.java

@@ -67,6 +67,11 @@ public class RuleGroup {
      * 规则解释
      */
     private String remark;
+
+
+    private Integer isRequired;//  是否必填  true 是 false 否
+    private Integer isCopy;//  是否可复制  true 是 false 否
+
     /**
      * createTime
      */

+ 90 - 0
module-alarm/src/main/java/cn/com/ctop/alarm/modules/entity/vo/TemplateAppliedVo.java

@@ -0,0 +1,90 @@
+package cn.com.ctop.alarm.modules.entity.vo;
+
+public class TemplateAppliedVo {
+    private Long accountId;
+    private String authName;
+    private Long templateId;
+    private String templateName;
+    private Long projectId;
+    private String projectName;
+    private String userId;
+    private String userName;
+
+    public Long getAccountId() {
+        return accountId;
+    }
+
+    public void setAccountId(Long accountId) {
+        this.accountId = accountId;
+    }
+
+    public String getAuthName() {
+        return authName;
+    }
+
+    public void setAuthName(String authName) {
+        this.authName = authName;
+    }
+
+    public Long getTemplateId() {
+        return templateId;
+    }
+
+    public void setTemplateId(Long templateId) {
+        this.templateId = templateId;
+    }
+
+    public String getTemplateName() {
+        return templateName;
+    }
+
+    public void setTemplateName(String templateName) {
+        this.templateName = templateName;
+    }
+
+    public Long getProjectId() {
+        return projectId;
+    }
+
+    public void setProjectId(Long projectId) {
+        this.projectId = projectId;
+    }
+
+    public String getProjectName() {
+        return projectName;
+    }
+
+    public void setProjectName(String projectName) {
+        this.projectName = projectName;
+    }
+
+    public String getUserId() {
+        return userId;
+    }
+
+    public void setUserId(String userId) {
+        this.userId = userId;
+    }
+
+    public String getUserName() {
+        return userName;
+    }
+
+    public void setUserName(String userName) {
+        this.userName = userName;
+    }
+
+    @Override
+    public String toString() {
+        return "TemplateAppliedVo{" +
+                "accountId=" + accountId +
+                ", authName='" + authName + '\'' +
+                ", templateId=" + templateId +
+                ", templateName='" + templateName + '\'' +
+                ", projectId=" + projectId +
+                ", projectName='" + projectName + '\'' +
+                ", userId='" + userId + '\'' +
+                ", userName='" + userName + '\'' +
+                '}';
+    }
+}

+ 3 - 0
module-alarm/src/main/java/cn/com/ctop/alarm/modules/mapper/RuleAccountTemplateMapper.java

@@ -1,7 +1,9 @@
 package cn.com.ctop.alarm.modules.mapper;
 
 import java.util.List;
+import java.util.Map;
 
+import cn.com.ctop.alarm.modules.entity.vo.TemplateAppliedVo;
 import org.apache.ibatis.annotations.Param;
 import cn.com.ctop.alarm.modules.entity.RuleAccountTemplate;
 import com.baomidou.mybatisplus.core.mapper.BaseMapper;
@@ -14,4 +16,5 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  */
 public interface RuleAccountTemplateMapper extends BaseMapper<RuleAccountTemplate> {
 
+    List<TemplateAppliedVo> getTemplateApplied(@Param("params") Map<String, Object> requestMap);
 }

+ 42 - 0
module-alarm/src/main/java/cn/com/ctop/alarm/modules/mapper/xml/RuleAccountTemplateMapper.xml

@@ -2,4 +2,46 @@
 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 <mapper namespace="cn.com.ctop.alarm.modules.mapper.RuleAccountTemplateMapper">
 
+    <select id="getTemplateApplied" parameterType="Map"
+            resultType="cn.com.ctop.alarm.modules.entity.vo.TemplateAppliedVo">
+        t1.account_id accountId,SELECT
+        t2.auth_name autnName,
+        t1.template_id templateId,
+        (
+        SELECT
+        template_name
+        FROM
+        ctop_rule_template
+        WHERE
+        id = t1.template_id
+        ) templateName,
+        t3.id projectId,
+        t3.project_name projectName,
+        t2.user_id userId,
+        t4.realname userName
+        FROM
+        ctop_rule_account_template t1
+        LEFT JOIN ctop_user_allocation t2 ON t1.account_id = t2.account_id
+        LEFT JOIN ctop_project t3 ON t2.project_id = t3.id
+        left sys_user t4 on t2.user_id = t4.id
+        where 1 = 1
+        <if test="params.userId !=null and params.userId !='' ">
+            and t2.user_id = #{params.userId}
+        </if>
+
+        <if test="params.accountId !=null and params.accountId !='' ">
+            and t2.account_id = #{params.accountId}
+        </if>
+
+        <if test="params.accountId !=null and params.accountId !='' ">
+            and t2.account_id = #{params.accountId}
+        </if>
+        <if test="params.projectName !=null and params.projectName !='' ">
+            and t3.project_name like concat(concat('%',#{params.projectName}),'%')
+        </if>
+        <if test="params.userName !=null and params.userName !='' ">
+            and t4.realname like concat(concat('%',#{params.userName}),'%')
+        </if>
+    </select>
+
 </mapper>

+ 7 - 0
module-alarm/src/main/java/cn/com/ctop/alarm/modules/service/IRuleAccountTemplateService.java

@@ -1,9 +1,13 @@
 package cn.com.ctop.alarm.modules.service;
 
 import cn.com.ctop.alarm.modules.entity.RuleAccountTemplate;
+import cn.com.ctop.alarm.modules.entity.vo.TemplateAppliedVo;
 import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.extension.service.IService;
 
+import java.util.List;
+import java.util.Map;
+
 /**
  * @Description: 规则模板
  * @Author: jeecg-boot
@@ -14,4 +18,7 @@ public interface IRuleAccountTemplateService extends IService<RuleAccountTemplat
 
     // 推送模板到账户下
     JSONObject pushTemplateToAccount(Long accountId, Long templateId) throws Exception;
+
+    // 查询 名下账户 应用的模板
+    List<TemplateAppliedVo> getTemplateApplied(Map<String, Object> requestMap);
 }

+ 2 - 0
module-alarm/src/main/java/cn/com/ctop/alarm/modules/service/IRuleTemplateService.java

@@ -15,4 +15,6 @@ public interface IRuleTemplateService extends IService<RuleTemplate> {
     JSONObject createTemplate(JSONObject requestJson);
 
     JSONObject queryDetailById(String id) throws Exception;
+
+    JSONObject queryDetailByAccountIdAndTemplateId(Long accountId, Long templateId) throws Exception;
 }

+ 14 - 0
module-alarm/src/main/java/cn/com/ctop/alarm/modules/service/impl/RuleAccountTemplateServiceImpl.java

@@ -1,6 +1,7 @@
 package cn.com.ctop.alarm.modules.service.impl;
 
 import cn.com.ctop.alarm.modules.entity.*;
+import cn.com.ctop.alarm.modules.entity.vo.TemplateAppliedVo;
 import cn.com.ctop.alarm.modules.mapper.RuleAccountTemplateMapper;
 import cn.com.ctop.alarm.modules.service.*;
 import cn.com.ctop.common.module.utils.Check;
@@ -11,6 +12,7 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 
 /**
@@ -92,4 +94,16 @@ public class RuleAccountTemplateServiceImpl extends ServiceImpl<RuleAccountTempl
         returnJson.put("groupCount", groupCount);
         return returnJson;
     }
+
+
+    /**
+     * 查询 账户下 应用的模板
+     *
+     * @param requestMap
+     * @return
+     */
+    @Override
+    public List<TemplateAppliedVo> getTemplateApplied(Map<String, Object> requestMap) {
+        return ruleAccountTemplateMapper.getTemplateApplied(requestMap);
+    }
 }

+ 199 - 77
module-alarm/src/main/java/cn/com/ctop/alarm/modules/service/impl/RuleGroupServiceImpl.java

@@ -5,17 +5,22 @@ import cn.com.ctop.alarm.modules.entity.*;
 import cn.com.ctop.alarm.modules.mapper.*;
 import cn.com.ctop.alarm.modules.service.IRuleAccountTemplateService;
 import cn.com.ctop.alarm.modules.service.IRuleGroupService;
+import cn.com.ctop.common.module.entity.CtopOauthToken;
+import cn.com.ctop.common.module.mapper.SysUserMapper;
+import cn.com.ctop.common.module.service.ICtopOauthTokenService;
+import cn.com.ctop.common.module.service.IRuleDataAccountService;
 import cn.com.ctop.common.module.service.ISendMessageService;
 import cn.com.ctop.common.module.utils.Check;
+import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouUpdateService;
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.xxl.job.core.enums.NoEn;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
-import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -44,11 +49,20 @@ public class RuleGroupServiceImpl extends ServiceImpl<RuleGroupMapper, RuleGroup
     @Autowired
     private RuleTemplateMapper ruleTemplateMapper;
     @Autowired
+    private SysUserMapper sysUserMapper;
+    @Autowired
     private IRuleGroupService ruleGroupService;
     @Autowired
     private IRuleAccountTemplateService ruleAccountTemplateService;
     @Autowired
     private ISendMessageService sendMessageService;
+    @Autowired
+    private IKuaiShouUpdateService kuaiShouUpdateService;
+    @Autowired
+    private ICtopOauthTokenService oauthTokenService;
+    @Autowired
+    private IRuleDataAccountService ruleDataAccountService;
+    private JSONObject userObj = null;
 
     @Override
     public void checkRules() {
@@ -58,12 +72,6 @@ public class RuleGroupServiceImpl extends ServiceImpl<RuleGroupMapper, RuleGroup
             log.warn("查询账户绑定过的规则模板失败");
             return;
         }
-        //查询匹配数据
-        List<JSONObject> dataList = getData();
-        if (Check.isNull(dataList)) {
-            log.warn("查询匹配数据失败");
-            return;
-        }
         //获取规则集
         Map<Long, List<RuleGroup>> ruleGroupMap = getRuleGroupMap();
         if (Check.isNull(ruleGroupMap)) {
@@ -77,12 +85,8 @@ public class RuleGroupServiceImpl extends ServiceImpl<RuleGroupMapper, RuleGroup
             return;
         }
         for (RuleAccountTemplate templates : ruleAccountTemplates) {
-            for (JSONObject matchData : dataList) {
-                if (templates.getAccountId() == matchData.getLong("accountId")) {
-                    List<RuleGroup> ruleGroups = ruleGroupMap.get(templates.getTemplateId());
-                    matchAlarmRules(ruleGroups, getThreshold(ruleAccountThresholdMapper.selectByAccountId(templates.getAccountId())), matchData, indicators);
-                }
-            }
+            List<RuleGroup> ruleGroups = ruleGroupMap.get(templates.getTemplateId());
+            matchAlarmRules(ruleGroups, getThreshold(ruleAccountThresholdMapper.selectByAccountId(templates.getAccountId())), indicators, templates.getAccountId());
         }
     }
 
@@ -91,60 +95,194 @@ public class RuleGroupServiceImpl extends ServiceImpl<RuleGroupMapper, RuleGroup
      *
      * @param ruleGroups   规则集
      * @param thresholdObj 规则id阈值
-     * @param matchData    匹配数据
      * @param indicators   指标码
      * @return void
      * @throws
      * @author ZHAOXA
      */
-    private void matchAlarmRules(List<RuleGroup> ruleGroups, JSONObject thresholdObj, JSONObject matchData, JSONObject indicators) {
+    private void matchAlarmRules(List<RuleGroup> ruleGroups, JSONObject thresholdObj, JSONObject indicators, Long accountId) {
+        userObj = new JSONObject();
+        //查询匹配数据
+        JSONObject matchData = getRuleData(accountId);
+        if (Check.isNull(matchData)) {
+            log.warn("查询匹配数据失败");
+            return;
+        }
+        log.info("已获取账户({})的数据,开始匹配规则", accountId);
         for (RuleGroup ruleGroup : ruleGroups) {
-            boolean isAllTrue = "and".equals(ruleGroup.getRuleRelationship());
-            boolean flag = true;
             List<RuleBase> ruleBaseList = ruleGroup.getRuleBaseList();
-            for (RuleBase ruleBase : ruleBaseList) {
-                //指标阈值
-                String threshold = thresholdObj.getString(ruleBase.getId().toString());
-                String value = matchData.getString(ruleBase.getIndicatorCode());
+            if (Check.isNull(ruleBaseList)) {
+                continue;
+            }
+            boolean isBase = "base".equals(ruleGroup.getRuleType());
+            //匹配单规则
+            if (isBase) {
+                RuleBase ruleBase = ruleBaseList.get(0);
                 //指标对象
                 JSONObject indicator = indicators.getJSONObject(ruleBase.getIndicatorCode());
-                //and关系,全部匹配规则
-                if (isAllTrue) {
-                    if (flag) {
-                        flag = MatchLogic.matchCondition(indicator.getString("dataType"), ruleBase.getRuleCondition(), threshold, value);
+                //指标阈值
+                String threshold = thresholdObj.getString(ruleBase.getId().toString());
+                //阈值为空时,或者阈值为“unlimited”(不限),不执行该规则
+                if (Check.isNull(threshold) || "unlimited".equals(threshold)) {
+                    log.warn("阈值为空/不限,该规则({})不执行", ruleBase.getId());
+                    continue;
+                }
+                //维度数据
+                JSONArray dimensionData = matchData.getJSONArray(ruleBase.getRuleDimension());
+                if (!Check.isNull(dimensionData)) {
+                    for (int i = 0; i < dimensionData.size(); i++) {
+                        JSONObject obj = dimensionData.getJSONObject(i);
+                        String value = obj.getString(ruleBase.getIndicatorCode());
+                        if (MatchLogic.matchCondition(indicator.getString("dataType"), ruleBase.getRuleCondition(), threshold, value)) {
+                            sendMsg(ruleGroup, obj);
+                        }
+                    }
+                }
+                //匹配组合规则
+            } else {
+                boolean flag = false;
+                //符合规则的数据集
+                JSONArray targetDatas = new JSONArray();
+                JSONArray planDatas = new JSONArray();
+                JSONArray creativeDatas = new JSONArray();
+                JSONArray accountDatas = new JSONArray();
+                for (RuleBase ruleBase : ruleBaseList) {
+                    //指标对象
+                    JSONObject indicator = indicators.getJSONObject(ruleBase.getIndicatorCode());
+                    //阈值类型
+                    String dataType = indicator.getString("dataType");
+                    //指标阈值
+                    String threshold = thresholdObj.getString(ruleBase.getId().toString());
+                    //阈值为空时,或者阈值为“unlimited”(不限),不执行该规则
+                    if (Check.isNull(threshold) || "unlimited".equals(threshold)) {
+                        continue;
                     }
-                } else {
-                    //or关系,任一阈值匹配,则跳出循环
-                    flag = MatchLogic.matchCondition(indicator.getString("dataType"), ruleBase.getRuleCondition(), threshold, value);
-                    if (flag) {
-                        break;
+                    JSONArray dimensionData = matchData.getJSONArray(ruleBase.getRuleDimension());
+                    //账户维度数据
+                    if ("account".equals(ruleBase.getRuleDimension())) {
+                        JSONObject accountEntity = dimensionData.getJSONObject(0);
+                        if (MatchLogic.matchCondition(dataType, ruleBase.getRuleCondition(), threshold, accountEntity.getString(ruleBase.getIndicatorCode()))) {
+                            accountDatas.add(accountEntity);
+                        } else {
+                            log.warn("判断规则组({}),账户规则不符合", ruleGroup.getId());
+                            break;
+                        }
+                    } else if ("plan".equals(ruleBase.getRuleDimension())) {
+                        planDatas = getOKData(planDatas, dimensionData, ruleBase, dataType, threshold);
+                    } else if ("creative".equals(ruleBase.getRuleDimension())) {
+                        creativeDatas = getOKData(creativeDatas, dimensionData, ruleBase, dataType, threshold);
+                    } else if ("target".equals(ruleBase.getRuleDimension())) {
+                        targetDatas = getOKData(targetDatas, dimensionData, ruleBase, dataType, threshold);
+                    }
+
+                }
+                //获取达标可发送的数据
+                JSONArray sendData = MatchLogic.getSendData(accountDatas, planDatas, creativeDatas, targetDatas);
+                if (!Check.isNull(sendData)) {
+                    //执行发送
+                    for (int i = 0; i < sendData.size(); i++) {
+                        sendMsg(ruleGroup, sendData.getJSONObject(i));
                     }
                 }
             }
-            //执行发送
-            if (flag) {
-                boolean isPause = "PAUSE".equals(ruleGroup.getOperate());
-                if (isPause) {
-                    //关停操作 TODO
+        }
+    }
 
+    /**
+     * @param ruleDatas     达标数据集
+     * @param dimensionData 匹配数据
+     * @param ruleBase      规则
+     * @param type          数据类型
+     * @param threshold     阈值
+     * @return void
+     * @throws
+     * @author ZHAOXA
+     */
+    private JSONArray getOKData(JSONArray ruleDatas, JSONArray dimensionData, RuleBase ruleBase, String type, String threshold) {
+        if (ruleDatas.size() > 0) {
+            JSONArray okData = new JSONArray();
+            for (int i = 0; i < ruleDatas.size(); i++) {
+                JSONObject targetEntity = dimensionData.getJSONObject(i);
+                String value = targetEntity.getString(ruleBase.getIndicatorCode());
+                if (MatchLogic.matchCondition(type, ruleBase.getRuleCondition(), threshold, value)) {
+                    okData.add(targetEntity);
                 }
-                //TODO
-                String msg = MatchLogic.getMsg(null, null, null, null);
-                String sendType = ruleGroup.getSendType();
-                if ("SMS".equals(sendType)) {
+            }
+            return okData;
+        }
+        for (int i = 0; i < dimensionData.size(); i++) {
+            JSONObject targetEntity = dimensionData.getJSONObject(i);
+            String value = targetEntity.getString(ruleBase.getIndicatorCode());
+            if (MatchLogic.matchCondition(type, ruleBase.getRuleCondition(), threshold, value)) {
+                ruleDatas.add(targetEntity);
+            }
+        }
+        return ruleDatas;
+    }
 
-                } else if ("WeChat".equals(sendType)) {
-                    sendMessageService.sendMessage("", msg);
-                } else if ("EMAIL".equals(sendType)) {
+    /**
+     * 发送消息
+     *
+     * @param
+     * @return void
+     * @throws
+     * @author ZHAOXA
+     */
+    private void sendMsg(RuleGroup ruleGroup, JSONObject obj) {
+        Long creativeId = obj.getLong("creativeId");
+        Long planId = obj.getLong("planId");
+        Long accountId = obj.getLong("accountId");
+        JSONObject user = getUserByAccountId(accountId);
+        boolean isPause = "PAUSE".equals(ruleGroup.getOperate());
+        if (isPause) {
+            if (shutDown(accountId, planId, creativeId, user.getString("id"))) {
+                isPause = true;
+            }
+        }
+        String msg = MatchLogic.getMsg(ruleGroup, user, accountId, planId, creativeId, isPause);
+        String sendType = ruleGroup.getSendType();
+        if ("SMS".equals(sendType)) {
 
-                } else if ("TEL".equals(sendType)) {
+        } else if ("EMAIL".equals(sendType)) {
 
-                } else {
+        } else if ("TEL".equals(sendType)) {
 
-                }
+        } else {
+            sendMessageService.sendMessage(user.getString("id"), msg);
+        }
+    }
 
+    private JSONObject getUserByAccountId(Long accountId) {
+        JSONObject obj = userObj.getJSONObject(accountId.toString());
+        if (Check.isNull(obj)) {
+            JSONObject user = sysUserMapper.selectUserByAccount(accountId);
+            obj.put(accountId.toString(), user);
+            return user;
+        }
+        return obj;
+    }
+
+    /**
+     * 关停操作
+     *
+     * @param
+     * @return boolean
+     * @throws
+     * @author ZHAOXA
+     */
+    private boolean shutDown(Long accountId, Long planId, Long creativeId, String userId) {
+        CtopOauthToken token = oauthTokenService.getTokenByAccountId(accountId);
+        Map<String, Object> updateMap = new HashMap<>();
+        if (!Check.isNull(token)) {
+            if (!Check.isNull(creativeId)) {
+                updateMap = kuaiShouUpdateService.updateCreativeStatus(token.getAccessToken(), accountId, creativeId, NoEn.NO2.valueInt(), userId);
+                log.info("---------规则关停创意:{}", creativeId);
+            } else if (!Check.isNull(planId) && Check.isNull(creativeId)) {
+                updateMap = kuaiShouUpdateService.updateCampaignStatus(token.getAccessToken(), accountId, planId, NoEn.NO2.valueInt(), userId);
+                log.info("---------规则关停计划:{}", planId);
             }
         }
+        return (boolean) updateMap.get("success");
     }
 
     //整理阈值数据
@@ -185,51 +323,31 @@ public class RuleGroupServiceImpl extends ServiceImpl<RuleGroupMapper, RuleGroup
         Map<Long, List<RuleGroup>> map = new HashMap<>();
         List<RuleTemplate> ruleTemplates = ruleTemplateMapper.selectByMap(null);
         ruleTemplates.forEach(tem -> {
-            List<String> groupIds = strToList(tem.getGroupIds());
-            if (!Check.isNull(groupIds)) {
-                List<RuleGroup> ruleGroups = ruleGroupMapper.selectBatchIds(groupIds);
-                for (RuleGroup group : ruleGroups) {
-                    List<String> ruleIds = strToList(group.getRuleIds());
-                    if (!Check.isNull(ruleIds)) {
-                        group.setRuleBaseList(ruleBaseMapper.selectBatchIds(ruleIds));
-                    }
-                }
-                map.put(tem.getId(), ruleGroups);
+            QueryWrapper<RuleGroup> groupWrapper = new QueryWrapper<>();
+            groupWrapper.eq("template_id", tem.getId());
+            List<RuleGroup> ruleGroups = ruleGroupMapper.selectList(groupWrapper);
+            for (RuleGroup group : ruleGroups) {
+                QueryWrapper<RuleBase> baseWrapper = new QueryWrapper<>();
+                baseWrapper.eq("group_id", group.getId());
+                baseWrapper.orderByDesc("is_unlimited");
+                group.setRuleBaseList(ruleBaseMapper.selectList(baseWrapper));
             }
+            map.put(tem.getId(), ruleGroups);
         });
         return null;
     }
 
-    //拆分逗号拼接数据
-    private List<String> strToList(String strings) {
-        List<String> ids = null;
-        try {
-            if (Check.isNull(strings)) {
-                return null;
-            }
-            JSONObject job = new JSONObject();
-            job.put("list", strings);
-            ids = new ArrayList<>();
-            JSONArray idList = job.getJSONArray("list");
-            for (Object id : idList) {
-                ids.add(String.valueOf(id));
-            }
-        } catch (Exception e) {
-            log.error("ids格式转换异常", e);
-        }
-        return ids;
-    }
 
     /**
-     * TODO 获取指标数据
+     * 获取指标数据
      *
      * @param
      * @return java.util.List<org.json.JSONObject>
      * @throws
      * @author ZHAOXA
      */
-    private List<JSONObject> getData() {
-        return null;
+    private JSONObject getRuleData(Long accountId) {
+        return ruleDataAccountService.getRuleDataByAccountId(accountId);
     }
 
     /**
@@ -277,6 +395,8 @@ public class RuleGroupServiceImpl extends ServiceImpl<RuleGroupMapper, RuleGroup
                     ruleBase.setThreshold(ruleDetailJson.getString("threshold"));
                     ruleBase.setVariableType(ruleDetailJson.getInteger("variableType"));
                     ruleBase.setRuleDimension(ruleDetailJson.getString("ruleDimension"));
+                    ruleBase.setJudgeFormat(ruleDetailJson.getInteger("judgeFormat"));
+                    ruleBase.setIsUnlimited(ruleDetailJson.getInteger("isUnlimited"));
                     int insert = ruleBaseMapper.insert(ruleBase);  // 添加基础规则
                     if (insert > 0) {
                         if (!Check.isNull(accountList)) {
@@ -306,6 +426,8 @@ public class RuleGroupServiceImpl extends ServiceImpl<RuleGroupMapper, RuleGroup
                 ruleGroup.setRuleRelationship(groupJson.getString("ruleRelationship"));
                 ruleGroup.setGroupName(groupJson.getString("groupName"));
                 ruleGroup.setRemark(groupJson.getString("remark"));
+                ruleGroup.setIsCopy(groupJson.getInteger("isCopy"));
+                ruleGroup.setIsRequired(groupJson.getInteger("isRequired"));
                 boolean save = ruleGroupService.save(ruleGroup); // 新增规则组
                 if (save) {
 

+ 108 - 10
module-alarm/src/main/java/cn/com/ctop/alarm/modules/service/impl/RuleTemplateServiceImpl.java

@@ -1,15 +1,9 @@
 package cn.com.ctop.alarm.modules.service.impl;
 
-import cn.com.ctop.alarm.modules.entity.RuleBase;
-import cn.com.ctop.alarm.modules.entity.RuleGroup;
-import cn.com.ctop.alarm.modules.entity.RuleIndicator;
-import cn.com.ctop.alarm.modules.entity.RuleTemplate;
+import cn.com.ctop.alarm.modules.entity.*;
 import cn.com.ctop.alarm.modules.mapper.RuleBaseMapper;
 import cn.com.ctop.alarm.modules.mapper.RuleTemplateMapper;
-import cn.com.ctop.alarm.modules.service.IRuleBaseService;
-import cn.com.ctop.alarm.modules.service.IRuleGroupService;
-import cn.com.ctop.alarm.modules.service.IRuleIndicatorService;
-import cn.com.ctop.alarm.modules.service.IRuleTemplateService;
+import cn.com.ctop.alarm.modules.service.*;
 import cn.com.ctop.common.module.utils.Check;
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
@@ -42,6 +36,9 @@ public class RuleTemplateServiceImpl extends ServiceImpl<RuleTemplateMapper, Rul
     @Autowired
     private IRuleIndicatorService ruleIndicatorService;
 
+    @Autowired
+    private IRuleAccountThresholdService accountThresholdService;
+
     /**
      * 创建规则模板
      *
@@ -93,19 +90,22 @@ public class RuleTemplateServiceImpl extends ServiceImpl<RuleTemplateMapper, Rul
                                 ruleBase.setThreshold(ruleDetailJson.getString("threshold"));
                                 ruleBase.setVariableType(ruleDetailJson.getInteger("variableType"));
                                 ruleBase.setRuleDimension(ruleDetailJson.getString("ruleDimension"));
+                                ruleBase.setJudgeFormat(ruleDetailJson.getInteger("judgeFormat"));
+                                ruleBase.setIsUnlimited(ruleDetailJson.getInteger("isUnlimited"));
                                 int insert = ruleBaseMapper.insert(ruleBase);
                                 if (insert > 0) {
                                     ruleIds.add(ruleBase.getId());
                                 }
                             }
                         }
-
                         RuleGroup ruleGroup = new RuleGroup();
                         ruleGroup.setRuleIds(ruleIds.toJSONString());
                         ruleGroup.setRuleType(ruleGroupJson.getString("ruleType"));
                         ruleGroup.setRuleRelationship(ruleGroupJson.getString("ruleRelationship"));
                         ruleGroup.setGroupName(ruleGroupJson.getString("groupName"));
                         ruleGroup.setRemark(ruleGroupJson.getString("remark"));
+                        ruleGroup.setIsCopy(ruleGroupJson.getInteger("isCopy"));
+                        ruleGroup.setIsRequired(ruleGroupJson.getInteger("isRequired"));
                         boolean save = ruleGroupService.save(ruleGroup);
                         if (save) {
                             String ruleIdsArrStr = ruleGroup.getRuleIds();
@@ -120,7 +120,6 @@ public class RuleTemplateServiceImpl extends ServiceImpl<RuleTemplateMapper, Rul
                                 }
                             }
                             groupIds.add(ruleGroup.getId());
-
                         }
                     }
                 }
@@ -195,6 +194,8 @@ public class RuleTemplateServiceImpl extends ServiceImpl<RuleTemplateMapper, Rul
             groupJson.put("remark", group.getRemark());
             groupJson.put("operate", group.getOperate());
             groupJson.put("sendType", group.getSendType());
+            groupJson.put("isCopy", group.getIsCopy());
+            groupJson.put("isRequired", group.getIsRequired());
             JSONArray ruleIds = JSONArray.parseArray(group.getRuleIds());
             if (Check.isNull(ruleIds)) {
                 continue;
@@ -209,11 +210,108 @@ public class RuleTemplateServiceImpl extends ServiceImpl<RuleTemplateMapper, Rul
                 JSONObject ruleJson = new JSONObject();
                 ruleJson.put("ruleId", ruleBase.getId());
                 ruleJson.put("ruleName", ruleBase.getRuleName());
+                ruleJson.put("judgeFormat", ruleBase.getJudgeFormat());
                 ruleJson.put("indicatorCode", ruleBase.getIndicatorCode());
                 ruleJson.put("ruleCondition", ruleBase.getRuleCondition());
                 ruleJson.put("threshold", ruleBase.getThreshold());
                 ruleJson.put("ruleDimension", ruleBase.getRuleDimension());
                 ruleJson.put("variableType", ruleBase.getVariableType());
+                ruleJson.put("isUnlimited", ruleBase.getIsUnlimited());
+                /**
+                 * 查询指标对应信息
+                 */
+                QueryWrapper<RuleIndicator> indicatorQueryWrapper = new QueryWrapper<>();
+                indicatorQueryWrapper.eq("code", ruleBase.getIndicatorCode());
+                indicatorQueryWrapper.eq("dimension", ruleBase.getRuleDimension());
+                indicatorQueryWrapper.last("limit 1");
+                RuleIndicator ruleIndicator = ruleIndicatorService.getOne(indicatorQueryWrapper);
+                if (!Check.isNull(ruleIndicator)) {
+                    ruleJson.put("dataType", ruleIndicator.getDataType());
+                    ruleJson.put("dictId", ruleIndicator.getDictId());
+                    ruleJson.put("dataUnit", ruleIndicator.getDataUnit());
+                    ruleJson.put("name", ruleIndicator.getName());
+                    ruleJson.put("modelType", ruleIndicator.getModelType());
+                }
+
+                ruleDetail.add(ruleJson);
+            }
+            groupJson.put("ruleDetail", ruleDetail);
+            ruleList.add(groupJson);
+        }
+
+        returnJson.put("ruleList", ruleList);
+        return returnJson;
+    }
+
+
+    /**
+     * 根据 账户id 模板id 查询模板详情
+     *
+     * @param accountId
+     * @param templateId
+     * @return
+     */
+    @Override
+    public JSONObject queryDetailByAccountIdAndTemplateId(Long accountId, Long templateId) throws Exception {
+        JSONObject returnJson = new JSONObject();
+        RuleTemplate template = ruleTemplateMapper.selectById(templateId);
+        if (Check.isNull(ruleTemplateMapper)) {
+            throw new Exception("获取模板基本信息为空");
+        }
+
+        returnJson.put("templateId", template.getId());
+        returnJson.put("templateName", template.getTemplateName());
+        returnJson.put("mediaType", template.getMediaType());
+        JSONArray groupIds = JSONArray.parseArray(template.getGroupIds());
+        if (Check.isNull(groupIds)) {
+            throw new Exception("未获取规则集");
+        }
+
+
+        JSONArray ruleList = new JSONArray();
+        for (int i = 0; i < groupIds.size(); i++) {
+            Long groupId = groupIds.getLong(i);
+            RuleGroup group = ruleGroupService.getById(groupId);
+            if (Check.isNull(group)) {
+                continue;
+            }
+            JSONObject groupJson = new JSONObject();
+            groupJson.put("groupId", group.getId());
+            groupJson.put("groupName", group.getGroupName());
+            groupJson.put("ruleType", group.getRuleType());
+            groupJson.put("ruleRelationship", group.getRuleRelationship());
+            groupJson.put("remark", group.getRemark());
+            groupJson.put("operate", group.getOperate());
+            groupJson.put("sendType", group.getSendType());
+            groupJson.put("isCopy", group.getIsCopy());
+            groupJson.put("isRequired", group.getIsRequired());
+            JSONArray ruleIds = JSONArray.parseArray(group.getRuleIds());
+            if (Check.isNull(ruleIds)) {
+                continue;
+            }
+            JSONArray ruleDetail = new JSONArray();
+            for (int j = 0; j < ruleIds.size(); j++) {
+                Long ruleId = ruleIds.getLong(j);
+                RuleBase ruleBase = ruleBaseService.getById(ruleId);
+                if (Check.isNull(ruleBase)) {
+                    continue;
+                }
+                JSONObject ruleJson = new JSONObject();
+                ruleJson.put("ruleId", ruleBase.getId());
+                ruleJson.put("ruleName", ruleBase.getRuleName());
+                ruleJson.put("judgeFormat", ruleBase.getJudgeFormat());
+                ruleJson.put("indicatorCode", ruleBase.getIndicatorCode());
+                ruleJson.put("ruleCondition", ruleBase.getRuleCondition());
+                QueryWrapper<RuleAccountThreshold> accountThresholdQueryWrapper = new QueryWrapper<>();
+                accountThresholdQueryWrapper.eq("account_id", accountId);
+                accountThresholdQueryWrapper.eq("rule_id", ruleId);
+                RuleAccountThreshold threshold = accountThresholdService.getOne(accountThresholdQueryWrapper);
+                if (!Check.isNull(threshold)) {
+                    ruleJson.put("threshold", threshold.getThreshoId());
+                }
+                ruleJson.put("ruleDimension", ruleBase.getRuleDimension());
+                ruleJson.put("variableType", ruleBase.getVariableType());
+                ruleJson.put("isUnlimited", ruleBase.getIsUnlimited());
                 /**
                  * 查询指标对应信息
                  */

+ 112 - 96
module-common/src/main/java/cn/com/ctop/common/module/mapper/SysUserMapper.java

@@ -4,6 +4,7 @@ import cn.com.ctop.common.module.entity.SysUser;
 import cn.com.ctop.common.module.model.SysUserSysDepartModel;
 import cn.com.ctop.common.module.vo.SysUserDepVo;
 import cn.com.ctop.common.module.vo.SysUserVo;
+import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.core.conditions.Wrapper;
 import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 import com.baomidou.mybatisplus.core.metadata.IPage;
@@ -23,76 +24,85 @@ import java.util.Map;
  * @since 2018-12-20
  */
 public interface SysUserMapper extends BaseMapper<SysUser> {
-	List<SysUser> selectAllUser();
-	/**
-	  * 通过用户账号查询用户信息
-	 * @param username
-	 * @return
-	 */
-	 SysUser getUserByName(@Param("username") String username);
-
-	/**
-	 *  根据部门Id查询用户信息
-	 * @param page
-	 * @param departId
-	 * @return
-	 */
-	IPage<SysUser> getUserByDepId(Page page, @Param("departId") String departId, @Param("username") String username);
-
-	/**
-	 *  根据用户Ids,查询用户所属部门名称信息
-	 * @param userIds
-	 * @return
-	 */
-	List<SysUserDepVo> getDepNamesByUserIds(@Param("userIds") List<String> userIds);
-
-	/**
-	 *  根据部门Ids,查询部门下用户信息
-	 * @param page
-	 * @param departIds
-	 * @return
-	 */
-	IPage<SysUser> getUserByDepIds(Page page, @Param("departIds") List<String> departIds, @Param("username") String username);
-
-	/**
-	 * 根据角色Id查询用户信息
-	 * @param page
-	 * @param
-	 * @return
-	 */
-	IPage<SysUser> getUserByRoleId(Page page, @Param("roleId") String roleId, @Param("username") String username);
-
-	/**
-	 * 根据用户名设置部门ID
-	 * @param username
-	 * @param orgCode
-	 */
-	void updateUserDepart(@Param("username") String username, @Param("orgCode") String orgCode);
-
-	/**
-	 * 根据手机号查询用户信息
-	 * @param phone
-	 * @return
-	 */
-	SysUser getUserByPhone(@Param("phone") String phone);
-
-
-	/**
-	 * 根据邮箱查询用户信息
-	 * @param email
-	 * @return
-	 */
-	SysUser getUserByEmail(@Param("email") String email);
-
-	/**
-	 * 根据 orgCode 查询用户,包括子部门下的用户
-	 *
-	 * @param page 分页对象, xml中可以从里面进行取值,传递参数 Page 即自动分页,必须放在第一位(你可以继承Page实现自己的分页对象)
-	 * @param orgCode
-	 * @param userParams 用户查询条件,可为空
-	 * @return
-	 */
-	List<SysUserSysDepartModel> getUserByOrgCode(IPage page, @Param("orgCode") String orgCode, @Param("userParams") SysUser userParams);
+    List<SysUser> selectAllUser();
+
+    /**
+     * 通过用户账号查询用户信息
+     *
+     * @param username
+     * @return
+     */
+    SysUser getUserByName(@Param("username") String username);
+
+    /**
+     * 根据部门Id查询用户信息
+     *
+     * @param page
+     * @param departId
+     * @return
+     */
+    IPage<SysUser> getUserByDepId(Page page, @Param("departId") String departId, @Param("username") String username);
+
+    /**
+     * 根据用户Ids,查询用户所属部门名称信息
+     *
+     * @param userIds
+     * @return
+     */
+    List<SysUserDepVo> getDepNamesByUserIds(@Param("userIds") List<String> userIds);
+
+    /**
+     * 根据部门Ids,查询部门下用户信息
+     *
+     * @param page
+     * @param departIds
+     * @return
+     */
+    IPage<SysUser> getUserByDepIds(Page page, @Param("departIds") List<String> departIds, @Param("username") String username);
+
+    /**
+     * 根据角色Id查询用户信息
+     *
+     * @param page
+     * @param
+     * @return
+     */
+    IPage<SysUser> getUserByRoleId(Page page, @Param("roleId") String roleId, @Param("username") String username);
+
+    /**
+     * 根据用户名设置部门ID
+     *
+     * @param username
+     * @param orgCode
+     */
+    void updateUserDepart(@Param("username") String username, @Param("orgCode") String orgCode);
+
+    /**
+     * 根据手机号查询用户信息
+     *
+     * @param phone
+     * @return
+     */
+    SysUser getUserByPhone(@Param("phone") String phone);
+
+
+    /**
+     * 根据邮箱查询用户信息
+     *
+     * @param email
+     * @return
+     */
+    SysUser getUserByEmail(@Param("email") String email);
+
+    /**
+     * 根据 orgCode 查询用户,包括子部门下的用户
+     *
+     * @param page       分页对象, xml中可以从里面进行取值,传递参数 Page 即自动分页,必须放在第一位(你可以继承Page实现自己的分页对象)
+     * @param orgCode
+     * @param userParams 用户查询条件,可为空
+     * @return
+     */
+    List<SysUserSysDepartModel> getUserByOrgCode(IPage page, @Param("orgCode") String orgCode, @Param("userParams") SysUser userParams);
 
 
     /**
@@ -109,46 +119,52 @@ public interface SysUserMapper extends BaseMapper<SysUser> {
      * @Date 2019/12/13 16:10
      * @Description: 批量删除角色与用户关系
      */
-	void deleteBathRoleUserRelation(@Param("roleIdArray") String[] roleIdArray);
+    void deleteBathRoleUserRelation(@Param("roleIdArray") String[] roleIdArray);
 
     /**
      * @Author scott
      * @Date 2019/12/13 16:10
      * @Description: 批量删除角色与权限关系
      */
-	void deleteBathRolePermissionRelation(@Param("roleIdArray") String[] roleIdArray);
+    void deleteBathRolePermissionRelation(@Param("roleIdArray") String[] roleIdArray);
 
-	/**
-	 * 查询被逻辑删除的用户
-	 */
-	List<SysUser> selectLogicDeleted(@Param(Constants.WRAPPER) Wrapper<SysUser> wrapper);
+    /**
+     * 查询被逻辑删除的用户
+     */
+    List<SysUser> selectLogicDeleted(@Param(Constants.WRAPPER) Wrapper<SysUser> wrapper);
 
-	/**
-	 * 还原被逻辑删除的用户
-	 */
-	int revertLogicDeleted(@Param("userIds") String userIds, @Param("entity") SysUser entity);
+    /**
+     * 还原被逻辑删除的用户
+     */
+    int revertLogicDeleted(@Param("userIds") String userIds, @Param("entity") SysUser entity);
 
-	/**
-	 * 彻底删除被逻辑删除的用户
-	 */
-	int deleteLogicDeleted(@Param("userIds") String userIds);
+    /**
+     * 彻底删除被逻辑删除的用户
+     */
+    int deleteLogicDeleted(@Param("userIds") String userIds);
 
-    /** 更新空字符串为null【此写法有sql注入风险,禁止随便用】 */
+    /**
+     * 更新空字符串为null【此写法有sql注入风险,禁止随便用】
+     */
     int updateNullByEmptyString(@Param("fieldName") String fieldName);
 
-	/**
-	 *  根据部门Ids,查询部门下用户信息
-	 * @param departIds
-	 * @return
-	 */
-	List<SysUser> queryByDepIds(@Param("departIds") List<String> departIds, @Param("username") String username);
-	Map<String, Object> queryRoleCode(@Param("userId") String userId);
+    /**
+     * 根据部门Ids,查询部门下用户信息
+     *
+     * @param departIds
+     * @return
+     */
+    List<SysUser> queryByDepIds(@Param("departIds") List<String> departIds, @Param("username") String username);
+
+    Map<String, Object> queryRoleCode(@Param("userId") String userId);
+
+    List<SysUserVo> getAllUser(@Param("userName") String userName);
 
-	List<SysUserVo> getAllUser(@Param("userName") String userName);
+    List<SysUserVo> getUserListByCompany(@Param("companyId") String companyId, @Param("userName") String userName);
 
-	List<SysUserVo> getUserListByCompany(@Param("companyId") String companyId,@Param("userName") String userName);
+    List<SysUserVo> getAllSale();
 
-	List<SysUserVo> getAllSale();
+    List<SysUserVo> getAllSalesByCompanyId(@Param("companyId") String companyId);
 
-	List<SysUserVo> getAllSalesByCompanyId(@Param("companyId") String companyId);
+    JSONObject selectUserByAccount(@Param("accountId") Long accountId);
 }

+ 7 - 0
module-common/src/main/java/cn/com/ctop/common/module/mapper/xml/SysUserMapper.xml

@@ -242,4 +242,11 @@ SELECT
             and username != #{username}
         </if>
     </select>
+
+    <select id="selectUserByAccount" resultType="com.alibaba.fastjson.JSONObject">
+        SELECT *
+        FROM  sys_user t1
+        INNER JOIN  ctop_user_allocation t2 ON t1.id = t2.user_id
+        WHERE t2.account_id = #{accountId}
+    </select>
 </mapper>

+ 3 - 1
module-common/src/main/java/cn/com/ctop/common/module/service/IRuleDataAccountService.java

@@ -1,14 +1,16 @@
 package cn.com.ctop.common.module.service;
 
 import cn.com.ctop.common.module.entity.RuleDataAccount;
+import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.extension.service.IService;
 
 /**
  * @Description: 规则账户清洗数据
  * @Author: jeecg-boot
- * @Date:   2020-11-16
+ * @Date: 2020-11-16
  * @Version: V1.0
  */
 public interface IRuleDataAccountService extends IService<RuleDataAccount> {
 
+    JSONObject getRuleDataByAccountId(Long accountId);
 }

+ 35 - 1
module-common/src/main/java/cn/com/ctop/common/module/service/impl/RuleDataAccountServiceImpl.java

@@ -2,17 +2,51 @@ package cn.com.ctop.common.module.service.impl;
 
 import cn.com.ctop.common.module.entity.RuleDataAccount;
 import cn.com.ctop.common.module.mapper.RuleDataAccountMapper;
+import cn.com.ctop.common.module.mapper.RuleDataCreativeMapper;
+import cn.com.ctop.common.module.mapper.RuleDataPlanMapper;
+import cn.com.ctop.common.module.mapper.RuleDataTargetMapper;
 import cn.com.ctop.common.module.service.IRuleDataAccountService;
+import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.xxl.job.core.enums.NoEn;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
+import java.util.HashMap;
+import java.util.Map;
+
 /**
  * 规则账户清洗数据
+ *
  * @author jeecg-boot
- * @date   2020-11-16
  * @version V1.0
+ * @date 2020-11-16
  */
 @Service
 public class RuleDataAccountServiceImpl extends ServiceImpl<RuleDataAccountMapper, RuleDataAccount> implements IRuleDataAccountService {
 
+    @Autowired
+    private RuleDataAccountMapper ruleDataAccountMapper;
+
+    @Autowired
+    private RuleDataPlanMapper ruleDataPlanMapper;
+
+    @Autowired
+    private RuleDataTargetMapper ruleDataTargetMapper;
+
+    @Autowired
+    private RuleDataCreativeMapper ruleDataCreativeMapper;
+
+    @Override
+    public JSONObject getRuleDataByAccountId(Long accountId) {
+        JSONObject obj = new JSONObject();
+        Map<String, Object> map = new HashMap<>();
+        map.put("account_id", accountId);
+        map.put("status", NoEn.NO1.valueStr());
+        obj.put("account", ruleDataAccountMapper.selectByMap(map));
+        obj.put("plan", ruleDataPlanMapper.selectByMap(map));
+        obj.put("target", ruleDataTargetMapper.selectByMap(map));
+        obj.put("creative", ruleDataCreativeMapper.selectByMap(map));
+        return obj;
+    }
 }