123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317 |
- package jyutil
- import (
- "app.yhyue.com/moapp/jybase/common"
- "app.yhyue.com/moapp/jybase/date"
- "app.yhyue.com/moapp/jybase/mongodb"
- "app.yhyue.com/moapp/jybase/usercenter"
- "bytes"
- "context"
- "encoding/json"
- "fmt"
- "github.com/gogf/gf/v2/frame/g"
- "github.com/gogf/gf/v2/util/gconv"
- "github.com/pkg/errors"
- "io/ioutil"
- "jyOrderManager/internal/consts"
- "jyOrderManager/internal/model"
- "log"
- "net/http"
- "strings"
- "time"
- )
- // GetCreateUserData 查询用户 不存在注册用户 isEntSign 是否需要注册企业信息(避免校验调用) 如entId不为0代办已注册企业信息
- func GetCreateUserData(phone, companyName string, isEntSign bool) (data map[string]interface{}, entId, userPositionId int64, err error) {
- data = make(map[string]interface{})
- userData, ok := MG.DB().FindOne("user", map[string]interface{}{
- "$or": []map[string]interface{}{
- {"s_phone": phone},
- {"s_m_phone": phone},
- },
- })
- if ok && userData != nil && len(*userData) > 0 {
- data = *userData
- } else {
- id := MG.DB().Save("user", map[string]interface{}{
- "i_appid": 2,
- "s_phone": phone,
- "s_password": "",
- "l_registedate": time.Now().Unix(),
- "i_ts_guide": 2,
- "o_jy": map[string]interface{}{
- "i_wxpush": 1,
- "i_apppush": 1,
- "i_ratemode": 2,
- "l_modifydate": time.Now().Unix(),
- },
- "s_regsource": "qmx_admin",
- })
- if id == "" {
- return nil, 0, 0, fmt.Errorf("创建用户失败")
- }
- ck := &http.Cookie{}
- usercenter.AddBaseUser(*MG.DB(), g.Cfg().MustGet(ctx, "userCenterUrl").String(), id, map[string]interface{}{
- "appid": 10000,
- "phone": phone,
- "password": "",
- }, ck)
- SaveUserLog(id, phone)
- uData, _ := MG.DB().FindById("user", id, "")
- data = *uData
- }
- data["userId"] = common.InterfaceToStr(data["_id"])
- //企业查询企业信息是否注册
- if isEntSign {
- entUser, err := g.DB().Ctx(ctx).GetOne(ctx, fmt.Sprintf(`SELECT a.ent_id FROM entniche_user a
- LEFT JOIN entniche_info b on b.name='%s' and a.ent_id = b.id
- WHERE phone = '%s' limit 1`, companyName, phone))
- if err != nil {
- return nil, 0, 0, errors.Wrapf(err, "查询企业是否存在异常 %s", companyName)
- }
- entId = gconv.Int64(entUser.Map()["ent_id"])
- if entId == 0 {
- entId, userPositionId, err = AutomaticallyCreatingEnt(companyName, phone, "", common.InterfaceToStr(data["_id"]))
- if err != nil {
- return nil, 0, 0, errors.Wrapf(err, "创建企业异常 %s", companyName)
- }
- } else {
- //查找baseUserId
- baseUserId := common.Int64All(data["base_user_id"])
- positionData, _ := g.DB().Ctx(ctx).GetOne(ctx, fmt.Sprintf(`SELECT s_name FROM base_position WHERE type=1 and user_id='%d' and ent_id=%d`, baseUserId, entId))
- if !positionData.IsEmpty() {
- userPositionId = gconv.Int64(positionData.Map()["id"])
- }
- }
- }
- return data, entId, userPositionId, nil
- }
- // 用户注册日志保存
- func SaveUserLog(userid, phone string) {
- data := map[string]interface{}{
- "userid": userid,
- "phone": phone,
- "way": "phone",
- "system": "pc",
- "source": "background",
- "create_time": date.NowFormat(date.Date_Full_Layout),
- }
- MG.DB().Save("register_log", data)
- }
- func GetUserFullId(phone, companyName string) (mongoUserId string, baseUserId, entId, entUserId int64) {
- userData, ok := MG.DB().FindOne("user", map[string]interface{}{
- "$or": []map[string]interface{}{
- {"s_phone": phone},
- {"s_m_phone": phone},
- },
- })
- if ok && userData != nil && len(*userData) > 0 {
- mongoUserId = mongodb.BsonIdToSId((*userData)["_id"])
- baseUserId = gconv.Int64((*userData)["base_user_id"])
- }
- if companyName == "" {
- entUser, err := g.DB().Ctx(ctx).GetOne(ctx, fmt.Sprintf(`SELECT a.ent_id,a.id FROM entniche_user a
- LEFT JOIN entniche_info b on b.name='%s' and a.ent_id = b.id
- WHERE phone = '%s' limit 1`, companyName, phone))
- if err == nil && !entUser.IsEmpty() {
- entId = gconv.Int64(entUser.Map()["ent_id"])
- entUserId = gconv.Int64(entUser.Map()["id"])
- }
- }
- return
- }
- var getPositionIdByMongoUserId = func(mgoUserId string) int64 {
- userData, ok := MG.DB().FindById("user", mgoUserId, `"base_user_id":1`)
- if userData != nil && len(*userData) > 0 && ok {
- baseUserId := common.Int64All((*userData)["base_user_id"])
- positionData, _ := g.DB("base").GetOne(ctx, "SELECT id FROM base_position WHERE type=0 and ent_id=0 and user_id=?", baseUserId)
- if !positionData.IsEmpty() {
- return gconv.Int64(positionData.Map()["id"])
- }
- }
- return -1
- }
- func ClearBigVipUserPower(ctx context.Context, userId string) {
- var (
- powerChacheKey = g.Cfg().MustGet(ctx, "bigmemberKey", "bigmember_power_3_").String()
- IsGetUserBaseInfoRedisKey = "baseinfo_%s"
- RedisMenuKeyPC = "jy_workdesktopmenu_10000_PC_menu1_%s" //剑鱼appid:10000
- RedisMenuKeyWX = "jy_workdesktopmenu_10000_WX_menu1_%s" //剑鱼appid:10000
- RedisMenuKeyAPP = "jy_workdesktopmenu_10000_APP_menu1_%s" //剑鱼appid:10000
- UserPowerRedisKey = "jy_userpowerredis_10000_%d_%s" //工作桌面 用户功能缓存(类似bigmember_power_3_%s)
- )
- if mongodb.IsObjectIdHex(userId) {
- user_id := userId
- //大会员主账号清理
- userDatas, ok := MG.DB().Find("user", map[string]interface{}{"s_member_mainid": user_id, "i_member_sub_status": 1}, nil, nil, false, -1, -1)
- if ok && userDatas != nil && len(*userDatas) > 0 {
- for _, v := range *userDatas {
- if pId := getPositionIdByMongoUserId(mongodb.BsonIdToSId(v["_id"])); pId > 0 {
- _, _ = g.Redis("newother").Del(ctx, fmt.Sprintf("%s%d", powerChacheKey, pId))
- }
- }
- }
- //通过mongo查找职位标识
- if pId := getPositionIdByMongoUserId(userId); pId > 0 {
- userId = fmt.Sprint(pId)
- }
- }
- _, _ = g.Redis("newother").Del(ctx, fmt.Sprintf(powerChacheKey, userId))
- _, _ = g.Redis("newother").Del(ctx, fmt.Sprintf("jy_workdesktopmenu_10000_menu1_%s", userId))
- _, _ = g.Redis("newother").Del(ctx, fmt.Sprintf("jy_userpowerredis_10000_17_%s", userId))
- _, _ = g.Redis("newother").Del(ctx, fmt.Sprintf("jy_workdesktopmenu_10000_menu2_%s", userId))
- _, _ = g.Redis("newother").Del(ctx, fmt.Sprintf("jy_workdesktopmenu_10000_PC_menu2_%s", userId))
- _, _ = g.Redis("newother").Del(ctx, fmt.Sprintf("jy_workdesktopmenu_10000_WX_menu2_%s", userId))
- _, _ = g.Redis("newother").Del(ctx, fmt.Sprintf("jy_workdesktopmenu_10000_APP_menu2_%s", userId))
- _, _ = g.Redis("newother").Del(ctx, fmt.Sprintf("user_power_info_%s", userId))
- _, _ = g.Redis("newother").Del(ctx, fmt.Sprintf(IsGetUserBaseInfoRedisKey, userId))
- _, _ = g.Redis("newother").Del(ctx, fmt.Sprintf(RedisMenuKeyPC, userId))
- _, _ = g.Redis("newother").Del(ctx, fmt.Sprintf(RedisMenuKeyWX, userId))
- _, _ = g.Redis("newother").Del(ctx, fmt.Sprintf(RedisMenuKeyAPP, userId))
- _, _ = g.Redis("newother").Del(ctx, fmt.Sprintf(UserPowerRedisKey, time.Now().Day(), userId))
- _, _ = g.Redis("newother").Del(ctx, "pl_indexMessage_"+userId)
- }
- func PayUserIdentitySwitchRedis(mgoUserId string, data map[string]interface{}) {
- key := fmt.Sprintf("jy_identitySwitch_%s", mgoUserId)
- _ = g.Redis("newother").SetEX(ctx, key, data, -1)
- }
- func GetUserMsgFromCtx(ctx context.Context) *model.User {
- if value := ctx.Value(consts.ContextKey); value != nil {
- if c, ok := value.(*model.User); ok {
- return c
- }
- }
- return nil
- }
- func GetUserDeptIdFromCtx(ctx context.Context) int64 {
- if u := GetUserMsgFromCtx(ctx); u != nil {
- return u.EntDeptId
- }
- return 0
- }
- func MultipleSaveMsg(msg map[string]interface{}, userIds, positionIds string) {
- log.Println("开始调用MultipleSaveMsg保存消息")
- idsJson, _ := json.Marshal(map[string]interface{}{"msgInfo": msg, "userIds": userIds, "userNames": "对公转账审批", "positionIds": positionIds})
- reqData := bytes.NewBuffer([]byte(idsJson))
- multipleSaveMsgUrl := common.ObjToString(g.Cfg().MustGet(context.Background(), "multipleSaveMsgUrl").String())
- method := "POST"
- client := &http.Client{}
- req, err := http.NewRequest(method, multipleSaveMsgUrl, reqData)
- if err != nil {
- log.Println("MultipleSaveMsg构造请求出错:", err)
- return
- }
- req.Header.Add("Content-Type", "application/json")
- res, err := client.Do(req)
- if err != nil {
- log.Println("MultipleSaveMsg发送请求出错:", err)
- return
- }
- defer res.Body.Close()
- body, err := ioutil.ReadAll(res.Body)
- if err != nil {
- log.Println("MultipleSaveMsg读取返回值出错:", err)
- return
- }
- dat := make(map[string]interface{})
- err = json.Unmarshal(body, &dat)
- if err != nil {
- log.Println("MultipleSaveMsg Unmarshal 出错:", err, msg)
- }
- //log.Println("调用中台返回结果", dat)
- return
- }
- // GetPositionByPhone 获取当前销售人员职位id
- func GetPositionByPhone(phone string) (int64, error) {
- res, _ := g.DB().GetOne(ctx, `SELECT b.id FROM base_service.base_user u INNER JOIN base_service.base_position b on(u.id=b.user_id AND b.ent_id = '25917' AND u.phone=?)`, phone)
- if res.IsEmpty() {
- return -1, fmt.Errorf("查询职位id异常")
- }
- posId := common.Int64All(res.Map()["id"])
- if posId <= 0 {
- return -1, fmt.Errorf("获取职位id异常")
- }
- return posId, nil
- }
- // sellerCheck 查询当前销售是否有权限操作改用户
- // 规则 满足1和2中任意一条
- // 1.新增-管理后台与电销系统用户匹配:同步电销系统组织架构,根据手机号对管理后台用户与电销系统的人员进行匹配;
- // 2.“帮助用户下单”增加限制条件,即下单用户需在下单电销人员私海里,且近期电销人员与该用户有过沟通,“有过沟通”判断依据(满足以下任意1个条件即可):
- // (1)最近3天(可配置)该电销人员与用户存在通话时长≥60秒(可配置);
- // (2)最近3天(可配置)该电销人员与该用户存在已上传附件的跟进记录;
- // (3)该电销人员与该用户正在通话中。
- func SellerCheck(ctx context.Context, posId int64, UserPhone string) error {
- var (
- total int
- err error
- )
- total, err = g.DB("subject").GetCount(ctx, fmt.Sprintf("SELECT * FROM dwd_f_crm_clue_info a inner join dwd_f_userbase_contacts b on a.uid=b.baseinfo_id WHERE b.phone='%s' and a.position_id=%d", UserPhone, posId))
- if err != nil {
- return err
- }
- if total == 0 {
- return fmt.Errorf("不满足代用户下单条件,不支持下单")
- }
- //2(1)
- var (
- uid string
- phoneArr []string
- phonesStr string
- )
- res, err := g.DB("subject").Query(ctx, fmt.Sprintf("SELECT baseinfo_id,phone FROM dwd_f_userbase_contacts WHERE baseinfo_id=(SELECT baseinfo_id FROM dwd_f_userbase_contacts WHERE phone='%s')", UserPhone))
- if res.IsEmpty() {
- return fmt.Errorf("查询手机号异常")
- }
- for i, m := range res.List() {
- if i == 0 {
- uid = common.ObjToString(m["baseinfo_id"])
- }
- if p := common.ObjToString(m["phone"]); p != "" {
- phoneArr = append(phoneArr, p)
- }
- }
- phonesStr = strings.Join(phoneArr, "','")
- //(1)最近3天(可配置)该电销人员与用户存在通话时长≥60秒(可配置);
- if num, err := g.DB("subject").GetCount(ctx, fmt.Sprintf(`SELECT *
- FROM Call_Accounting.voice_record
- WHERE CallTimeLength >= ?
- AND Ring > (SELECT DATE_SUB(NOW(), INTERVAL ? HOUR))
- AND Exten IN (
- SELECT seat_number
- FROM dwd_f_crm_personnel_management
- WHERE position_id = ?
- )
- AND (CallNo in ('%s') or CalledNo in ('%s'))`, phonesStr, phonesStr), g.Cfg().MustGet(ctx, "helpUserOrder.talkTimeLong", 60).Int64(), g.Cfg().MustGet(ctx, "helpUserOrder.talkHourLimit", 72).Int64(), posId); err == nil && num > 0 {
- return nil
- }
- //(2)最近3天(可配置)该电销人员与该用户存在已上传附件的跟进记录;
- if num, err := g.DB("subject").GetCount(ctx, `SELECT *
- FROM dwd_f_crm_clue_info a
- INNER JOIN dwd_f_crm_trail_content b ON a.id =b.clue_id
- INNER JOIN attachment c ON b.id =c.change_id
- WHERE a.uid =? AND b.createtime >DATE_SUB(NOW(), INTERVAL ? HOUR) AND type='跟进记录附件'`, uid, g.Cfg().MustGet(ctx, "helpUserOrder.trailAttach", 72).Int64()); err == nil && num > 0 {
- return nil
- }
- //(3)该电销人员与该用户正在通话中。
- if num, err := g.DB("subject").GetCount(ctx, `SELECT * FROM dwd_f_userbase_contacts
- WHERE baseinfo_id=? AND is_talking=1
- AND is_talking_seat_number IN(
- SELECT seat_number
- FROM dwd_f_crm_personnel_management
- WHERE position_id = ?)`, uid, posId); err == nil && num > 0 {
- return nil
- }
- return fmt.Errorf("不满足代用户下单条件,不支持下单")
- }
|