12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415 |
- 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)
- InsertLock = new(sync.Mutex)
- )
- // Count 未读消息查询
- func (b MessaggeService) Count(newUserId, positionId int64) (last map[string]interface{}, count int) {
- //导航右上角未读消息总量 1v1聊天+群组消息+客服消息
- querySql := fmt.Sprintf("SELECT b.*,(SELECT SUM( a.unread) FROM %s a "+
- "LEFT JOIN %s b ON a.message_id = b.id "+
- "WHERE a.unread > 0 "+
- "AND ( a.my_position_id = %d OR a.user_id = %d )) AS unread "+
- "FROM %s a "+
- "LEFT JOIN %s b ON a.message_id = b.id "+
- "WHERE a.unread > 0 "+
- "AND ( a.my_position_id = %d OR a.user_id = %d ) "+
- "ORDER BY a.TIMESTAMP DESC LIMIT 0,1", util.SOCIALIZE_SUMMARY, util.SOCIALIZE_MESSAGE, positionId, newUserId,
- util.SOCIALIZE_SUMMARY, util.SOCIALIZE_MESSAGE, positionId, newUserId)
- log.Println("查询sql", querySql)
- data := IC.BaseMysql.SelectBySql(querySql)
- if data != nil && len(*data) > 0 {
- return (*data)[0], quitl.IntAll((*data)[0]["unread"])
- } else {
- return nil, 0
- }
- }
- // 用户列表查询
- 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
- DISTINCT(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,
- a.timestamp,
- "" as phone,
- b.groupMember
- FROM
- socialize_summary a
- INNER JOIN %s b ON ( a.my_position_id = %d AND a.chat_group_id = b.id)
- LEFT JOIN socialize_message d ON ( a.message_id = d.id )
- ORDER BY a.timestamp DESC LIMIT 0,500
- ) `, GroupNameSql, in.PositionId)
- if oneSql != "" {
- sqlArr = append(sqlArr, oneSql)
- }
- if groupSql != "" {
- sqlArr = append(sqlArr, groupSql)
- }
- switch in.QueryType {
- case 1: //分享列表
- if len(sqlArr) > 1 {
- allSql = strings.Join(sqlArr, " UNION ALL ")
- } else {
- allSql = sqlArr[0]
- }
- default:
- //历史会话列表
- if serviceSql != "" {
- sqlArr = append(sqlArr, serviceSql)
- }
- allSql = strings.Join(sqlArr, " UNION ALL ")
- }
- var startNum int64 = 1
- var pageSize int64 = 500
- if in.Size > 0 && in.Size < 500 {
- if in.Page == 0 {
- in.Page = 1
- }
- if in.Page*in.Size < 500 {
- startNum = in.Page
- pageSize = in.Size
- }
- }
- sqlStr = fmt.Sprintf(`SELECT * FROM(
- %s
- ) a ORDER BY a.timestamp DESC LIMIT %d,%d`, allSql, (startNum-1)*pageSize, pageSize)
- } else {
- var timeSql, phoneSql, filtrationSql, isTouristSql string
- if in.StartTime != "" {
- timeSql += fmt.Sprintf(" AND a.timestamp >= '%s 00:00:00'", in.StartTime)
- }
- if in.EndTime != "" {
- timeSql += fmt.Sprintf(" AND a.timestamp <= '%s 23:59:59'", in.EndTime)
- }
- if in.Phone != "" {
- phoneSql = " AND b.phone like '%" + in.Phone + "%'"
- }
- if in.IsTourist == 1 || in.IsTourist == 2 {
- isTouristSql = " AND b.is_tourist = " + fmt.Sprintf("%d", in.IsTourist)
- }
- 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,
- b.phone,
- 0 as userType,
- b.is_tourist
- 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 %s)`, in.EntId, timeSql, phoneSql, filtrationSql, isTouristSql)
- serviceSql := fmt.Sprintf(`(SELECT
- a.user_id,
- c.message_id,
- c.timestamp,
- b.nickname,
- a.unread,
- b.headimg,
- b.phone,
- 0 as userType,
- b.is_tourist
- 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 %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, isTouristSql,
- 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,
- a.is_tourist
- FROM
- (%s) a
- LEFT JOIN socialize_message c ON ( a.message_id = c.id )
- ORDER BY
- a.timestamp DESC limit %v ,%v`, restrictionSql, (in.Page-1)*in.Size, in.Size)
- count = IC.BaseMysql.CountBySql(fmt.Sprintf(`SELECT count(1)
- FROM
- (%s) a`, restrictionSql))
- }
- if sqlStr != "" {
- log.Println("查询列表sql:", sqlStr)
- data = IC.BaseMysql.SelectBySql(sqlStr)
- if data != nil && len(*data) > 0 {
- 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 data, count, err
- case 2: //用户查询结果
- count = quitl.Int64All(len(*data))
- phoneMap, _, positionMap := EntPerson(in.EntId, true) //获取企业架构人员名称
- log.Println("查询列表耗时3:", time.Since(tm))
- 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,
- b.phone,
- b.is_tourist
- 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,
- b.phone,
- b.is_tourist
- 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)
- restrictionSql := aiSql + " UNION ALL " + serviceSql
- 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.is_tourist
- FROM
- (%s) a
- LEFT JOIN socialize_message c ON ( a.message_id = c.id )
- ORDER BY
- a.timestamp DESC`, restrictionSql)
- }
- if sqlStr != "" {
- log.Println("ConversationList查询列表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)
- 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
- userType := int64(1)
- //客服相关信息保存
- fool = IC.BaseMysql.ExecTx("聊天信息保存", func(tx *sql.Tx) bool {
- //先插入信息表
- 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
- if in.ItemType == 4 {
- messageMailBox["isread"] = 1
- }
- } 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,
- "type": in.ItemType,
- "create_time": nowForm.Format(util.Date_Full_Layout),
- "messag_id": ok,
- "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)
- return ok > 1 && receiveOk > 1
- })
- if fool {
- //go
- UserSynchronousList(customer_service_id, userid, entid, message_id, create_time, quitl.Int64All(quitl.If(userType == 1, 2, 1)), in.ItemType)
- }
- return fool, "", in.Content, messageId, nowForm.Unix()
- }
- // 客服 用户聊天消息列表同步
- // sendUserType 发送人类型 1客服 2用户
- func UserSynchronousList(customerServiceId, userId, entId, messageId int64, createTime string, sendUserType, itemType int64) {
- InsertLock.Lock()
- defer InsertLock.Unlock()
- log.Printf("同步最后消息参数customerServiceId:%d,userId:%d,entId%d,messageId:%d", customerServiceId, userId, entId, messageId)
- //nowForm := time.Now().Local()
- //create_time := nowForm.Format(util.Date_Full_Layout)
- //查看汇总表
- IC.BaseMysql.ExecTx("更新汇总表", func(tx *sql.Tx) bool {
- data := IC.BaseMysql.SelectBySqlByTx(tx, "select customer_service_access from socialize_summary where ent_id=? and user_id=? ", entId, userId)
- //data := FindOne(util.SOCIALIZE_SUMMARY, map[string]interface{}{"user_id": userId, "ent_id": entId}, "customer_service_access", "")
- customer_service_access := 0
- if data != nil && len(*data) > 0 {
- if quitl.IntAll((*data)[0]["customer_service_access"]) == 0 && customerServiceId > 0 {
- customer_service_access = 1
- } else {
- customer_service_access = quitl.IntAll((*data)[0]["customer_service_access"])
- }
- log.Println(customer_service_access, "customer_service_access打印", (*data)[0]["customer_service_access"], customerServiceId, quitl.IntAll((*data)[0]["customer_service_access"]) == 0 && customerServiceId > 0)
- //更新汇总表
- ok := int64(0)
- if sendUserType == 1 {
- if itemType == 4 {
- //机器人消息保存处理
- ok = IC.BaseMysql.UpdateOrDeleteBySqlByTx(tx, fmt.Sprintf("UPDATE socialize_summary SET message_id = %d ,timestamp = '%s' WHERE user_id = %d and ent_id= %d", messageId, createTime, userId, entId))
- } else {
- ok = IC.BaseMysql.UpdateOrDeleteBySqlByTx(tx, fmt.Sprintf("UPDATE socialize_summary SET message_id = %d ,timestamp = '%s', unread = unread+1, customer_service_access = %d WHERE user_id = %d and ent_id= %d", messageId, createTime, customer_service_access, userId, entId))
- }
- } else {
- ok = IC.BaseMysql.UpdateOrDeleteBySqlByTx(tx, fmt.Sprintf("UPDATE socialize_summary SET message_id = %d ,timestamp = '%s', customer_service_access = %d WHERE user_id = %d and ent_id= %d", messageId, createTime, customer_service_access, userId, entId))
- }
- if ok > 0 {
- if customerServiceId > 0 {
- //判断客服用户表是否存在
- if IC.BaseMysql.Count(util.Socialize_customer_service_user, map[string]interface{}{"user_id": userId, "ent_id": entId, "customer_service_id": customerServiceId}) > 0 {
- if sendUserType == 2 {
- IC.BaseMysql.UpdateOrDeleteBySqlByTx(tx, fmt.Sprintf("UPDATE socialize_customer_service_user SET unread = unread+1 WHERE user_id = %d and customer_service_id= %d", userId, customerServiceId))
- }
- } else {
- IC.BaseMysql.Insert(util.SOCIALIZE_CUSTOMER_SERVICE_USER, map[string]interface{}{
- "user_id": userId,
- "ent_id": entId,
- "customer_service_id": customerServiceId,
- "unread": quitl.If(sendUserType == 1, 0, 1),
- })
- }
- }
- }
- } else {
- //新增汇总表
- ok := IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
- "user_id": userId,
- "ent_id": entId,
- "customer_service_access": quitl.If(customerServiceId > 0, 1, 0),
- "timestamp": createTime,
- "unread": quitl.If(sendUserType == 1, 0, 1),
- "message_id": messageId,
- })
- log.Println(ok, "---", userId, "---", messageId, "---", entId, "------add summary log:")
- //新增客服用户表
- if ok > 0 {
- if customerServiceId > 0 {
- if id := IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_CUSTOMER_SERVICE_USER, map[string]interface{}{
- "user_id": userId,
- "ent_id": entId,
- "customer_service_id": customerServiceId,
- "unread": quitl.If(sendUserType == 1, 0, 1),
- }); id <= 0 {
- return false
- }
- }
- } else {
- return false
- }
- }
- return true
- })
- }
- // 历史信息查询
- 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,a.send_user_type,a.type AS itemType,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 "+
- "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 IN ( 2, 6 ) %s "+
- "AND a.chat_group_id IS null "+
- "AND a.send_user_type = a.receive_user_type "+
- "ORDER BY a.id desc "+
- "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.*,a.send_user_type,a.type AS itemType,"+
- "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.iswithdraw = 0 AND a.own_id = %d "+
- "AND a.chat_group_id = %d AND a.type IN ( 3, 6 ) %s "+
- "ORDER BY a.id DESC "+
- "LIMIT 0, %d",
- util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_MESSAGE, in.PositionId,
- in.ChatGroupId, lastStr, 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 = %d %s "+
- "AND a.send_user_type != a.receive_user_type "+
- "ORDER BY a.id desc "+
- "limit 0 , %d ",
- util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_MESSAGE, util.SOCIALIZE_CHAT_SESSION,
- in.EntId, in.SendId, 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.ent_id = %d AND c.user_id = %d "+
- "LEFT JOIN %s d on c.ent_id=d.ent_id "+
- "LEFT JOIN %s e on e.messag_id=b.id "+
- "WHERE a.own_type = 2 and a.iswithdraw = 0 "+
- "AND a.own_id = %d "+
- "AND c.ent_id = %d "+
- "AND c.user_id = %d "+
- "AND a.send_user_type != a.receive_user_type "+
- "AND ( a.type = 4 OR a.type = 5 or a.type=6 or a.type=7 or a.type=8) %s "+
- "ORDER BY a.id desc "+
- "limit 0 , %d ",
- util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_MESSAGE, util.SOCIALIZE_CHAT_SESSION, in.SendId, in.NewUserId, util.SOCIALIZE_TENANT_ROBOT, util.SOCIALIZE_APPRAISE,
- in.NewUserId, in.SendId, in.NewUserId, 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 || in.MsgType == 2) && data != nil && len(*data) > 0 {
- _, _, positionData := EntPerson(in.EntId, true)
- for _, v := range *data {
- positionId := quitl.IntAll(v["send_position_id"])
- if positionId != 0 {
- v["userName"] = positionData[positionId]
- //log.Println(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.PositionId,
- "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.PositionId,
- "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.PositionId,
- "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 AND customer_service_id = %d", util.Socialize_customer_service_user, in.SendId, in.EntUserId)
- } 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 AND ent_id = %d", util.SOCIALIZE_SUMMARY, in.NewUserId, in.SendId)
- }
- 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
- userType = 1
- } 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
- userType = 2
- } 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
- userType = 1
- }
- 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, userType, 6)
- }
- return ok1, messageId
- }
- // 修改未读状态
- func (b MessaggeService) UpdateReadById(in *messagecenter.ReadStateReq) {
- updateMap := map[string]interface{}{}
- sqlStr := ""
- log.Println("UpdateReadById", in.PositionId, in.NewUserId, in.SendId, in.EntUserId, in.UserType)
- switch in.UserType {
- case 2: //点对点聊天
- updateMap = map[string]interface{}{
- "own_type": 2,
- "own_id": in.PositionId,
- "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.PositionId,
- "your_position_id": in.SendId,
- }
- IC.BaseMysql.Update(util.SOCIALIZE_SUMMARY, updateQuery, map[string]interface{}{"unread": 0})
- 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.PositionId, in.SendId)
- IC.BaseMysql.UpdateOrDeleteBySql(sqlStr)
- //更新socialize_summary表未读消息数量
- updateQuery := map[string]interface{}{
- "my_position_id": in.PositionId,
- "chat_group_id": in.SendId,
- }
- IC.BaseMysql.Update(util.SOCIALIZE_SUMMARY, updateQuery, map[string]interface{}{"unread": 0})
- case 1: // 客服聊天
- unreadSql := ""
- positionStr := GetUserAllPosition(in.NewUserId)
- if in.SendType == 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 AND customer_service_id = %d", util.Socialize_customer_service_user, in.SendId, in.EntUserId)
- } 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 AND ent_id = %d", util.SOCIALIZE_SUMMARY, in.NewUserId, in.SendId)
- }
- IC.BaseMysql.UpdateOrDeleteBySql(sqlStr)
- IC.BaseMysql.UpdateOrDeleteBySql(unreadSql)
- }
- //if true {
- //未读信息修改
- //redis缓存处理
- //b.Count(in.NewUserId, in.UserType, in.EntUserId, true)
- }
- // 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_MAILBOX, map[string]interface{}{"messag_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_MAILBOX, map[string]interface{}{"messag_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_MAILBOX, map[string]interface{}{"messag_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 my_position_id in (%s) THEN unread-1 ELSE 0 END;", util.Socialize_summary, 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 ,群聊,群发
- /*
- 类型;1:站内信消息 2:点对点消息 3:群消息 4:机器人消息 5:客服消息 6系统信息 7:客服自动回复 8:评价 9:其它系统消息 (除客服以外的) 10:撤回(自己看到的) 11:撤回(其他人看到的)
- 群撤回自己看到的和用户看到的不一样
- */
- 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
- isWithdrawByMyself := in.ItemType == 10
- isWithdrawByOthers := in.ItemType == 11
- 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 == 10 || in.ItemType == 11 {
- 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{}{}
- groupUser := GetUserByGroupId(tx, v, in.SendId)
- //发送人自己
- if !isWithdrawByOthers {
- args = append(args, in.Appid, messageId, in.ItemType, in.SendId, 2, in.SendId, 2, 2, in.SendId, nowTime, v, 1)
- //最后一次聊天
- SocializeSummaryAddOrUpdate(tx, v, in.SendId, 0, messageId, isCustomerServiceAccess, nowTime, false, in.ItemType)
- }
- for _, vv := range groupUser {
- if !isWithdrawByMyself {
- log.Println("获取到群组下员工:", vv)
- //接收人其他用户
- args = append(args, in.Appid, messageId, in.ItemType, in.SendId, 2, vv, 2, 2, vv, nowTime, v, 0)
- //最后一次聊天
- SocializeSummaryAddOrUpdate(tx, v, 0, vv, messageId, isCustomerServiceAccess, nowTime, false, in.ItemType)
- }
- }
- MessageMailBoxAdd(tx, fieids, args)
- }
- }
- //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{}{}
- for _, v := range in.ReceiverIds {
- if !isWithdrawByOthers {
- args = append(args, in.Appid, messageId, in.ItemType, in.SendId, 2, v, 2, 2, in.SendId, nowTime, 1)
- //最后一次聊天
- SocializeSummaryAddOrUpdate(tx, 0, in.SendId, v, messageId, isCustomerServiceAccess, nowTime, true, in.ItemType)
- }
- if !isWithdrawByMyself {
- args = append(args, in.Appid, messageId, in.ItemType, in.SendId, 2, v, 2, 2, v, nowTime, 0)
- //最后一次聊天
- SocializeSummaryAddOrUpdate(tx, 0, v, in.SendId, messageId, isCustomerServiceAccess, nowTime, false, in.ItemType)
- }
- }
- 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
- }
- // 最后一次聊天存储
- // 1v1是双方的
- // 群聊是发送人和其他人的
- // send :true发送人 false接收人 用于取分1对1 身份
- func SocializeSummaryAddOrUpdate(tx *sql.Tx, groupId, myPositionId, yourPositionId, messageId int64, isCustomerServiceAccess int, timestamp string, send bool, itemType int64) bool {
- //判断是否存在
- if groupId > 0 {
- isSend := myPositionId != 0
- if isSend {
- if IC.BaseMysql.CountBySql(fmt.Sprintf(`select count(1) from %s where chat_group_id =? and my_position_id =?`, util.SOCIALIZE_SUMMARY), groupId, myPositionId) > 0 {
- //存在更新
- return IC.BaseMysql.UpdateByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
- "chat_group_id": groupId,
- "my_position_id": myPositionId,
- }, map[string]interface{}{
- "message_id": messageId,
- "timestamp": timestamp,
- })
- } else {
- //新增
- return IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
- "chat_group_id": groupId,
- "my_position_id": myPositionId,
- "message_id": messageId,
- "timestamp": timestamp,
- "unread": 0,
- }) > 0
- }
- } else {
- if r := IC.BaseMysql.SelectBySql(fmt.Sprintf(`select unread from %s where chat_group_id =? and my_position_id =?`, util.SOCIALIZE_SUMMARY), groupId, yourPositionId); r != nil && len(*r) > 0 {
- updateMap := map[string]interface{}{
- "message_id": messageId,
- "timestamp": timestamp,
- }
- if itemType != 6 {
- updateMap["unread"] = gconv.Int((*r)[0]["unread"]) + 1
- }
- //存在更新
- return IC.BaseMysql.UpdateByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
- "chat_group_id": groupId,
- "my_position_id": yourPositionId,
- }, updateMap)
- } else {
- //新增
- saveMap := map[string]interface{}{
- "chat_group_id": groupId,
- "my_position_id": yourPositionId,
- "message_id": messageId,
- "timestamp": timestamp,
- }
- if itemType != 6 {
- saveMap["unread"] = 1
- }
- return IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_SUMMARY, saveMap) > 0
- }
- }
- } else {
- if yourPositionId > 0 {
- ok_my := true
- ok_your := true
- //发送方
- if r := IC.BaseMysql.SelectBySql(fmt.Sprintf(`select id,unread from %s where my_position_id =? and your_position_id =? limit 1`, util.SOCIALIZE_SUMMARY), myPositionId, yourPositionId); r != nil && len(*r) > 0 { //存在更新
- updateMap := map[string]interface{}{
- "message_id": messageId,
- "timestamp": timestamp,
- }
- if !send && itemType != 6 {
- updateMap["unread"] = gconv.Int((*r)[0]["unread"]) + 1
- }
- ok_my = IC.BaseMysql.UpdateByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
- "my_position_id": myPositionId,
- "your_position_id": yourPositionId,
- }, updateMap)
- } else {
- //新增
- saveMap := map[string]interface{}{
- "my_position_id": myPositionId,
- "your_position_id": yourPositionId,
- "message_id": messageId,
- "timestamp": timestamp,
- "unread": 0,
- "customer_service_access": isCustomerServiceAccess,
- }
- if !send && itemType != 6 {
- saveMap["unread"] = 1
- }
- ok_my = IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_SUMMARY, saveMap) > 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
- }
- // 1v1首次建立会话 创建汇总表
- func OneCreatingSession(in *messagecenter.OneUserConversationReq) string {
- if in.MyPositionId < 0 || in.YouPositionId < 0 {
- return "参数异常"
- }
- if IC.BaseMysql.Count(util.SOCIALIZE_SUMMARY, map[string]interface{}{"my_position_id": in.MyPositionId, "your_position_id": in.YouPositionId}) > 0 {
- return ""
- }
- if IC.BaseMysql.Insert(util.SOCIALIZE_SUMMARY, map[string]interface{}{
- "my_position_id": in.MyPositionId,
- "your_position_id": in.YouPositionId,
- "message_id": 0,
- "timestamp": time.Now().Format(date.Date_Full_Layout),
- "unread": 0,
- "customer_service_access": 0,
- }) > 0 {
- return ""
- }
- return "创建汇总表数据失败"
- }
- func GetSenderName(in *messagecenter.GetSenderNameReq) string {
- var name string
- switch in.SType {
- case 1: //客服
- data1 := IC.BaseMysql.FindOne("socialize_chat_session", map[string]interface{}{"id": in.Id}, "customer_service_id", "")
- if data1 != nil && len(*data1) > 0 {
- data := IC.BaseMysql.FindOne("socialize_tenant_seat", map[string]interface{}{"customer_service_id": quitl.IntAll((*data1)["customer_service_id"])}, "customer_service_name", "")
- if data != nil && len(*data) > 0 {
- name = fmt.Sprintf("%s(客服)", quitl.InterfaceToStr((*data)["customer_service_name"]))
- }
- }
- case 2: //用户
- position := IC.BaseMysql.SelectBySql(fmt.Sprintf(`SELECT a.ent_id,b.phone FROM base_position a INNER JOIN base_user b on a.id =%d AND a.user_id = b.id `, in.Id))
- if position != nil && len(*position) > 0 {
- phone := (*position)[0]["phone"]
- entId := (*position)[0]["ent_id"]
- nameMap := IC.MainMysql.SelectBySql(fmt.Sprintf(`SELECT a.phone,IF(a.name = "我" AND b.role_id = 1 ,"%s",a.name) AS name,b.role_id FROM %s a
- LEFT JOIN entniche_user_role b on a.id = b.user_id where a.phone = %s and a.ent_id = %d `, util.UserRoleOne, util.ENTNICHE_USER, phone, entId))
- if nameMap != nil && len(*nameMap) > 0 {
- name = fmt.Sprintf("%s(用户)", (*nameMap)[0]["name"])
- }
- }
- case 3: //群
- data := IC.BaseMysql.FindOne(util.SOCIALIZE_CHAT_GROUP, map[string]interface{}{"id": in.Id}, "name", "")
- if data != nil {
- name = fmt.Sprintf("%s(群)", quitl.InterfaceToStr((*data)["name"]))
- }
- }
- return name
- }
|