not tracked not covered covered

    package service

    import (
            util "app.yhyue.com/moapp/jybase/common"
            . "app.yhyue.com/moapp/jybase/mongodb"
            "app.yhyue.com/moapp/jybase/mysql"
            "github.com/zeromicro/go-zero/core/logx"
    )

    func ClearEnt() {
            Ents = map[int]*Ent{}
            EntUsers = map[int]*EntUser{}
            EntUserDept = map[int]*EntDeptUser{}
            EntDeptUsers = map[int][]*EntDeptUser{}
            EntRuleUsers = map[string][]*EntRuleUser{}
            EntUserRules = map[int][]*EntRuleUser{}
            EntDepts = map[int]*EntDept{}
            EntParentDept = map[int][]*EntDeptParent{}
            EntChildDept = map[int][]*EntDeptParent{}
            EntDeptDis = map[int][]*EntDistribute{}
    }

    //
    func InitEnt(mysql *mysql.Mysql, mgo *MongodbSim, dbName string, entId, entUserId int) {
            InitEnts(mysql, entId)
            InitEntUsers(mysql, entUserId)
            InitEntDeptUsers(mysql, entUserId)
            InitEntRuleUsers(mysql, entUserId)
            InitEntDepts(mysql, entId)
            InitEntDeptParents(mysql, entId)
            InitEntDistribute(mgo, dbName, entId)
    }

    ///////////////////////
    var Ents = map[int]*Ent{}

    type Ent struct {
            Id         int
            Model      int
            Name       string
            DeptParent map[int][]int
            IsNew      int
    }

    func InitEnts(Mysql *mysql.Mysql, entId int) {
            list := Mysql.SelectBySql("select id,model,name from entniche_info where id=? and isNew=1 and status=1 and model in (1,2)", entId)
            if list == nil {
                    return
            }
            for _, v := range *list {
                    id := util.IntAll(v["id"])
                    Ents[id] = &Ent{
                            Id:    id,
                            Model: util.IntAll(v["model"]),
                            Name:  util.ObjToString(v["name"]),
                    }
            }
            logx.Info("entniche_info加载完成！")
    }

    var EntDepts = map[int]*EntDept{}

    type EntDept struct {
            Id     int
            Pid    int
            Name   string
            Nodiff int
            Subdis int
    }

    func InitEntDepts(Mysql *mysql.Mysql, entId int) {
            list := Mysql.SelectBySql(`select id,name,pid,subdis,nodiff from entniche_department where ent_id=?`, entId)
            if list == nil {
                    return
            }
            for _, v := range *list {
                    id := util.IntAll(v["id"])
                    EntDepts[id] = &EntDept{
                            Id:     id,
                            Pid:    util.IntAll(v["pid"]),
                            Nodiff: util.IntAll(v["nodiff"]),
                            Subdis: util.IntAll(v["subdis"]),
                            Name:   util.ObjToString(v["name"]),
                    }
            }
            logx.Info("entniche_department加载完成！")
    }

    var EntUsers = map[int]*EntUser{}

    type EntUser struct {
            Id    int
            Name  string
            Mail  string
            Phone string
            Power int
    }

    func InitEntUsers(Mysql *mysql.Mysql, entUserId int) {
            list := Mysql.SelectBySql(`select id,name,mail,phone,power from entniche_user where id=?`, entUserId)
            if list == nil {
                    return
            }
            for _, v := range *list {
                    id := util.IntAll(v["id"])
                    EntUsers[id] = &EntUser{
                            Id:    id,
                            Name:  util.ObjToString(v["name"]),
                            Mail:  util.ObjToString(v["mail"]),
                            Phone: util.ObjToString(v["phone"]),
                            Power: util.IntAll(v["power"]),
                    }
            }
            logx.Info("entniche_user加载完成！")
    }

    //我所有的父部门
    var EntParentDept = map[int][]*EntDeptParent{}

    //我所有的子部门
    var EntChildDept = map[int][]*EntDeptParent{}

    type EntDeptParent struct {
            Id  int
            Pid int
    }

    func InitEntDeptParents(Mysql *mysql.Mysql, entId int) {
            list := Mysql.SelectBySql(`select a.id,a.pid from entniche_department_parent a inner join entniche_department b on (a.id=b.id and b.ent_id=?)`, entId)
            if list == nil {
                    return
            }
            for _, v := range *list {
                    id := util.IntAll(v["id"])
                    pid := util.IntAll(v["pid"])
                    EntParentDept[id] = append(EntParentDept[id], &EntDeptParent{
                            Id:  id,
                            Pid: pid,
                    })
                    EntChildDept[pid] = append(EntChildDept[pid], &EntDeptParent{
                            Id:  id,
                            Pid: pid,
                    })
            }
            logx.Info("entniche_department_parent加载完成！")
    }

    var EntUserDept = map[int]*EntDeptUser{}
    var EntDeptUsers = map[int][]*EntDeptUser{}

    type EntDeptUser struct {
            UserId int
            DeptId int
    }

    func InitEntDeptUsers(Mysql *mysql.Mysql, entUserId int) {
            list := Mysql.SelectBySql(`select dept_id,user_id from entniche_department_user where user_id=?`, entUserId)
            if list == nil {
                    return
            }
            for _, v := range *list {
                    user_id := util.IntAll(v["user_id"])
                    dept_id := util.IntAll(v["dept_id"])
                    entDeptUser := &EntDeptUser{
                            UserId: user_id,
                            DeptId: dept_id,
                    }
                    EntUserDept[user_id] = entDeptUser
                    EntDeptUsers[dept_id] = append(EntDeptUsers[dept_id], entDeptUser)
            }
            logx.Info("entniche_department_user加载完成！")
    }

    var EntRuleUsers = map[string][]*EntRuleUser{}
    var EntUserRules = map[int][]*EntRuleUser{}

    type EntRuleUser struct {
            UserId int
            RuleId string
    }

    func InitEntRuleUsers(Mysql *mysql.Mysql, entUserId int) {
            list := Mysql.SelectBySql(`select user_id,rule_id from entniche_user_rule where user_id=?`, entUserId)
            if list == nil {
                    return
            }
            for _, v := range *list {
                    ruleId := util.ObjToString(v["rule_id"])
                    userId := util.IntAll(v["user_id"])
                    entRuleUser := &EntRuleUser{
                            UserId: userId,
                            RuleId: ruleId,
                    }
                    EntRuleUsers[ruleId] = append(EntRuleUsers[ruleId], entRuleUser)
                    EntUserRules[userId] = append(EntUserRules[userId], entRuleUser)
            }
            logx.Info("entniche_user_rule加载完成！")
    }

    var EntDeptDis = map[int][]*EntDistribute{}

    type EntDistribute struct {
            Id         string
            DeptId     int
            Area       map[string]interface{}
            Buyerclass []interface{}
            Items      []string
    }

    func InitEntDistribute(mgo *MongodbSim, dbName string, entId int) {
            sess := mgo.GetMgoConn()
            defer mgo.DestoryMongoConn(sess)
            it := sess.DB(dbName).C("entniche_distribute").Find(map[string]interface{}{
                    "i_status": map[string]interface{}{"$ne": 1},
                    "i_entid":  entId,
            }).Select(map[string]interface{}{
                    "_id":          1,
                    "i_entid":      1,
                    "i_deptid":     1,
                    "a_items":      1,
                    "o_area":       1,
                    "a_buyerclass": 1,
            }).Iter()
            for temp := make(map[string]interface{}); it.Next(&temp); {
                    if temp["i_deptid"] == nil {
                            continue
                    }
                    deptId := util.IntAll(temp["i_deptid"])
                    a_items, _ := temp["a_items"].([]interface{})
                    o_area, _ := temp["o_area"].(map[string]interface{})
                    a_buyerclass, _ := temp["a_buyerclass"].([]interface{})
                    EntDeptDis[deptId] = append(EntDeptDis[deptId], &EntDistribute{
                            Id:         BsonIdToSId(temp["_id"]),
                            DeptId:     deptId,
                            Area:       o_area,
                            Buyerclass: a_buyerclass,
                            Items:      util.ObjArrToStringArr(a_items),
                    })
                    temp = make(map[string]interface{})
            }
    }

    package service

    import (
            util "app.yhyue.com/moapp/jybase/common"
            . "app.yhyue.com/moapp/jybase/mongodb"
            "app.yhyue.com/moapp/jybase/mysql"
            "github.com/zeromicro/go-zero/core/logx"
            IC "jyBXSubscribe/rpc/init"
    )

    var Mysql *mysql.Mysql
    var Mgo *MongodbSim

    //用户基本信息
    type UserInfo struct {
            Entniche *Entniche
            SubSet   map[string]interface{}
    }

    //
    type Entniche struct {
            EntId    int    //企业id
            EntName  string //企业名称
            DeptId   int    //部门id
            DeptName string //部门名称
            DisId    string //分发id
            UserId   int
    }
    type MatchJob struct {
    }

    func (m *MatchJob) Start(entId, entUserId int) (map[string]interface{}, int) {
            defer util.Catch()
            defer ClearEnt()
            InitEnt(IC.MainMysql, &IC.Mgo, "qfw", entId, entUserId)
            users := m.LoadSubSet(entId)
            return FinalSub(entUserId, users), EntUserDept[entUserId].DeptId
    }

    func (m *MatchJob) LoadSubSet(entId int) map[*UserInfo]bool {
            defer util.Catch()
            Users := map[*UserInfo]bool{}
            sess := Mgo.GetMgoConn()
            defer Mgo.DestoryMongoConn(sess)
            it := sess.DB("qfw").C("entniche_rule").Find(map[string]interface{}{
                    "i_entid": entId,
            }).Select(map[string]interface{}{
                    "i_entid":    1,
                    "i_deptid":   1,
                    "i_userid":   1,
                    "o_entniche": 1,
            }).Iter()
            for _temp := make(map[string]interface{}); it.Next(&_temp); {
                    func(temp map[string]interface{}) {
                            entId := util.IntAll(temp["i_entid"])
                            deptId := util.IntAll(temp["i_deptid"])
                            userId := util.IntAll(temp["i_userid"])
                            if entId == 0 || (deptId == 0 && userId == 0) {
                                    return
                            } else if Ents[entId] == nil {
                                    logx.Info("没有找到该企业", entId)
                                    return
                            }
                            entName := Ents[entId].Name
                            if deptId > 0 && EntDepts[deptId] == nil {
                                    logx.Info("没有找到该部门", entName, entId, deptId)
                                    return
                            }
                            deptName := ""
                            if EntDepts[deptId] != nil {
                                    deptName = EntDepts[deptId].Name
                            }
                            subSet, _ := temp["o_entniche"].(map[string]interface{})
                            if subSet == nil || len(subSet) == 0 {
                                    logx.Info("订阅设置为空，过滤掉", entName, entId, deptName, deptId, userId)
                                    return
                            }
                            //
                            if deptId > 0 { //部门订阅
                                    if Ents[entId].Model != 1 {
                                            logx.Info("不是统一订阅模式，过滤掉", entName, entId, deptName, deptId)
                                            return
                                    } else if EntDepts[deptId] == nil {
                                            logx.Info("没有找到该部门，过滤掉", entName, entId, deptName, deptId)
                                            return
                                    } else if EntDepts[deptId].Subdis == 0 {
                                            logx.Info("该部门的订阅分发没有开启，过滤掉", entName, entId, deptName, deptId)
                                            return
                                    } else if EntDepts[deptId].Nodiff == 0 && EntDeptDis[deptId] == nil {
                                            logx.Info("该部门开启了订阅分发，没有开启全员无差别接收，但是没有分发规则，过滤掉", entName, entId, deptName, deptId)
                                            return
                                    }
                                    //如果我的上级部门打开了订阅分发，并且开启了全员无差别接收，本部门规则无效
                                    for _, dept := range EntParentDept[deptId] {
                                            if EntDepts[dept.Pid].Subdis == 1 && EntDepts[dept.Pid].Nodiff == 1 {
                                                    logx.Info("我的上级部门", dept.Pid, "开启了订阅分发和全员无差别，过滤掉", entName, entId, deptName, deptId)
                                                    return
                                            }
                                    }
                            } else if userId > 0 { //个人订阅
                                    if Ents[entId].Model != 2 {
                                            logx.Info("不是个人订阅模式，过滤掉", entName, entId, userId)
                                            return
                                    } else if EntUsers[userId] == nil {
                                            logx.Info("没有找到该用户，过滤掉", entName, entId, userId)
                                            return
                                    } else if EntUsers[userId].Power == 0 {
                                            logx.Info("该用户没有权限，过滤掉", entName, entId, userId)
                                            return
                                    }
                            }
                            user := &UserInfo{
                                    Entniche: &Entniche{
                                            EntId:    entId,
                                            EntName:  entName,
                                            DeptId:   deptId,
                                            DeptName: deptName,
                                            UserId:   userId,
                                    },
                                    SubSet: subSet,
                            }
                            logx.Info("加载订阅设置", "entId", entId, "entName", entName, "deptId", deptId, "deptName", deptName, "userId", userId)
                            Users[user] = true
                            if deptId <= 0 {
                                    return
                            }
                            //分发规则
                            if EntDepts[deptId].Nodiff == 1 {
                                    logx.Info("该部门开启了全员无差别，分发规则无效", entName, entId, deptName, deptId)
                                    return
                            } else if EntDeptDis[deptId] == nil {
                                    logx.Info("该部门没有分发规则", entName, entId, deptName, deptId)
                                    return
                            }
                            itemMap := map[string]interface{}{}
                            items, _ := subSet["a_items"].([]interface{})
                            for _, v := range items {
                                    item, _ := v.(map[string]interface{})
                                    if item == nil {
                                            continue
                                    }
                                    item_name, _ := item["s_item"].(string)
                                    if item_name == "" {
                                            continue
                                    }
                                    itemMap[item_name] = item
                            }
                            for _, dis := range EntDeptDis[deptId] {
                                    child_items := []interface{}{}
                                    for _, item_name := range dis.Items {
                                            if itemMap[item_name] == nil {
                                                    continue
                                            }
                                            child_items = append(child_items, itemMap[item_name])
                                    }
                                    child_subSet := map[string]interface{}{}
                                    if len(dis.Buyerclass) > 0 {
                                            child_subSet["a_buyerclass"] = dis.Buyerclass
                                    }
                                    if len(dis.Area) > 0 {
                                            child_subSet["o_area"] = dis.Area
                                    }
                                    if len(child_items) > 0 {
                                            child_subSet["a_items"] = child_items
                                    }
                                    if len(child_subSet) == 0 {
                                            continue
                                    }
                                    child_user := &UserInfo{
                                            Entniche: &Entniche{
                                                    EntId:    user.Entniche.EntId,
                                                    EntName:  user.Entniche.EntName,
                                                    DeptId:   user.Entniche.DeptId,
                                                    DeptName: user.Entniche.DeptName,
                                                    DisId:    dis.Id,
                                            },
                                            SubSet: child_subSet,
                                    }
                                    Users[child_user] = true
                            }
                    }(_temp)
                    _temp = make(map[string]interface{})
            }
            return Users
    }
    func FinalSub(entUserId int, users map[*UserInfo]bool) map[string]interface{} {
            for k, _ := range users {
                    if k.Entniche.DeptId > 0 {
                            k.Entniche.DeptName = EntDepts[k.Entniche.DeptId].Name
                            staffIds := GetDeptUserIds(&UserInfo{
                                    Entniche: &Entniche{
                                            EntId:    k.Entniche.EntId,
                                            EntName:  k.Entniche.EntName,
                                            DeptId:   k.Entniche.DeptId,
                                            DeptName: k.Entniche.DeptName,
                                            DisId:    k.Entniche.DisId,
                                    },
                            })
                            if staffIds == nil {
                                    continue
                            }
                            if staffIds[entUserId] {
                                    return k.SubSet
                            }
                    } else if k.Entniche.UserId > 0 {
                            return k.SubSet
                    } else {
                            continue
                    }
            }
            return nil
    }
    func GetDeptUserIds(ui *UserInfo) map[int]bool {
            if EntDepts[ui.Entniche.DeptId].Subdis == 0 {
                    logx.Info(ui.Entniche.EntName, ui.Entniche.EntId, ui.Entniche.DeptName, ui.Entniche.DeptId, "没有开启订阅分发，过滤掉")
                    return nil
            } else if EntDepts[ui.Entniche.DeptId].Nodiff == 0 && ui.Entniche.DisId == "" {
                    logx.Info(ui.Entniche.EntName, ui.Entniche.EntId, ui.Entniche.DeptName, ui.Entniche.DeptId, "没有开启全员无差别接收，并且没有分发规则，过滤掉")
                    return nil
            }
            //对我的对着生效的用户
            myIds := map[int]bool{}
            //打开了全员无差别，下面所有员工都生效
            if EntDepts[ui.Entniche.DeptId].Nodiff == 1 {
                    for _, v := range EntDeptUsers[ui.Entniche.DeptId] {
                            myIds[v.UserId] = true
                    }
                    for _, v := range EntChildDept[ui.Entniche.DeptId] {
                            for _, vv := range EntDeptUsers[v.Id] {
                                    myIds[vv.UserId] = true
                            }
                    }
                    logx.Info(ui.Entniche.EntName, ui.Entniche.EntId, ui.Entniche.DeptName, ui.Entniche.DeptId, "该部门打开了全员无差别", len(myIds), "人接收")
            } else if ui.Entniche.DisId != "" {
                    for _, v := range EntRuleUsers[ui.Entniche.DisId] {
                            myIds[v.UserId] = true
                    }
                    logx.Info(ui.Entniche.EntName, ui.Entniche.EntId, ui.Entniche.DeptName, ui.Entniche.DeptId, "该规则开启了订阅分发", ui.Entniche.DisId, "规则分发了", len(myIds), "人")
            }
            //我的上级部门，过滤掉本部门的人
            for _, v := range EntParentDept[ui.Entniche.DeptId] {
                    //看我的上级部门，有没有开启订阅分发
                    if EntDepts[v.Pid].Subdis == 0 {
                            continue
                    }
                    //看我的上级部门，有没有全员无差别接收
                    if EntDepts[v.Pid].Nodiff == 1 {
                            logx.Info(ui.Entniche.EntName, ui.Entniche.EntId, ui.Entniche.DeptName, ui.Entniche.DeptId, ui.Entniche.DisId, "上级部门", v.Pid, "打开了全员无差别开关，过滤掉")
                            return nil
                    }
                    //看我的上级部门，有没有对我设置规则
                    for _, vv := range EntDeptDis[v.Pid] {
                            for _, vvv := range EntRuleUsers[vv.Id] {
                                    _, ok := myIds[vvv.UserId]
                                    if !ok {
                                            continue
                                    }
                                    delete(myIds, vvv.UserId)
                                    logx.Info(ui.Entniche.EntName, ui.Entniche.EntId, ui.Entniche.DeptName, ui.Entniche.DeptId, "上级部门", v.Pid, "对我设置的有", vvv.RuleId, "分发规则，此规则作废", vvv.UserId)
                            }
                    }
            }
            logx.Info(ui.Entniche.EntName, ui.Entniche.EntId, ui.Entniche.DeptName, ui.Entniche.DeptId, ui.Entniche.DisId, "该规则匹配到", len(myIds), "人")
            return myIds
    }

    // @Description   订阅设置相关
    package service

    import (
            "errors"
            "jyBXSubscribe/entity"
            "log"
            "strconv"

            "app.yhyue.com/moapp/jybase/common"
            "app.yhyue.com/moapp/jybase/mongodb"
            "github.com/zeromicro/go-zero/core/logx"
    )

    //
    type SubseribeService struct {
            Mgo          *mongodb.MongodbSim
            UserId       string                   //mongodb 的用户id
            Types        string                   //订阅信息产品类型 超级订阅、大会员、商机管理、免费订阅...
            Area         map[string]interface{}   //地区
            Buyerclass   []string                 //采购单位类型
            Items        []map[string]interface{} //关键词
            Infotype     []string                 //信息类型
            Matchway     string                   //匹配方式 1标题 2正文
            Projectmatch string                   //项目匹配 1开始 0关闭
            Ratemode     string                   // 1：实时推送，2：每天9点推送，3：每周推送，4：每月推送 5：每日推送两次
            Apppush      string                   //app推送 1开启 0关闭
            Mailpush     string                   //邮箱推送 1开启 0关闭
            Mail         string                   //邮箱
    }

    // @description          订阅设置相关修改
    // @param                     SubseribeService  用户信息相关
    // @return                    int64 是否成功 1成功 -1失败
    // @return                    error 错误信息
    //TODO 后期需要实现 查询各个身份的订阅设置修改[目前只实现了超级订阅]
    func (this *SubseribeService) Update() (int64, error) {
            if this.UserId == "" {
                    return -1, errors.New(entity.UPDATE_ERROR_MSG)
            }
            //查询条件
            query := map[string]interface{}{
                    "_id": mongodb.StringTOBsonId(this.UserId),
            }
            //查询字段
            fields := `{"i_vip_status":1,"o_vipjy":1}`

            //查询用户信息
            r, ok := this.Mgo.FindOneByField(entity.User, query, fields)
            if !ok || r == nil || len(*r) == 0 {
                    logx.Error("未找到用户")
                    return -1, errors.New(entity.UPDATE_ERROR_MSG)
            }
            //判断用户权益
            vip_status := common.Int64All((*r)["i_vip_status"])
            if vip_status <= 0 {
                    logx.Error("用户暂无权益")
                    return -1, errors.New(entity.UPDATE_ERROR_MSG)
            }
            //权益通过，获取要修改的参数
            setMap := map[string]interface{}{}
            if this.Area != nil {
                    setMap["o_vipjy.o_area"] = this.Area
            }
            if this.Buyerclass != nil {
                    setMap["o_vipjy.a_buyerclass"] = this.Buyerclass
            }
            if this.Items != nil {
                    setMap["o_vipjy.a_items"] = this.Items
            }
            if this.Infotype != nil {
                    setMap["o_vipjy.a_infotype"] = this.Infotype
            }
            if this.Matchway != "" {
                    i_matchway, _ := strconv.Atoi(this.Matchway)
                    setMap["o_vipjy.i_matchway"] = i_matchway
            }
            if this.Projectmatch != "" {
                    i_projectmatch, _ := strconv.Atoi(this.Projectmatch)
                    setMap["o_vipjy.i_projectmatch"] = i_projectmatch
            }
            if this.Ratemode != "" {
                    i_ratemode, _ := strconv.Atoi(this.Ratemode)
                    setMap["o_vipjy.i_ratemode"] = i_ratemode
            }
            if this.Apppush != "" {
                    i_apppush, _ := strconv.Atoi(this.Apppush)
                    setMap["o_vipjy.i_apppush"] = i_apppush
            }
            if this.Mailpush != "" {
                    i_mailpush, _ := strconv.Atoi(this.Mailpush)
                    setMap["o_vipjy.i_mailpush"] = i_mailpush
            }
            if this.Mail != "" {
                    setMap["o_vipjy.s_email"] = this.Mail
            }
            log.Println(setMap)
            if ok := this.Mgo.UpdateById(entity.User, this.UserId, map[string]interface{}{
                    "$set": setMap,
            }); ok {
                    return 1, nil

            }
            return -1, errors.New(entity.UPDATE_ERROR_MSG)
    }