1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237 |
- package service
- import (
- "database/sql"
- "fmt"
- "log"
- "strconv"
- "strings"
- "sync"
- "time"
- quitl "app.yhyue.com/moapp/jybase/common"
- "app.yhyue.com/moapp/jybase/date"
- "app.yhyue.com/moapp/jybase/encrypt"
- util "bp.jydev.jianyu360.cn/SocialPlatform/messageCenter/entity"
- IC "bp.jydev.jianyu360.cn/SocialPlatform/messageCenter/rpc/messagecenter/init"
- "bp.jydev.jianyu360.cn/SocialPlatform/messageCenter/rpc/messagecenter/messagecenter"
- "github.com/gogf/gf/v2/util/gconv"
- )
- type MessaggeService struct{}
- var rwLock = new(sync.RWMutex)
- // Count 未读消息查询
- func (b MessaggeService) Count(newUserId int64) (count int, last map[string]interface{}, err error) {
- //导航右上角未读消息总量 1v1聊天+群组消息+客服消息
- //v := make([]interface{}, 0)
- var (
- allSql string
- sqlArr []string
- )
- //一对一
- oneSql := fmt.Sprintf(`(SELECT
- a.your_position_id AS id,
- 1 AS userType,
- c.nickname AS name,
- c.headimg,
- d.content,
- d.type,
- d.create_time,
- a.unread as number,
- a.timestamp
- FROM
- socialize_summary a
- INNER JOIN base_position b ON ( a.my_position_id = %d AND a.unread > 0 AND a.your_position_id = b.id )
- INNER JOIN base_user c ON ( b.user_id = c.id )
- LEFT JOIN socialize_message d ON ( a.message_id = d.id ))`, newUserId)
- //客服列表
- serviceSql := fmt.Sprintf(` (
- SELECT
- a.ent_id AS id,
- 2 AS userType,
- b.nickname AS name,
- b.headimage as headimg,
- c.content,
- c.type,
- c.create_time,
- a.unread as number,
- a.timestamp
- FROM
- socialize_summary a
- INNER JOIN socialize_tenant_robot b ON ( a.user_id = %d AND a.unread > 0 AND a.ent_id = b.ent_id )
- LEFT JOIN socialize_message c ON ( a.message_id = c.id )
- ) `, newUserId)
- //群列表
- groupSql := fmt.Sprintf(` (
- SELECT
- b.id,
- 3 AS userType,
- b.name,
- '' AS headimg,
- d.content,
- d.type,
- d.create_time,
- a.unread as number,
- c.timestamp
- FROM
- socialize_chat_group_person a
- INNER JOIN socialize_chat_group b ON ( a.position_id = %d AND a.unread > 0 AND a.chat_group_id = b.id AND b.isdismiss = 0)
- INNER JOIN socialize_summary c ON ( b.id = c.chat_group_id )
- LEFT JOIN socialize_message d ON ( c.message_id = d.id )
- ) `, newUserId)
- allSql = strings.Join(append(sqlArr, oneSql, groupSql, serviceSql), " union ")
- log.Println("查询sql", allSql)
- data := IC.BaseMysql.SelectBySql(allSql)
- log.Println("查询数据:", data)
- return
- }
- // 用户列表查询
- func (b MessaggeService) UserList(in *messagecenter.UserReq) (data *[]map[string]interface{}, count int64, err error) {
- sqlStr := ""
- tm := time.Now()
- if in.UserType == 2 {
- var (
- allSql, positionIdArr, oneSql, oneNameSql, serviceNameSql string
- sqlArr []string
- )
- GroupNameSql := `(SELECT *,"" as groupMember FROM socialize_chat_group where isdismiss = 0)` //无搜索群
- if in.NameSearch != "" {
- serviceNameSql = " AND b.nickname like '%" + in.NameSearch + "%'"
- GroupNameSql = `(SELECT id,name,"" as groupMember FROM socialize_chat_group WHERE isdismiss = 0 AND name like '%` + in.NameSearch + `%')` //默认搜素群名称
- positionIdArr = NameToPositionIdp(in.NameSearch, in.EntId)
- if positionIdArr != "" {
- oneNameSql = " AND find_in_set(b.id,'" + positionIdArr + "')" //1v1搜索成员id
- //存在满足成员名时 重新定义搜索sql 并兼容群名称不满足但成员名满足时也展示 并展示部分满足群员名
- nameSearch := " or b.name like '%" + in.NameSearch + "%')"
- name := fmt.Sprintf(" AND (c.position_id IN ( %s ) %s", positionIdArr, nameSearch)
- GroupNameSql = fmt.Sprintf(` (
- SELECT
- a.chat_group_id as id,
- GROUP_CONCAT( distinct c.position_id ) as groupMember,
- GROUP_CONCAT( distinct b.name ) as name
- FROM
- socialize_chat_group_person a
- INNER JOIN socialize_chat_group b ON a.position_id=%d AND a.chat_group_id = b.id AND b.isdismiss = 0
- INNER JOIN socialize_chat_group_person c ON a.chat_group_id = c.chat_group_id %s
- GROUP BY
- a.chat_group_id)`, in.PositionId, name) //群搜索
- }
- }
- log.Println("用户列表展示", in.NameSearch, in.EntId, oneNameSql)
- //1v1 无搜索时 或搜索有结果时
- if in.NameSearch == "" || oneNameSql != "" {
- oneSql = fmt.Sprintf(`(SELECT
- a.your_position_id AS id,
- 2 AS userType,
- c.nickname AS name,
- c.headimg,
- d.content,
- d.type,
- d.create_time,
- a.unread as number,
- a.timestamp,
- c.phone,
- "" as groupMember
- FROM
- socialize_summary a
- INNER JOIN base_position b ON ( a.my_position_id = %d %s AND a.your_position_id = b.id )
- INNER JOIN base_user c ON ( b.user_id = c.id )
- LEFT JOIN socialize_message d ON ( a.message_id = d.id )
- ORDER BY a.timestamp DESC LIMIT 0,500
- )`, in.PositionId, oneNameSql)
- }
- //客服列表
- serviceSql := fmt.Sprintf(` (
- SELECT
- a.ent_id AS id,
- 1 AS userType,
- b.nickname AS name,
- b.headimage as headimg,
- c.content,
- c.type,
- c.create_time,
- a.unread as number,
- a.timestamp,
- "" as phone,
- "" as groupMember
- FROM
- socialize_summary a
- INNER JOIN socialize_tenant_robot b ON ( a.user_id = %d AND a.ent_id = b.ent_id %s )
- LEFT JOIN socialize_message c ON ( a.message_id = c.id )
- ORDER BY a.timestamp DESC LIMIT 0,500
- ) `, in.NewUserId, serviceNameSql)
- //群列表
- groupSql := fmt.Sprintf(` (
- SELECT
- b.id,
- 3 AS userType,
- b.name,
- '' AS headimg,
- d.content,
- d.type,
- d.create_time,
- a.unread as number,
- c.timestamp,
- "" as phone,
- b.groupMember
- FROM
- socialize_chat_group_person a
- INNER JOIN %s b ON ( a.position_id = %d AND a.chat_group_id = b.id)
- INNER JOIN socialize_summary c ON ( b.id = c.chat_group_id )
- LEFT JOIN socialize_message d ON ( c.message_id = d.id )
- ORDER BY c.timestamp DESC LIMIT 0,500
- ) `, GroupNameSql, in.PositionId)
- switch in.QueryType {
- case 1: //分享列表
- if oneSql != "" {
- sqlArr = append(sqlArr, oneSql)
- }
- if groupSql != "" {
- sqlArr = append(sqlArr, groupSql)
- }
- if len(sqlArr) > 1 {
- allSql = strings.Join(sqlArr, " UNION ALL ")
- } else {
- allSql = sqlArr[0]
- }
- default:
- //历史会话列表
- if oneSql != "" {
- sqlArr = append(sqlArr, oneSql)
- }
- if groupSql != "" {
- sqlArr = append(sqlArr, groupSql)
- }
- if serviceSql != "" {
- sqlArr = append(sqlArr, serviceSql)
- }
- allSql = strings.Join(sqlArr, " UNION ALL ")
- }
- sqlStr = fmt.Sprintf(`SELECT * FROM(
- %s
- ) a ORDER BY a.timestamp DESC LIMIT 0,500`, allSql)
- } else {
- var timeSql, phoneSql, filtrationSql string
- if in.StartTime != "" {
- timeSql += fmt.Sprintf(" AND a.timestamp > %s", in.StartTime)
- }
- if in.EndTime != "" {
- timeSql += fmt.Sprintf(" AND a.timestamp < %s", in.EndTime)
- }
- if in.Phone != "" {
- phoneSql = " AND b.phone like '%" + in.Phone + "%'"
- }
- if in.FiltrationId != "" {
- var ids []string
- for _, v := range strings.Split(in.FiltrationId, ",") {
- ids = append(ids, encrypt.SE.Decode4Hex(v))
- }
- filtrationSql += fmt.Sprintf(" AND b.id not in (%s)", strings.Join(ids, ","))
- }
- aiSql := fmt.Sprintf(`(SELECT
- a.user_id,
- a.message_id,
- a.timestamp,
- b.nickname,
- 0 as unread,
- b.headimg,
- "" as phone,
- 0 as userType
- FROM
- socialize_summary a
- INNER JOIN base_user b ON (a.user_id = b.id AND a.ent_id = %d AND a.customer_service_access = 0))
- %s %s %s)`, in.EntId, timeSql, phoneSql, filtrationSql)
- serviceSql := fmt.Sprintf(`(SELECT
- a.user_id,
- c.message_id,
- c.timestamp,
- b.nickname,
- a.unread,
- b.headimg,
- "" as phone,
- 0 as userType
- FROM
- socialize_customer_service_user a
- INNER JOIN base_user b ON ( a.customer_service_id = %d AND a.user_id = b.id %s %s)
- INNER JOIN socialize_summary c ON ( a.ent_id = c.ent_id AND a.user_id = c.user_id %s))`, in.EntUserId, filtrationSql, phoneSql,
- strings.ReplaceAll(timeSql, "a.", "c."))
- var restrictionSql string
- switch in.IsArtificial {
- case 1:
- restrictionSql = serviceSql
- case 2:
- restrictionSql = aiSql
- default:
- restrictionSql = aiSql + " UNION ALL " + serviceSql
- }
- if in.Page <= 0 {
- in.Page = 1
- }
- if in.Size <= 0 || in.Size > 100 {
- in.Size = 50
- }
- sqlStr = fmt.Sprintf(`SELECT
- (
- CASE
- WHEN SUBSTR( a.nickname, 1, 3 ) = 'JY_' THEN
- CONCAT( SUBSTR( a.phone, 1, 3 ), '****', SUBSTR( a.phone, 8, 11 ) )
- WHEN a.nickname = ''
- OR a.nickname IS NULL THEN
- CONCAT( SUBSTR( a.phone, 1, 3 ), '****', SUBSTR( a.phone, 8, 11 ) ) ELSE a.nickname
- END
- ) AS name,
- c.content,
- c.title,
- c.type,
- c.link,
- c.create_time,
- a.message_id,
- a.timestamp,
- a.unread as number,
- a.user_id as id,
- a.headimg,
- a.phone,
- a.userType
- FROM
- (%s) a
- LEFT JOIN socialize_message c ON ( a.message_id = c.id )
- ORDER BY
- a.timestamp DESC`, restrictionSql)
- }
- var dataSize []map[string]interface{}
- if sqlStr != "" {
- log.Println("查询列表sql:", sqlStr)
- data = IC.BaseMysql.SelectBySql(sqlStr)
- if data != nil && len(*data) > 0 {
- count = quitl.Int64All(len(*data))
- log.Println("查询列表耗时2:", time.Since(tm), in.QueryType, count)
- switch in.UserType { //客服查询结果分页
- case 1:
- if in.Page*in.Size >= count {
- dataSize = (*data)[(in.Page-1)*in.Size:]
- } else {
- dataSize = (*data)[(in.Page-1)*in.Size : in.Page*in.Size]
- }
- return &dataSize, count, err
- case 2: //用户查询结果
- phoneMap, _, positionMap := EntPerson(in.EntId, true) //获取企业架构人员名称
- for _, v := range *data {
- if quitl.IntAll(v["userType"]) == 2 {
- v["name"] = phoneMap[quitl.InterfaceToStr(v["phone"])]
- } else if quitl.IntAll(v["userType"]) == 3 {
- var names []string
- if quitl.InterfaceToStr(v["groupMember"]) != "" {
- for _, id := range strings.Split(quitl.InterfaceToStr(v["groupMember"]), ",") {
- if len(names) > 4 {
- break
- }
- //防止匹配的是群名称 去除不匹配的群成员
- if strings.Contains(positionMap[quitl.IntAll(id)], in.NameSearch) {
- names = append(names, positionMap[quitl.IntAll(id)])
- }
- }
- }
- v["groupMember"] = names
- }
- }
- }
- }
- }
- return
- }
- // 客服会话列表
- func (b MessaggeService) ConversationList(in *messagecenter.ConversationReq) (data *[]map[string]interface{}, count int64, err error) {
- sqlStr := ""
- tm := time.Now()
- if in.UserType == 1 && in.FiltrationId != "" {
- var ids []string
- for _, v := range strings.Split(in.FiltrationId, ",") {
- ids = append(ids, encrypt.SE.Decode4Hex(v))
- }
- filtrationSql := fmt.Sprintf(" AND b.id in (%s)", strings.Join(ids, ","))
- aiSql := fmt.Sprintf(`(SELECT
- a.user_id,
- a.message_id,
- a.timestamp,
- b.nickname,
- 0 as unread,
- b.headimg
- FROM
- socialize_summary a
- INNER JOIN base_user b ON (a.user_id = b.id AND a.ent_id = %d AND a.customer_service_access = 0
- %s ))`, in.EntId, filtrationSql)
- serviceSql := fmt.Sprintf(`(SELECT
- a.user_id,
- c.message_id,
- c.timestamp,
- b.nickname,
- a.unread,
- b.headimg
- FROM
- socialize_customer_service_user a
- INNER JOIN base_user b ON ( a.customer_service_id = %d AND a.user_id = b.id %s)
- INNER JOIN socialize_summary c ON ( a.ent_id = c.ent_id AND a.user_id = c.user_id))`, in.EntUserId, filtrationSql)
- sqlStr = aiSql + " UNION ALL " + serviceSql
- }
- if sqlStr != "" {
- log.Println("查询列表sql:", sqlStr)
- data = IC.BaseMysql.SelectBySql(sqlStr)
- log.Println("查询耗时2:", time.Since(tm), count)
- }
- return
- }
- // 消息保存
- func (b MessaggeService) SaveMessage(in *messagecenter.MessageEntity) (fool bool, errorMsg string, content string, messageId, nowInt int64) {
- //先插入信息表
- //判断会话标识是否属于本人
- var customer_service_id, userid, entid, message_id int64
- nowForm := time.Now().Local()
- create_time := nowForm.Format(util.Date_Full_Layout)
- if in.ItemType != 2 {
- userId := int64(0)
- sessionId := int64(0)
- switch in.ItemType {
- case 4, 5, 8:
- if in.OwnType == 1 {
- sessionId = in.ReceiveId
- userId = in.NewUserId
- } else {
- sessionId = in.SendId
- userId = in.ReceiveId
- if in.ItemType == 4 || in.ItemType == 8 {
- userId = in.NewUserId
- }
- }
- break
- case 6:
- if in.OwnType == 1 {
- sessionId = in.ReceiveId
- userId = in.NewUserId
- } else if in.OwnType == 2 {
- sessionId = in.SendId
- userId = in.ReceiveId
- } else {
- sessionId = in.ReceiveId
- userId = in.NewUserId
- }
- break
- }
- //查找会话信息
- chatJson := IC.BaseMysql.FindOne(util.SOCIALIZE_CHAT_SESSION, map[string]interface{}{"id": sessionId}, "user_id,ent_id,customer_service_id", "")
- if chatJson == nil {
- return false, "会话标识不存在", "", 0, nowForm.Unix()
- } else {
- if userId != quitl.Int64All((*chatJson)["user_id"]) {
- return false, "会话标识不属于此用户", "", 0, nowForm.Unix()
- }
- }
- customer_service_id = quitl.Int64All((*chatJson)["customer_service_id"])
- entid = quitl.Int64All((*chatJson)["ent_id"])
- userid = userId
- }
- fool = IC.BaseMysql.ExecTx("聊天信息保存", func(tx *sql.Tx) bool {
- //先插入信息表
- userType := int64(1)
- userId := int64(0)
- message := map[string]interface{}{
- "appid": in.Appid,
- "title": in.Title,
- "content": in.Content,
- "item": in.Item,
- "type": in.Type,
- "link": in.Link,
- "create_time": create_time,
- "create_person": in.SendId,
- }
- data := map[string]interface{}{
- "item": in.Item,
- "type": in.Type,
- "create_time": create_time,
- "content": in.Content,
- }
- ok := IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_MESSAGE, message)
- receiveOk := int64(0)
- messageId, message_id = ok, ok
- data["id"] = ok
- //在插入邮箱表socialize_message_mailbox
- messageMailBox := map[string]interface{}{
- "appid": in.Appid,
- "messag_id": ok,
- "type": in.ItemType,
- "create_time": nowForm.Format(util.Date_Full_Layout),
- "isread": 0,
- "send_isdel": 0,
- "receive_isdel": 0,
- "iswithdraw": 0,
- }
- //系统信息处理
- if in.ItemType == 6 {
- messageMailBox = map[string]interface{}{
- "appid": in.Appid,
- "messag_id": ok,
- "type": in.ItemType,
- "create_time": nowForm.Format(util.Date_Full_Layout),
- "read_time": nowForm.Format(util.Date_Full_Layout),
- "isread": 1,
- "send_isdel": 0,
- "receive_isdel": 0,
- "iswithdraw": 0,
- }
- if in.OwnType == 1 {
- //用户接受系统信息
- messageMailBox["own_type"] = 2
- messageMailBox["send_user_type"] = 1
- messageMailBox["receive_user_type"] = 2
- messageMailBox["own_id"] = in.NewUserId
- messageMailBox["send_user_id"] = in.ReceiveId
- messageMailBox["receive_user_id"] = in.NewUserId
- } else if in.OwnType == 2 {
- //客服接受系统信息
- messageMailBox["own_type"] = 1
- messageMailBox["send_user_type"] = 2
- messageMailBox["receive_user_type"] = 1
- messageMailBox["own_id"] = in.SendId
- messageMailBox["send_user_id"] = in.ReceiveId
- messageMailBox["receive_user_id"] = in.SendId
- } else {
- //客服接受系统信息
- messageMailBox["own_type"] = 1
- messageMailBox["send_user_type"] = 2
- messageMailBox["receive_user_type"] = 1
- messageMailBox["own_id"] = in.ReceiveId
- messageMailBox["send_user_id"] = in.NewUserId
- messageMailBox["receive_user_id"] = in.ReceiveId
- }
- receiveOk = IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_MESSAGE_MAILBOX, messageMailBox)
- return ok > 1 && receiveOk > 1
- }
- if in.ItemType == 4 || in.ItemType == 8 || in.ItemType == 5 {
- //客服或者机器人聊天
- if in.OwnType == 1 {
- // (用户发送)客服接受
- messageMailBox["own_type"] = 1
- messageMailBox["send_user_type"] = 2
- messageMailBox["receive_user_type"] = 1
- messageMailBox["own_id"] = in.ReceiveId
- messageMailBox["send_user_id"] = in.NewUserId
- messageMailBox["receive_user_id"] = in.ReceiveId
- userType = 1
- userId = in.ReceiveId
- } else {
- //客服发送(用户接收信息)
- messageMailBox["own_type"] = 2
- messageMailBox["send_user_type"] = 1
- messageMailBox["receive_user_type"] = 2
- messageMailBox["own_id"] = in.ReceiveId
- messageMailBox["send_user_id"] = in.SendId
- messageMailBox["receive_user_id"] = in.ReceiveId
- userId = in.ReceiveId
- if in.ItemType == 4 || in.ItemType == 8 {
- messageMailBox["receive_user_id"] = in.NewUserId
- userId = in.NewUserId
- messageMailBox["own_id"] = in.NewUserId
- messageMailBox["isread"] = 1
- messageMailBox["read_time"] = nowForm.Format(util.Date_Full_Layout)
- }
- userType = 2
- }
- } else {
- messageMailBox["own_type"] = 2
- messageMailBox["send_user_type"] = 2
- messageMailBox["receive_user_type"] = 2
- messageMailBox["own_id"] = in.ReceiveId
- messageMailBox["send_user_id"] = in.NewUserId
- messageMailBox["receive_user_id"] = in.ReceiveId
- userType = 2
- userId = in.ReceiveId
- }
- receiveOk = IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_MESSAGE_MAILBOX, messageMailBox)
- messageMailBox = map[string]interface{}{
- "appid": in.Appid,
- "messag_id": ok,
- "type": in.ItemType,
- "create_time": nowForm.Format(util.Date_Full_Layout),
- "read_time": nowForm.Format(util.Date_Full_Layout),
- "isread": 1,
- "send_isdel": 0,
- "receive_isdel": 0,
- "iswithdraw": 0,
- }
- if in.ItemType == 4 || in.ItemType == 8 || in.ItemType == 5 {
- //客服或者机器人聊天
- if in.OwnType == 1 {
- //用户发送(用户接受)
- messageMailBox["own_type"] = 2
- messageMailBox["send_user_type"] = 2
- messageMailBox["receive_user_type"] = 1
- messageMailBox["own_id"] = in.NewUserId
- messageMailBox["send_user_id"] = in.NewUserId
- messageMailBox["receive_user_id"] = in.ReceiveId
- } else {
- //客服发送信息(用户接受)
- messageMailBox["own_type"] = 1
- messageMailBox["send_user_type"] = 1
- messageMailBox["receive_user_type"] = 2
- messageMailBox["own_id"] = in.SendId
- messageMailBox["send_user_id"] = in.SendId
- messageMailBox["receive_user_id"] = in.ReceiveId
- if in.ItemType == 4 || in.ItemType == 8 {
- messageMailBox["receive_user_id"] = in.NewUserId
- }
- }
- } else {
- messageMailBox["own_type"] = 2
- messageMailBox["send_user_type"] = 2
- messageMailBox["receive_user_type"] = 2
- messageMailBox["own_id"] = in.NewUserId
- messageMailBox["send_user_id"] = in.NewUserId
- messageMailBox["receive_user_id"] = in.ReceiveId
- }
- receiveOk = IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_MESSAGE_MAILBOX, messageMailBox)
- if ok > 1 && receiveOk > 1 {
- pc_a, err := util.GetData(userType, userId)
- count := 1
- if err == nil && pc_a != nil {
- count += pc_a.Count
- }
- util.SetData(userType, userId, map[string]interface{}{"data": data, "count": count}, IC.SurvivalTime)
- }
- return ok > 1 && receiveOk > 1
- })
- if fool && in.ItemType != 2 && in.ItemType != 3 {
- go UserSynchronousList(customer_service_id, userid, entid, message_id, create_time)
- }
- return fool, "", in.Content, messageId, nowForm.Unix()
- }
- // 客服 用户聊天消息列表同步
- func UserSynchronousList(customerServiceId, userId, entId, messageId int64, createTime string) {
- log.Printf("同步最后消息参数customerServiceId:%d,userId:%d,entId%d,messageId:%d", customerServiceId, userId, entId, messageId)
- rwLock.Lock()
- defer rwLock.Unlock()
- if IC.BaseMysql.Count(util.User_message_list, map[string]interface{}{"user_id": userId, "ent_id": entId}) > 0 {
- upData := map[string]interface{}{
- "message_id": messageId,
- "update_time": createTime,
- }
- //判断是否机器人聊天
- if customerServiceId > 0 && IC.BaseMysql.Count(util.User_message_list, map[string]interface{}{"user_id": userId, "ent_id": entId, "customer_service_id": 0}) > 0 {
- //将机器人列表更新成用户
- upData["customer_service_id"] = customerServiceId
- //转人工 机器人聊天类型修改
- upData["type"] = 1
- }
- //已于人工客服联系过 只同步最后消息
- IC.BaseMysql.Update(util.User_message_list, map[string]interface{}{"user_id": userId, "ent_id": entId}, upData)
- return
- }
- //不存在消息列表 创建
- IC.BaseMysql.Insert(util.User_message_list, map[string]interface{}{
- "ent_id": entId,
- "user_id": userId,
- "message_id": messageId,
- "update_time": createTime,
- "customer_service_id": customerServiceId,
- "type": quitl.If(customerServiceId == 0, 0, 1),
- })
- }
- // 历史信息查询
- func (b MessaggeService) FindMessage(in *messagecenter.MessageReq) *[]map[string]interface{} {
- log.Println(in.PositionId, in.NewUserId, in.EntId, in.ChatGroupId)
- sqlStr := ""
- lastStr := ""
- positionStr := ""
- if in.LastId > 0 {
- if in.Sort == "asc" {
- lastStr = fmt.Sprintf("AND a.messag_id > %d ", in.LastId)
- } else {
- lastStr = fmt.Sprintf("AND a.messag_id < %d ", in.LastId)
- }
- }
- switch in.MsgType {
- case 2: //点对点聊天
- sqlStr = fmt.Sprintf("SELECT a.messag_id as messageId,b.* ,if(a.own_id = a.send_user_id,1,2) as fool "+
- "FROM %s a "+
- "LEFT JOIN %s b on a.messag_id=b.id "+
- "LEFT JOIN %s c on c.id=a.send_user_id "+
- "LEFT JOIN %s d on d.id=a.receive_user_id "+
- "where a.own_id= %d and a.iswithdraw = 0"+
- "AND ((a.send_user_id= %d AND a.receive_user_id= %d) or (a.send_user_id= %d AND a.receive_user_id= %d)) "+
- "AND a.type=2 %s "+
- "ORDER BY a.create_time desc,a.id asc "+
- "limit 0 , %d ",
- util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_MESSAGE, util.BASE_USER, util.BASE_USER,
- in.PositionId, in.PositionId, in.SendId, in.SendId, in.PositionId, lastStr, in.PageSize)
- break
- case 3: //群聊天
- sqlStr = fmt.Sprintf("SELECT a.messag_id AS messageId,b.*,"+
- "IF ( a.own_id = a.send_user_id, 1, 2 ) AS fool,"+
- "IF ( a.own_id = a.send_user_id, 0, a.send_user_id ) AS send_position_id,"+
- "a.send_user_type,a.type AS itemType FROM %s a "+
- "LEFT JOIN %s b ON a.messag_id = b.id "+
- "WHERE a.own_type = 2 AND a.own_id = %d "+
- "AND a.chat_group_id = %d AND a.type IN ( 3, 6 ) "+
- "ORDER BY a.create_time desc,a.id DESC "+
- "LIMIT 0, %d",
- util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_MESSAGE, in.PositionId,
- in.ChatGroupId, in.PageSize)
- case 4, 5, 6, 7: //客服聊天
- //查询用户所有的职位id
- positionStr = GetUserAllPosition(in.NewUserId)
- if in.UserType == 1 {
- //客服聊天记录查看
- sqlStr = fmt.Sprintf("SELECT a.messag_id as messageId,b.*, IF ( a.own_id = a.send_user_id, 1, 2 ) AS fool, a.send_user_type, a.type AS itemType, '' AS robotName, '' AS robotImg, c.customer_service_name AS setName , c.user_id "+
- "FROM %s a "+
- "LEFT JOIN %s b ON a.messag_id = b.id "+
- "LEFT JOIN %s c ON a.own_type = 1 AND a.own_id=c.id "+
- "WHERE a.own_type = 1 and a.iswithdraw = 0 "+
- "AND (a.type = 5 or a.type=4 or a.type=6 or a.type=7 or a.type=8 ) "+
- "AND c.ent_id = %d "+
- "AND c.user_id in (%s) %s "+
- "ORDER BY a.create_time desc ,a.id asc "+
- "limit 0 , %d ",
- util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_MESSAGE, util.SOCIALIZE_CHAT_SESSION,
- in.EntId, positionStr, lastStr, in.PageSize)
- } else {
- //用户聊天记录查看
- sqlStr = fmt.Sprintf("SELECT a.messag_id as messageId,e.appraise as appraise, b.*, IF ( a.own_id = a.send_user_id, 1, 2 ) AS fool , a.send_user_type, a.type as itemType, d.nickname as robotName, d.headimage as robotImg, c.customer_service_name as setName "+
- "FROM %s a "+
- "LEFT JOIN %s b ON a.messag_id = b.id "+
- "LEFT JOIN %s c ON IF ( a.send_user_type = 1, a.send_user_id, a.receive_user_id ) = c.id AND c.user_id in (%s) "+
- "LEFT JOIN %s d on c.ent_id=d.ent_id "+
- "LEFT JOIN %s e on b.id=e.messag_id "+
- "WHERE a.own_type = 2 "+
- "AND a.own_id in (%s) "+
- //"AND c.ent_id = %d "+
- "AND c.user_id in (%s) "+
- "AND ( a.type = 4 OR a.type = 5 or a.type=6 or a.type=7) %s "+
- "ORDER BY a.create_time desc ,a.id asc "+
- "limit 0 , %d ",
- util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_MESSAGE, util.SOCIALIZE_CHAT_SESSION, positionStr, util.SOCIALIZE_TENANT_ROBOT,
- util.SOCIALIZE_APPRAISE, positionStr, positionStr, lastStr, in.PageSize)
- }
- break
- }
- log.Println(sqlStr)
- data := IC.BaseMysql.SelectBySql(sqlStr)
- //查询非自己发送消息得发送人名字
- //自己头像处理
- if in.UserType == 2 {
- userData := IC.BaseMysql.FindOne(util.BASE_USER, map[string]interface{}{"id": in.NewUserId}, "headimg", "")
- if userData != nil {
- for key := range *data {
- (*data)[key]["ownImg"] = (*userData)["headimg"]
- }
- }
- }
- if in.MsgType == 3 && data != nil && len(*data) > 0 {
- _, _, positionData := EntPerson(in.EntId, true)
- for _, v := range *data {
- positionId := quitl.IntAll(v["send_user_id"])
- if positionId != 0 {
- v["userName"] = positionData[positionId]
- }
- }
- }
- go func() {
- updateMap := map[string]interface{}{}
- if len(*data) > 0 && data != nil {
- //if true {
- //未读信息修改
- switch in.MsgType {
- case 2: //点对点聊天
- updateMap = map[string]interface{}{
- "own_type": 2,
- "own_id": in.NewUserId,
- "send_user_id": in.SendId,
- "type": 2,
- "isread": 0,
- }
- IC.BaseMysql.Update(util.SOCIALIZE_MESSAGE_MAILBOX, updateMap, map[string]interface{}{"isread": 1, "read_time": time.Now().Local().Format(util.Date_Full_Layout)})
- //更新socialize_summary表未读消息数量
- updateQuery := map[string]interface{}{
- "my_position_id": in.NewUserId,
- "your_position_id": in.SendId,
- }
- IC.BaseMysql.Update(util.SOCIALIZE_SUMMARY, updateQuery, map[string]interface{}{"unread": 0})
- break
- case 3: //群聊天
- sqlStr = fmt.Sprintf("UPDATE %s a SET a.isread = 1, a.read_time = now( ) "+
- "WHERE a.own_type = 1 "+
- "AND a.type IN (3,6) "+
- "AND a.isread = 0 "+
- "AND a.own_id = %d AND a.chat_group_id = %d",
- util.SOCIALIZE_MESSAGE_MAILBOX, in.SendId, in.ChatGroupId)
- IC.BaseMysql.UpdateOrDeleteBySql(sqlStr)
- //更新socialize_summary表未读消息数量
- updateQuery := map[string]interface{}{
- "my_position_id": in.NewUserId,
- "chat_group_id": in.ChatGroupId,
- }
- IC.BaseMysql.Update(util.SOCIALIZE_SUMMARY, updateQuery, map[string]interface{}{"unread": 0})
- case 4, 5:
- sqlStr := ""
- unreadSql := ""
- if in.UserType == 1 { //1客服
- sqlStr = fmt.Sprintf("UPDATE %s a SET a.isread = 1, a.read_time = now( ) "+
- "WHERE a.own_type = 1 and a.iswithdraw = 0 "+
- "AND a.type IN ( 4,5,6,7) "+
- "AND a.isread = 0 "+
- "AND a.own_id IN (SELECT id FROM %s WHERE user_id = %d)",
- util.SOCIALIZE_MESSAGE_MAILBOX, util.BASE_POSITION, in.NewUserId)
- unreadSql = fmt.Sprintf("UPDATE %s SET unread = 0 WHERE user_id = %d", util.Socialize_customer_service_user, in.NewUserId)
- } else { //2用户
- sqlStr = fmt.Sprintf("UPDATE %s a SET a.isread = 1, a.read_time = now( ) "+
- "WHERE a.own_type = 2 and a.iswithdraw = 0 "+
- "AND a.type IN ( 4,5,6,7 ) "+
- "AND a.isread = 0 "+
- "AND a.own_id in (%s) ", util.SOCIALIZE_MESSAGE_MAILBOX, positionStr)
- unreadSql = fmt.Sprintf("UPDATE %s SET unread = 0 WHERE user_id = %d", util.SOCIALIZE_SUMMARY, in.NewUserId)
- }
- IC.BaseMysql.UpdateOrDeleteBySql(sqlStr)
- IC.BaseMysql.UpdateOrDeleteBySql(unreadSql)
- break
- }
- //redis缓存处理
- //b.Count(in.NewUserId, in.UserType, in.EntUserId, true)
- }
- }()
- return data
- }
- // 创建会话
- func (b MessaggeService) CreateChatSession(in *messagecenter.ChatSessionReq) (fool bool, sessionId int64) {
- fool = IC.BaseMysql.ExecTx("会话新建", func(tx *sql.Tx) bool {
- customerserviceName := in.CustomerserviceName
- if in.CustomerServiceId != 0 {
- sqlStr := fmt.Sprintf("select customer_service_name from %s "+
- "where ent_id= %d "+
- "AND customer_service_id= %d ",
- util.SOCIALIZE_CHAT_SESSION, in.EntId, in.CustomerServiceId)
- customerList := IC.BaseMysql.SelectBySql(sqlStr)
- if len(*customerList) > 0 {
- customerserviceName = quitl.InterfaceToStr((*customerList)[0]["customer_service_name"])
- }
- }
- //查询企业是否存在
- count := IC.BaseMysql.Count(util.SOCIALIZE_TENANT_ROBOT, map[string]interface{}{
- "ent_id": in.EntId,
- })
- if count < 1 {
- return false
- }
- chatMession := map[string]interface{}{
- "handle_status": 0,
- "start_time": time.Now().Local().Format(util.Date_Full_Layout),
- "appid": in.AppId,
- "ent_id": in.EntId,
- "customer_service_id": in.CustomerServiceId,
- "user_id": in.UserId,
- "customer_service_name": customerserviceName,
- }
- sessionId = IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_CHAT_SESSION, chatMession)
- return sessionId > 0
- })
- return
- }
- // 结束会话
- func (b MessaggeService) CloseChatSession(in *messagecenter.CloseSessionReq) bool {
- fool := IC.BaseMysql.ExecTx("关闭会话", func(tx *sql.Tx) bool {
- updateMap := map[string]interface{}{
- "id": in.SessionId,
- }
- fool := IC.BaseMysql.Update(util.SOCIALIZE_CHAT_SESSION, updateMap, map[string]interface{}{"start_time": time.Now().Local().Format(util.Date_Full_Layout)})
- return fool
- })
- return fool
- }
- // 创建会话并保存信息
- func (b *MessaggeService) SaveAutoReplyMsg(userType, entId, entUserId, userId int64, content, appId, nowFormat string) (bool, int64) {
- var customer_service_id, userid, entid, message_id int64
- messageId := int64(0)
- ok1 := IC.BaseMysql.ExecTx("保存自动回复消息", func(tx *sql.Tx) bool {
- entUserName := ""
- if entUserId > 0 {
- list := IC.BaseMysql.SelectBySql(`select ? from socialize_tenant_seat where appid=? AND ent_id=? AND customer_service_id=?`, util.SOCIALIZE_CHAT_SESSION, appId, entId, entUserId)
- if list != nil && len(*list) > 0 {
- entUserName, _ = (*list)[0]["customer_service_name"].(string)
- }
- }
- messageId = IC.BaseMysql.InsertBySqlByTx(tx, `insert into socialize_message (appid,content,item,type,create_time,create_person) values (?,?,?,?,?,?)`, appId, content, 8, 1, nowFormat, "admin")
- sessionId := IC.BaseMysql.InsertBySqlByTx(tx, `insert into socialize_chat_session (appid,type,ent_id,customer_service_id,customer_service_name,user_id,start_time,end_time) values (?,?,?,?,?,?,?,?)`, appId, 1, entId, entUserId, entUserName, userId, nowFormat, nowFormat)
- ok := false
- if userType == 0 {
- ok1 := IC.BaseMysql.InsertBySqlByTx(tx, `insert into socialize_message_mailbox (appid,messag_id,type,send_user_id,send_user_type,receive_user_id,receive_user_type,own_id,own_type,create_time,isread,read_time) values (?,?,?,?,?,?,?,?,?,?,?,?)`, appId, messageId, 7, sessionId, 1, userId, 2, sessionId, 1, nowFormat, 1, nowFormat) > 0
- ok2 := IC.BaseMysql.InsertBySqlByTx(tx, `insert into socialize_message_mailbox (appid,messag_id,type,send_user_id,send_user_type,receive_user_id,receive_user_type,own_id,own_type,create_time) values (?,?,?,?,?,?,?,?,?,?)`, appId, messageId, 7, sessionId, 1, userId, 2, userId, 2, nowFormat) > 0
- ok = ok1 && ok2
- } else if userType == 1 {
- ok = IC.BaseMysql.InsertBySqlByTx(tx, `insert into socialize_message_mailbox (appid,messag_id,type,send_user_id,send_user_type,receive_user_id,receive_user_type,own_id,own_type,create_time,isread,read_time) values (?,?,?,?,?,?,?,?,?,?,?,?)`, appId, messageId, 7, sessionId, 1, userId, 2, sessionId, 1, nowFormat, 1, nowFormat) > 0
- } else if userType == 2 {
- ok = IC.BaseMysql.InsertBySqlByTx(tx, `insert into socialize_message_mailbox (appid,messag_id,type,send_user_id,send_user_type,receive_user_id,receive_user_type,own_id,own_type,create_time) values (?,?,?,?,?,?,?,?,?,?)`, appId, messageId, 7, sessionId, 1, userId, 2, userId, 2, nowFormat) > 0
- }
- message_id = messageId
- return messageId > 0 && sessionId > 0 && ok
- })
- if ok1 {
- customer_service_id = entUserId
- userid = userId
- entid = entId
- go UserSynchronousList(customer_service_id, userid, entid, message_id, nowFormat)
- }
- return ok1, messageId
- }
- // 修改未读状态
- func (b MessaggeService) UpdateReadById(in *messagecenter.ReadStateReq) bool {
- fool := IC.BaseMysql.ExecTx("已读状态修改", func(tx *sql.Tx) bool {
- updateMap := map[string]interface{}{
- "messag_id": in.MessageId,
- "isread": 0,
- }
- fool := IC.BaseMysql.Update(util.SOCIALIZE_MESSAGE_MAILBOX, updateMap, map[string]interface{}{"read_time": time.Now().Local().Format(util.Date_Full_Layout), "isread": 1})
- if fool {
- //查询此条信息拥有者
- data := IC.BaseMysql.FindOne(util.SOCIALIZE_MESSAGE_MAILBOX, updateMap, "receive_user_type", "")
- if data != nil {
- userType := int64(1)
- userId := int64(0)
- if (*data)["receive_user_type"] == 2 {
- userType = 2
- userId = in.EntUserId
- } else {
- userType = 1
- userId = in.NewUserId
- }
- pc_a, err := util.GetData(userType, userId)
- if fool {
- if err == nil && pc_a != nil {
- //id一致
- if in.MessageId == pc_a.Data["id"] {
- util.SetData(userType, userId, map[string]interface{}{"data": map[string]interface{}{}, "count": pc_a.Count - 1}, IC.SurvivalTime)
- } else {
- util.SetData(userType, userId, map[string]interface{}{"data": data, "count": pc_a.Count - 1}, IC.SurvivalTime)
- }
- }
- }
- }
- }
- return fool
- })
- return fool
- }
- // WithdrawMessage 撤回消息
- func (b MessaggeService) WithdrawMessage(in *messagecenter.ReadWithdrawReq) bool {
- messageId := encrypt.SE.Decode4Hex(in.MessageId)
- msg := IC.BaseMysql.FindOne(util.SOCIALIZE_MESSAGE, map[string]interface{}{"id": messageId}, "create_time", "")
- if msg == nil || len(*msg) <= 0 {
- log.Println("查询消息id失败")
- return false
- }
- createTime, _ := time.Parse(util.Date_Full_Layout, quitl.InterfaceToStr((*msg)["create_time"]))
- if createTime.Unix()+60*2 < time.Now().Unix() {
- log.Println("消息已超过2分钟,撤回失败")
- return false
- }
- nowForm := time.Now().Local()
- m := IC.BaseMysql.Update(util.SOCIALIZE_MESSAGE_MAILBOX,
- map[string]interface{}{"messag_id": messageId}, map[string]interface{}{"iswithdraw": 1, "withdraw_time": nowForm.Format(util.Date_Full_Layout)})
- if m {
- go SynchronousInfo(in.SenderId, in.RecipientId, in.ConversationType, quitl.Int64All(messageId), in.UserType, in.EntId, in.ChatGroupId)
- }
- return m
- }
- // 撤回消息同步信息
- func SynchronousInfo(sender, recipient, conversationType, messageId, userType, entId, chatGroupId int64) {
- switch conversationType {
- case 1: //1v1用户聊天
- if IC.BaseMysql.Count(util.SOCIALIZE_MESSAGE, map[string]interface{}{"id": messageId, "own_id": recipient, "isread": 0}) > 0 {
- IC.BaseMysql.SelectBySql(fmt.Sprintf("update %s set unread=CASE WHEN unread > 0 and my_position_id = %d and your_position_id = %d THEN unread-1 ELSE 0 END;", util.Socialize_summary, recipient, sender))
- }
- case 2: //用户与客服
- if IC.BaseMysql.Count(util.SOCIALIZE_MESSAGE, map[string]interface{}{"id": messageId, "own_id": recipient, "isread": 0}) > 0 {
- if userType == 2 { //发送人是用户
- //接收人是会话标识 查询客服id
- data := IC.BaseMysql.FindOne(util.SOCIALIZE_CHAT_SESSION, map[string]interface{}{"id": recipient}, "", "")
- if data != nil && len(*data) > 0 {
- IC.BaseMysql.SelectBySql(fmt.Sprintf("update %s set unread=CASE WHEN unread > 0 and user_id = %d and customer_service_id = %d and entId = %d THEN unread-1 ELSE 0 END;", util.Socialize_customer_service_user, sender, quitl.IntAll((*data)["customer_service_id"]), entId))
- }
- } else { //发送人是客服
- IC.BaseMysql.SelectBySql(fmt.Sprintf("update %s set unread=CASE WHEN unread > 0 and user_id = %d and ent_id = %d THEN unread-1 ELSE 0 END;", util.Socialize_summary, recipient, entId))
- }
- }
- case 3: //一对群
- data := IC.BaseMysql.Find(util.SOCIALIZE_MESSAGE, map[string]interface{}{"id": messageId, "chat_group_id": chatGroupId, "isread": 0}, "own_id", "", -1, -1)
- if data != nil && len(*data) > 0 {
- var ownIds []string
- for _, v := range *data {
- ownIds = append(ownIds, quitl.InterfaceToStr(v["own_id"]))
- }
- IC.BaseMysql.SelectBySql(fmt.Sprintf("update %s set unread=CASE WHEN unread > 0 and chat_group_id = %d and position_id in (%s) THEN unread-1 ELSE 0 END;", util.SOCIALIZE_CHAT_GROUP_PERSON, chatGroupId, strings.Join(ownIds, ",")))
- }
- }
- }
- // AppraiseMessage 消息评价
- func (b MessaggeService) AppraiseMessage(in *messagecenter.AppraiseReq) error {
- messageId := encrypt.SE.Decode4Hex(in.MessageId)
- //查询此条消息是否是当前用户的
- if IC.BaseMysql.Count(util.SOCIALIZE_MESSAGE_MAILBOX, map[string]interface{}{
- "messag_id": messageId,
- "receive_user_id": in.NewUserId,
- "receive_user_type": 2,
- "type": 8,
- }) == 0 {
- return fmt.Errorf("未查询到信息")
- }
- if IC.BaseMysql.Count(util.SOCIALIZE_APPRAISE, map[string]interface{}{
- "appid": in.Appid,
- "messag_id": messageId,
- }) > 0 {
- return fmt.Errorf("请勿重复评价")
- }
- //插入评价
- if IC.BaseMysql.Insert(util.SOCIALIZE_APPRAISE, map[string]interface{}{
- "appid": in.Appid,
- "messag_id": messageId,
- "create_time": time.Now().Local().Format(util.Date_Full_Layout),
- "appraise": in.Appraise,
- }) > 0 {
- return nil
- }
- return fmt.Errorf("评价消息异常")
- }
- // 聊天
- // 包含 1v1 ,群聊,群发
- /*
- 入参 appid,title,content,sendid,link,item,messagetype,receiverIds,groupIds
- */
- func (this *MessaggeService) Chat(in *messagecenter.MessageEntity) (fool bool, errorMsg string, content string, messageId, nowInt int64) {
- now := time.Now()
- nowTime := now.Format(date.Date_Full_Layout)
- messageId = int64(0)
- fool = IC.BaseMysql.ExecTx("消息存储", func(tx *sql.Tx) bool {
- isGroup := len(in.GroupIds) > 0
- isOneToOne := len(in.ReceiverIds) > 0
- createperson := strconv.Itoa(int(in.SendId))
- messageId = MessageAdd(tx, in.Appid, in.Title, in.Content, createperson, in.Link, in.Item, in.Type)
- //是否客服介入
- isCustomerServiceAccess := 0
- //除客服消息以外的系统消息
- if in.ItemType == 9 {
- in.ItemType = 6
- }
- //群聊
- if isGroup {
- //修改类型为群聊
- if in.ItemType != 6 {
- in.ItemType = 3
- }
- fieids := []string{"appid", "messag_id", "type", "send_user_id", "send_user_type", "receive_user_id", "receive_user_type", "own_type", "own_id", "create_time", "chat_group_id", "isread"}
- for _, v := range in.GroupIds {
- args := []interface{}{}
- args = append(args, in.Appid, messageId, in.ItemType, in.SendId, 2, in.SendId, 2, 2, in.SendId, nowTime, v, 1)
- groupUser := GetUserByGroupId(tx, v, in.SendId)
- for _, vv := range groupUser {
- log.Println("获取到群组下员工:", vv)
- args = append(args, in.Appid, messageId, in.ItemType, in.SendId, 2, vv, 2, 2, vv, nowTime, v, 0)
- }
- MessageMailBoxAdd(tx, fieids, args)
- //最后一次聊天
- SocializeSummaryAddOrUpdate(tx, v, 0, 0, messageId, isCustomerServiceAccess, nowTime)
- //更新未读消息
- GroupUserUnReadUpdate(tx, groupUser)
- }
- }
- //1v1
- if isOneToOne {
- //修改类型为个人
- if in.ItemType != 6 {
- in.ItemType = 2
- }
- fieids := []string{"appid", "messag_id", "type", "send_user_id", "send_user_type", "receive_user_id", "receive_user_type", "own_type", "own_id", "create_time", "isread"}
- args := []interface{}{}
- args = append(args, in.Appid, messageId, in.ItemType, in.SendId, 2, in.SendId, 2, 2, in.SendId, nowTime, 1)
- for _, v := range in.ReceiverIds {
- args = append(args, in.Appid, messageId, in.ItemType, in.SendId, 2, v, 2, 2, v, nowTime, 0)
- //最后一次聊天
- SocializeSummaryAddOrUpdate(tx, 0, in.SendId, v, messageId, isCustomerServiceAccess, nowTime)
- SocializeSummaryAddOrUpdate(tx, 0, v, in.SendId, messageId, isCustomerServiceAccess, nowTime)
- }
- MessageMailBoxAdd(tx, fieids, args)
- }
- return true
- })
- return fool, "", in.Content, messageId, now.Unix()
- }
- // 消息存储
- func MessageAdd(tx *sql.Tx, appid, title, content, createperson, link string, item, messageType int64) int64 {
- nowTime := time.Now()
- message := map[string]interface{}{
- "appid": appid,
- "title": title,
- "content": content,
- "item": item,
- "type": messageType,
- "link": link,
- "create_time": nowTime.Format(date.Date_Full_Layout),
- "create_person": createperson, //系统消息时,创建人是群聊id或接收人id
- }
- return IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_MESSAGE, message)
- }
- // 消息信息箱存储
- // types 2:点对点 3:群消息
- func MessageMailBoxAdd(tx *sql.Tx, fieids []string, args []interface{}) (int64, int64) {
- length, lastId := IC.BaseMysql.InsertBatchByTx(tx, util.SOCIALIZE_MESSAGE_MAILBOX, fieids, args)
- log.Println("MessageMailBoxAdd length:", length, "MessageMailBoxAdd lastId:", lastId)
- return length, lastId
- }
- // 获取除发送人以外的群成员
- func GetUserByGroupId(tx *sql.Tx, groupId, sendId int64) []int64 {
- arr := []int64{}
- data := IC.BaseMysql.SelectBySqlByTx(tx, "select position_id from "+util.SOCIALIZE_CHAT_GROUP_PERSON+" where status = 1 and chat_group_id = ? AND position_id != ? ", groupId, sendId)
- if data == nil || len(*data) <= 0 {
- return arr
- }
- for _, v := range *data {
- position_id := quitl.Int64All(v["position_id"])
- if position_id == 0 {
- continue
- }
- arr = append(arr, position_id)
- }
- return arr
- }
- // 最后一次聊天存储
- func SocializeSummaryAddOrUpdate(tx *sql.Tx, groupId, myPositionId, yourPositionId, messageId int64, isCustomerServiceAccess int, timestamp string) bool {
- //判断是否存在
- if groupId > 0 {
- if IC.BaseMysql.CountBySql(fmt.Sprintf(`select count(1) from %s where chat_group_id =?`, util.SOCIALIZE_SUMMARY), groupId) > 0 {
- //存在更新
- return IC.BaseMysql.UpdateByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
- "chat_group_id": groupId,
- }, map[string]interface{}{
- "message_id": messageId,
- "timestamp": timestamp,
- })
- } else {
- //新增
- return IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
- "chat_group_id": groupId,
- "message_id": messageId,
- "timestamp": timestamp,
- }) > 0
- }
- }
- if yourPositionId > 0 {
- ok_my := true
- ok_your := true
- //发送方
- if IC.BaseMysql.CountBySql(fmt.Sprintf(`select count(1) from %s where my_position_id =? and your_position_id =?`, util.SOCIALIZE_SUMMARY), myPositionId, yourPositionId) > 0 {
- //存在更新
- ok_my = IC.BaseMysql.UpdateByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
- "my_position_id": myPositionId,
- "your_position_id": yourPositionId,
- }, map[string]interface{}{
- "message_id": messageId,
- "timestamp": timestamp,
- })
- } else {
- //新增
- ok_my = IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
- "my_position_id": myPositionId,
- "your_position_id": yourPositionId,
- "message_id": messageId,
- "timestamp": timestamp,
- "unread": 0,
- "customer_service_access": isCustomerServiceAccess,
- }) > 0
- }
- //接收方
- if IC.BaseMysql.CountBySql(fmt.Sprintf(`select count(1) from %s where my_position_id =? and your_position_id =?`, util.SOCIALIZE_SUMMARY), yourPositionId, myPositionId) > 0 {
- //存在更新
- ok_your = IC.BaseMysql.UpdateByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
- "my_position_id": yourPositionId,
- "your_position_id": myPositionId,
- }, map[string]interface{}{
- "message_id": messageId,
- "timestamp": timestamp,
- "unread": 1,
- })
- } else {
- //新增
- ok_your = IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
- "my_position_id": yourPositionId,
- "your_position_id": myPositionId,
- "message_id": messageId,
- "timestamp": timestamp,
- "unread": 1,
- "customer_service_access": isCustomerServiceAccess,
- }) > 0
- }
- return ok_my && ok_your
- }
- return true
- }
- // 群组人员未读消息更新
- func GroupUserUnReadUpdate(tx *sql.Tx, ids []int64) bool {
- whs := []string{}
- for i := 0; i < len(ids); i++ {
- whs = append(whs, "?")
- }
- wh := strings.Join(whs, ",")
- interfaces := gconv.Interfaces(ids)
- count := IC.BaseMysql.UpdateOrDeleteBySql(`UPDATE `+util.SOCIALIZE_CHAT_GROUP_PERSON+` SET unread = unread + 1 WHERE id in (`+wh+`)`, interfaces...)
- if count > 0 {
- return true
- }
- return true
- }
- // GetUserAllPosition 用户下所有职位id
- func GetUserAllPosition(baseUserId int64) (positionStr string) {
- //查询用户所有的职位id
- sqlPosition := fmt.Sprintf("SELECT id FROM %s WHERE user_id = %d", util.BASE_POSITION, baseUserId)
- positionArr := IC.BaseMysql.SelectBySql(sqlPosition)
- if positionArr != nil && len(*positionArr) > 0 {
- for k, val := range *positionArr {
- if k < len(*positionArr)-1 {
- positionStr += strconv.Itoa(quitl.IntAll(val["id"])) + ","
- } else {
- positionStr += strconv.Itoa(quitl.IntAll(val["id"]))
- }
- }
- }
- return positionStr
- }
|