message_mail_box.go 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252
  1. package service
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "log"
  6. "strconv"
  7. "strings"
  8. "sync"
  9. "time"
  10. quitl "app.yhyue.com/moapp/jybase/common"
  11. "app.yhyue.com/moapp/jybase/date"
  12. "app.yhyue.com/moapp/jybase/encrypt"
  13. util "bp.jydev.jianyu360.cn/SocialPlatform/messageCenter/entity"
  14. IC "bp.jydev.jianyu360.cn/SocialPlatform/messageCenter/rpc/messagecenter/init"
  15. "bp.jydev.jianyu360.cn/SocialPlatform/messageCenter/rpc/messagecenter/messagecenter"
  16. "github.com/gogf/gf/v2/util/gconv"
  17. )
  18. type MessaggeService struct{}
  19. var rwLock = new(sync.RWMutex)
  20. // Count 未读消息查询
  21. func (b MessaggeService) Count(newUserId, positionId int64) (last map[string]interface{}, count int) {
  22. //导航右上角未读消息总量 1v1聊天+群组消息+客服消息
  23. querySql := fmt.Sprintf("SELECT b.*,(SELECT SUM( a.unread) FROM %s a "+
  24. "LEFT JOIN %s b ON a.message_id = b.id "+
  25. "WHERE a.unread > 0 "+
  26. "AND ( a.my_position_id = %d OR a.user_id = %d )) AS unread "+
  27. "FROM %s a "+
  28. "LEFT JOIN %s b ON a.message_id = b.id "+
  29. "WHERE a.unread > 0 "+
  30. "AND ( a.my_position_id = %d OR a.user_id = %d ) "+
  31. "ORDER BY a.TIMESTAMP DESC LIMIT 0,1", util.SOCIALIZE_SUMMARY, util.SOCIALIZE_MESSAGE, positionId, newUserId,
  32. util.SOCIALIZE_SUMMARY, util.SOCIALIZE_MESSAGE, positionId, newUserId)
  33. log.Println("查询sql", querySql)
  34. data := IC.BaseMysql.SelectBySql(querySql)
  35. if data != nil && len(*data) > 0 {
  36. return (*data)[0], quitl.IntAll((*data)[0]["unread"])
  37. } else {
  38. return nil, 0
  39. }
  40. }
  41. // 用户列表查询
  42. func (b MessaggeService) UserList(in *messagecenter.UserReq) (data *[]map[string]interface{}, count int64, err error) {
  43. sqlStr := ""
  44. tm := time.Now()
  45. if in.UserType == 2 {
  46. var (
  47. allSql, positionIdArr, oneSql, oneNameSql, serviceNameSql string
  48. sqlArr []string
  49. )
  50. GroupNameSql := `(SELECT *,"" as groupMember FROM socialize_chat_group where isdismiss = 0)` //无搜索群
  51. if in.NameSearch != "" {
  52. serviceNameSql = " AND b.nickname like '%" + in.NameSearch + "%'"
  53. GroupNameSql = `(SELECT id,name,"" as groupMember FROM socialize_chat_group WHERE isdismiss = 0 AND name like '%` + in.NameSearch + `%')` //默认搜素群名称
  54. positionIdArr = NameToPositionIdp(in.NameSearch, in.EntId)
  55. if positionIdArr != "" {
  56. oneNameSql = " AND find_in_set(b.id,'" + positionIdArr + "')" //1v1搜索成员id
  57. //存在满足成员名时 重新定义搜索sql 并兼容群名称不满足但成员名满足时也展示 并展示部分满足群员名
  58. nameSearch := " or b.name like '%" + in.NameSearch + "%')"
  59. name := fmt.Sprintf(" AND (c.position_id IN ( %s ) %s", positionIdArr, nameSearch)
  60. GroupNameSql = fmt.Sprintf(` (
  61. SELECT
  62. a.chat_group_id as id,
  63. GROUP_CONCAT( distinct c.position_id ) as groupMember,
  64. GROUP_CONCAT( distinct b.name ) as name
  65. FROM
  66. socialize_chat_group_person a
  67. INNER JOIN socialize_chat_group b ON a.position_id=%d AND a.chat_group_id = b.id AND b.isdismiss = 0
  68. INNER JOIN socialize_chat_group_person c ON a.chat_group_id = c.chat_group_id %s
  69. GROUP BY
  70. a.chat_group_id)`, in.PositionId, name) //群搜索
  71. }
  72. }
  73. log.Println("用户列表展示", in.NameSearch, in.EntId, oneNameSql)
  74. //1v1 无搜索时 或搜索有结果时
  75. if in.NameSearch == "" || oneNameSql != "" {
  76. oneSql = fmt.Sprintf(`(SELECT
  77. a.your_position_id AS id,
  78. 2 AS userType,
  79. c.nickname AS name,
  80. c.headimg,
  81. d.content,
  82. d.type,
  83. d.create_time,
  84. a.unread as number,
  85. a.timestamp,
  86. c.phone,
  87. "" as groupMember
  88. FROM
  89. socialize_summary a
  90. INNER JOIN base_position b ON ( a.my_position_id = %d %s AND a.your_position_id = b.id)
  91. INNER JOIN base_user c ON ( b.user_id = c.id )
  92. LEFT JOIN socialize_message d ON ( a.message_id = d.id )
  93. ORDER BY a.timestamp DESC LIMIT 0,500
  94. )`, in.PositionId, oneNameSql)
  95. }
  96. //客服列表
  97. serviceSql := fmt.Sprintf(` (
  98. SELECT
  99. a.ent_id AS id,
  100. 1 AS userType,
  101. b.nickname AS name,
  102. b.headimage as headimg,
  103. c.content,
  104. c.type,
  105. c.create_time,
  106. a.unread as number,
  107. a.timestamp,
  108. "" as phone,
  109. "" as groupMember
  110. FROM
  111. socialize_summary a
  112. INNER JOIN socialize_tenant_robot b ON ( a.user_id = %d AND a.ent_id = b.ent_id %s )
  113. LEFT JOIN socialize_message c ON ( a.message_id = c.id )
  114. ORDER BY a.timestamp DESC LIMIT 0,500
  115. ) `, in.NewUserId, serviceNameSql)
  116. //群列表
  117. groupSql := fmt.Sprintf(` (
  118. SELECT
  119. b.id,
  120. 3 AS userType,
  121. b.name,
  122. '' AS headimg,
  123. d.content,
  124. d.type,
  125. d.create_time,
  126. a.unread as number,
  127. a.timestamp,
  128. "" as phone,
  129. b.groupMember
  130. FROM
  131. socialize_summary a
  132. INNER JOIN %s b ON ( a.my_position_id = %d AND a.chat_group_id = b.id)
  133. LEFT JOIN socialize_message d ON ( a.message_id = d.id )
  134. ORDER BY a.timestamp DESC LIMIT 0,500
  135. ) `, GroupNameSql, in.PositionId)
  136. if oneSql != "" {
  137. sqlArr = append(sqlArr, oneSql)
  138. }
  139. if groupSql != "" {
  140. sqlArr = append(sqlArr, groupSql)
  141. }
  142. switch in.QueryType {
  143. case 1: //分享列表
  144. if len(sqlArr) > 1 {
  145. allSql = strings.Join(sqlArr, " UNION ALL ")
  146. } else {
  147. allSql = sqlArr[0]
  148. }
  149. default:
  150. //历史会话列表
  151. if serviceSql != "" {
  152. sqlArr = append(sqlArr, serviceSql)
  153. }
  154. allSql = strings.Join(sqlArr, " UNION ALL ")
  155. }
  156. sqlStr = fmt.Sprintf(`SELECT * FROM(
  157. %s
  158. ) a ORDER BY a.timestamp DESC LIMIT 0,500`, allSql)
  159. } else {
  160. var timeSql, phoneSql, filtrationSql string
  161. if in.StartTime != "" {
  162. timeSql += fmt.Sprintf(" AND a.timestamp > %s", in.StartTime)
  163. }
  164. if in.EndTime != "" {
  165. timeSql += fmt.Sprintf(" AND a.timestamp < %s", in.EndTime)
  166. }
  167. if in.Phone != "" {
  168. phoneSql = " AND b.phone like '%" + in.Phone + "%'"
  169. }
  170. if in.FiltrationId != "" {
  171. var ids []string
  172. for _, v := range strings.Split(in.FiltrationId, ",") {
  173. ids = append(ids, encrypt.SE.Decode4Hex(v))
  174. }
  175. filtrationSql += fmt.Sprintf(" AND b.id not in (%s)", strings.Join(ids, ","))
  176. }
  177. aiSql := fmt.Sprintf(`(SELECT
  178. a.user_id,
  179. a.message_id,
  180. a.timestamp,
  181. b.nickname,
  182. 0 as unread,
  183. b.headimg,
  184. "" as phone,
  185. 0 as userType
  186. FROM
  187. socialize_summary a
  188. INNER JOIN base_user b ON (a.user_id = b.id AND a.ent_id = %d AND a.customer_service_access = 0))
  189. %s %s %s)`, in.EntId, timeSql, phoneSql, filtrationSql)
  190. serviceSql := fmt.Sprintf(`(SELECT
  191. a.user_id,
  192. c.message_id,
  193. c.timestamp,
  194. b.nickname,
  195. a.unread,
  196. b.headimg,
  197. "" as phone,
  198. 0 as userType
  199. FROM
  200. socialize_customer_service_user a
  201. INNER JOIN base_user b ON ( a.customer_service_id = %d AND a.user_id = b.id %s %s)
  202. INNER JOIN socialize_summary c ON ( a.ent_id = c.ent_id AND a.user_id = c.user_id %s))`, in.EntUserId, filtrationSql, phoneSql,
  203. strings.ReplaceAll(timeSql, "a.", "c."))
  204. var restrictionSql string
  205. switch in.IsArtificial {
  206. case 1:
  207. restrictionSql = serviceSql
  208. case 2:
  209. restrictionSql = aiSql
  210. default:
  211. restrictionSql = aiSql + " UNION ALL " + serviceSql
  212. }
  213. if in.Page <= 0 {
  214. in.Page = 1
  215. }
  216. if in.Size <= 0 || in.Size > 100 {
  217. in.Size = 50
  218. }
  219. sqlStr = fmt.Sprintf(`SELECT
  220. (
  221. CASE
  222. WHEN SUBSTR( a.nickname, 1, 3 ) = 'JY_' THEN
  223. CONCAT( SUBSTR( a.phone, 1, 3 ), '****', SUBSTR( a.phone, 8, 11 ) )
  224. WHEN a.nickname = ''
  225. OR a.nickname IS NULL THEN
  226. CONCAT( SUBSTR( a.phone, 1, 3 ), '****', SUBSTR( a.phone, 8, 11 ) ) ELSE a.nickname
  227. END
  228. ) AS name,
  229. c.content,
  230. c.title,
  231. c.type,
  232. c.link,
  233. c.create_time,
  234. a.message_id,
  235. a.timestamp,
  236. a.unread as number,
  237. a.user_id as id,
  238. a.headimg,
  239. a.phone,
  240. a.userType
  241. FROM
  242. (%s) a
  243. LEFT JOIN socialize_message c ON ( a.message_id = c.id )
  244. ORDER BY
  245. a.timestamp DESC`, restrictionSql)
  246. }
  247. var dataSize []map[string]interface{}
  248. if sqlStr != "" {
  249. log.Println("查询列表sql:", sqlStr)
  250. data = IC.BaseMysql.SelectBySql(sqlStr)
  251. if data != nil && len(*data) > 0 {
  252. count = quitl.Int64All(len(*data))
  253. log.Println("查询列表耗时2:", time.Since(tm), in.QueryType, count)
  254. switch in.UserType { //客服查询结果分页
  255. case 1:
  256. if in.Page*in.Size >= count {
  257. dataSize = (*data)[(in.Page-1)*in.Size:]
  258. } else {
  259. dataSize = (*data)[(in.Page-1)*in.Size : in.Page*in.Size]
  260. }
  261. return &dataSize, count, err
  262. case 2: //用户查询结果
  263. phoneMap, _, positionMap := EntPerson(in.EntId, true) //获取企业架构人员名称
  264. for _, v := range *data {
  265. if quitl.IntAll(v["userType"]) == 2 {
  266. v["name"] = phoneMap[quitl.InterfaceToStr(v["phone"])]
  267. } else if quitl.IntAll(v["userType"]) == 3 {
  268. var names []string
  269. if quitl.InterfaceToStr(v["groupMember"]) != "" {
  270. for _, id := range strings.Split(quitl.InterfaceToStr(v["groupMember"]), ",") {
  271. if len(names) > 4 {
  272. break
  273. }
  274. //防止匹配的是群名称 去除不匹配的群成员
  275. if strings.Contains(positionMap[quitl.IntAll(id)], in.NameSearch) {
  276. names = append(names, positionMap[quitl.IntAll(id)])
  277. }
  278. }
  279. }
  280. v["groupMember"] = names
  281. }
  282. }
  283. }
  284. }
  285. }
  286. return
  287. }
  288. // 客服会话列表
  289. func (b MessaggeService) ConversationList(in *messagecenter.ConversationReq) (data *[]map[string]interface{}, count int64, err error) {
  290. sqlStr := ""
  291. tm := time.Now()
  292. if in.UserType == 1 && in.FiltrationId != "" {
  293. var ids []string
  294. for _, v := range strings.Split(in.FiltrationId, ",") {
  295. ids = append(ids, encrypt.SE.Decode4Hex(v))
  296. }
  297. filtrationSql := fmt.Sprintf(" AND b.id in (%s)", strings.Join(ids, ","))
  298. aiSql := fmt.Sprintf(`(SELECT
  299. a.user_id,
  300. a.message_id,
  301. a.timestamp,
  302. b.nickname,
  303. 0 as unread,
  304. b.headimg
  305. FROM
  306. socialize_summary a
  307. INNER JOIN base_user b ON (a.user_id = b.id AND a.ent_id = %d AND a.customer_service_access = 0
  308. %s ))`, in.EntId, filtrationSql)
  309. serviceSql := fmt.Sprintf(`(SELECT
  310. a.user_id,
  311. c.message_id,
  312. c.timestamp,
  313. b.nickname,
  314. a.unread,
  315. b.headimg
  316. FROM
  317. socialize_customer_service_user a
  318. INNER JOIN base_user b ON ( a.customer_service_id = %d AND a.user_id = b.id %s)
  319. INNER JOIN socialize_summary c ON ( a.ent_id = c.ent_id AND a.user_id = c.user_id))`, in.EntUserId, filtrationSql)
  320. sqlStr = aiSql + " UNION ALL " + serviceSql
  321. }
  322. if sqlStr != "" {
  323. log.Println("查询列表sql:", sqlStr)
  324. data = IC.BaseMysql.SelectBySql(sqlStr)
  325. log.Println("查询耗时2:", time.Since(tm), count)
  326. }
  327. return
  328. }
  329. // 消息保存
  330. func (b MessaggeService) SaveMessage(in *messagecenter.MessageEntity) (fool bool, errorMsg string, content string, messageId, nowInt int64) {
  331. //先插入信息表
  332. //判断会话标识是否属于本人
  333. var customer_service_id, userid, entid, message_id int64
  334. nowForm := time.Now().Local()
  335. create_time := nowForm.Format(util.Date_Full_Layout)
  336. userId := int64(0)
  337. sessionId := int64(0)
  338. switch in.ItemType {
  339. case 4, 5, 8:
  340. if in.OwnType == 1 {
  341. sessionId = in.ReceiveId
  342. userId = in.NewUserId
  343. } else {
  344. sessionId = in.SendId
  345. userId = in.ReceiveId
  346. if in.ItemType == 4 || in.ItemType == 8 {
  347. userId = in.NewUserId
  348. }
  349. }
  350. break
  351. case 6:
  352. if in.OwnType == 1 {
  353. sessionId = in.ReceiveId
  354. userId = in.NewUserId
  355. } else if in.OwnType == 2 {
  356. sessionId = in.SendId
  357. userId = in.ReceiveId
  358. } else {
  359. sessionId = in.ReceiveId
  360. userId = in.NewUserId
  361. }
  362. break
  363. }
  364. //查找会话信息
  365. chatJson := IC.BaseMysql.FindOne(util.SOCIALIZE_CHAT_SESSION, map[string]interface{}{"id": sessionId}, "user_id,ent_id,customer_service_id", "")
  366. if chatJson == nil {
  367. return false, "会话标识不存在", "", 0, nowForm.Unix()
  368. } else {
  369. if userId != quitl.Int64All((*chatJson)["user_id"]) {
  370. return false, "会话标识不属于此用户", "", 0, nowForm.Unix()
  371. }
  372. }
  373. customer_service_id = quitl.Int64All((*chatJson)["customer_service_id"])
  374. entid = quitl.Int64All((*chatJson)["ent_id"])
  375. userid = userId
  376. userType := int64(1)
  377. //客服相关信息保存
  378. fool = IC.BaseMysql.ExecTx("聊天信息保存", func(tx *sql.Tx) bool {
  379. //先插入信息表
  380. message := map[string]interface{}{
  381. "appid": in.Appid,
  382. "title": in.Title,
  383. "content": in.Content,
  384. "item": in.Item,
  385. "type": in.Type,
  386. "link": in.Link,
  387. "create_time": create_time,
  388. "create_person": in.SendId,
  389. }
  390. data := map[string]interface{}{
  391. "item": in.Item,
  392. "type": in.Type,
  393. "create_time": create_time,
  394. "content": in.Content,
  395. }
  396. ok := IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_MESSAGE, message)
  397. receiveOk := int64(0)
  398. messageId, message_id = ok, ok
  399. data["id"] = ok
  400. //在插入邮箱表socialize_message_mailbox
  401. messageMailBox := map[string]interface{}{
  402. "appid": in.Appid,
  403. "messag_id": ok,
  404. "type": in.ItemType,
  405. "create_time": nowForm.Format(util.Date_Full_Layout),
  406. "isread": 0,
  407. "send_isdel": 0,
  408. "receive_isdel": 0,
  409. "iswithdraw": 0,
  410. }
  411. //系统信息处理
  412. if in.ItemType == 6 {
  413. messageMailBox = map[string]interface{}{
  414. "appid": in.Appid,
  415. "messag_id": ok,
  416. "type": in.ItemType,
  417. "create_time": nowForm.Format(util.Date_Full_Layout),
  418. "read_time": nowForm.Format(util.Date_Full_Layout),
  419. "isread": 1,
  420. "send_isdel": 0,
  421. "receive_isdel": 0,
  422. "iswithdraw": 0,
  423. }
  424. if in.OwnType == 1 {
  425. //用户接受系统信息
  426. messageMailBox["own_type"] = 2
  427. messageMailBox["send_user_type"] = 1
  428. messageMailBox["receive_user_type"] = 2
  429. messageMailBox["own_id"] = in.NewUserId
  430. messageMailBox["send_user_id"] = in.ReceiveId
  431. messageMailBox["receive_user_id"] = in.NewUserId
  432. } else if in.OwnType == 2 {
  433. //客服接受系统信息
  434. messageMailBox["own_type"] = 1
  435. messageMailBox["send_user_type"] = 2
  436. messageMailBox["receive_user_type"] = 1
  437. messageMailBox["own_id"] = in.SendId
  438. messageMailBox["send_user_id"] = in.ReceiveId
  439. messageMailBox["receive_user_id"] = in.SendId
  440. } else {
  441. //客服接受系统信息
  442. messageMailBox["own_type"] = 1
  443. messageMailBox["send_user_type"] = 2
  444. messageMailBox["receive_user_type"] = 1
  445. messageMailBox["own_id"] = in.ReceiveId
  446. messageMailBox["send_user_id"] = in.NewUserId
  447. messageMailBox["receive_user_id"] = in.ReceiveId
  448. }
  449. receiveOk = IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_MESSAGE_MAILBOX, messageMailBox)
  450. return ok > 1 && receiveOk > 1
  451. }
  452. if in.ItemType == 4 || in.ItemType == 8 || in.ItemType == 5 {
  453. //客服或者机器人聊天
  454. if in.OwnType == 1 {
  455. // (用户发送)客服接受
  456. messageMailBox["own_type"] = 1
  457. messageMailBox["send_user_type"] = 2
  458. messageMailBox["receive_user_type"] = 1
  459. messageMailBox["own_id"] = in.ReceiveId
  460. messageMailBox["send_user_id"] = in.NewUserId
  461. messageMailBox["receive_user_id"] = in.ReceiveId
  462. userType = 1
  463. userId = in.ReceiveId
  464. } else {
  465. //客服发送(用户接收信息)
  466. messageMailBox["own_type"] = 2
  467. messageMailBox["send_user_type"] = 1
  468. messageMailBox["receive_user_type"] = 2
  469. messageMailBox["own_id"] = in.ReceiveId
  470. messageMailBox["send_user_id"] = in.SendId
  471. messageMailBox["receive_user_id"] = in.ReceiveId
  472. userId = in.ReceiveId
  473. if in.ItemType == 4 || in.ItemType == 8 {
  474. messageMailBox["receive_user_id"] = in.NewUserId
  475. userId = in.NewUserId
  476. messageMailBox["own_id"] = in.NewUserId
  477. messageMailBox["isread"] = 1
  478. messageMailBox["read_time"] = nowForm.Format(util.Date_Full_Layout)
  479. }
  480. userType = 2
  481. }
  482. } else {
  483. messageMailBox["own_type"] = 2
  484. messageMailBox["send_user_type"] = 2
  485. messageMailBox["receive_user_type"] = 2
  486. messageMailBox["own_id"] = in.ReceiveId
  487. messageMailBox["send_user_id"] = in.NewUserId
  488. messageMailBox["receive_user_id"] = in.ReceiveId
  489. userType = 2
  490. userId = in.ReceiveId
  491. }
  492. receiveOk = IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_MESSAGE_MAILBOX, messageMailBox)
  493. messageMailBox = map[string]interface{}{
  494. "appid": in.Appid,
  495. "type": in.ItemType,
  496. "create_time": nowForm.Format(util.Date_Full_Layout),
  497. "messag_id": ok,
  498. "read_time": nowForm.Format(util.Date_Full_Layout),
  499. "isread": 1,
  500. "send_isdel": 0,
  501. "receive_isdel": 0,
  502. "iswithdraw": 0,
  503. }
  504. if in.ItemType == 4 || in.ItemType == 8 || in.ItemType == 5 {
  505. //客服或者机器人聊天
  506. if in.OwnType == 1 {
  507. //用户发送(用户接受)
  508. messageMailBox["own_type"] = 2
  509. messageMailBox["send_user_type"] = 2
  510. messageMailBox["receive_user_type"] = 1
  511. messageMailBox["own_id"] = in.NewUserId
  512. messageMailBox["send_user_id"] = in.NewUserId
  513. messageMailBox["receive_user_id"] = in.ReceiveId
  514. } else {
  515. //客服发送信息(用户接受)
  516. messageMailBox["own_type"] = 1
  517. messageMailBox["send_user_type"] = 1
  518. messageMailBox["receive_user_type"] = 2
  519. messageMailBox["own_id"] = in.SendId
  520. messageMailBox["send_user_id"] = in.SendId
  521. messageMailBox["receive_user_id"] = in.ReceiveId
  522. if in.ItemType == 4 || in.ItemType == 8 {
  523. messageMailBox["receive_user_id"] = in.NewUserId
  524. }
  525. }
  526. } else {
  527. messageMailBox["own_type"] = 2
  528. messageMailBox["send_user_type"] = 2
  529. messageMailBox["receive_user_type"] = 2
  530. messageMailBox["own_id"] = in.NewUserId
  531. messageMailBox["send_user_id"] = in.NewUserId
  532. messageMailBox["receive_user_id"] = in.ReceiveId
  533. }
  534. receiveOk = IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_MESSAGE_MAILBOX, messageMailBox)
  535. return ok > 1 && receiveOk > 1
  536. })
  537. if fool {
  538. go UserSynchronousList(customer_service_id, userid, entid, message_id, create_time, quitl.Int64All(quitl.If(userType == 1, 2, 1)))
  539. }
  540. return fool, "", in.Content, messageId, nowForm.Unix()
  541. }
  542. // 客服 用户聊天消息列表同步
  543. //sendUserType 发送人类型 1客服 2用户
  544. func UserSynchronousList(customerServiceId, userId, entId, messageId int64, createTime string, sendUserType int64) {
  545. log.Printf("同步最后消息参数customerServiceId:%d,userId:%d,entId%d,messageId:%d", customerServiceId, userId, entId, messageId)
  546. /* rwLock.Lock()
  547. defer rwLock.Unlock()*/
  548. nowForm := time.Now().Local()
  549. create_time := nowForm.Format(util.Date_Full_Layout)
  550. //查看汇总表
  551. log.Println(IC.BaseMysql.Count(util.SOCIALIZE_SUMMARY, map[string]interface{}{"user_id": userId, "ent_id": entId}))
  552. if IC.BaseMysql.Count(util.SOCIALIZE_SUMMARY, map[string]interface{}{"user_id": userId, "ent_id": entId}) > 0 {
  553. //更新汇总表
  554. ok := int64(0)
  555. if sendUserType == 1 {
  556. ok = IC.BaseMysql.UpdateOrDeleteBySql(fmt.Sprintf("UPDATE socialize_summary SET message_id = %d, unread = unread+1, customer_service_access = %d WHERE user_id = %d and ent_id= %d", messageId, quitl.If(customerServiceId > 0, 0, 1), userId, entId))
  557. } else {
  558. ok = IC.BaseMysql.UpdateOrDeleteBySql(fmt.Sprintf("UPDATE socialize_summary SET message_id = %d, customer_service_access = %d WHERE user_id = %d and ent_id= %d", messageId, quitl.If(customerServiceId > 0, 0, 1), userId, entId))
  559. }
  560. if ok > 0 && customerServiceId > 0 {
  561. //判断客服用户表是否存在
  562. if IC.BaseMysql.Count(util.Socialize_customer_service_user, map[string]interface{}{"user_id": userId, "ent_id": entId, "customer_service_id": customerServiceId}) > 0 {
  563. if sendUserType == 2 {
  564. IC.BaseMysql.UpdateOrDeleteBySql(fmt.Sprintf("UPDATE socialize_customer_service_user SET unread = unread+1 WHERE user_id = %d and customer_service_id= %d", userId, customerServiceId))
  565. }
  566. } else {
  567. IC.BaseMysql.Insert(util.SOCIALIZE_CUSTOMER_SERVICE_USER, map[string]interface{}{
  568. "user_id": userId,
  569. "ent_id": entId,
  570. "customer_service_id": customerServiceId,
  571. "unread": quitl.If(sendUserType == 1, 0, 1),
  572. })
  573. }
  574. }
  575. } else {
  576. //新增汇总表
  577. ok := IC.BaseMysql.Insert(util.SOCIALIZE_SUMMARY, map[string]interface{}{
  578. "user_id": userId,
  579. "ent_id": entId,
  580. "customer_service_access": quitl.If(customerServiceId > 0, 1, 0),
  581. "timestamp": create_time,
  582. "unread": quitl.If(sendUserType == 1, 0, 1),
  583. "message_id": messageId,
  584. })
  585. //新增客服用户表
  586. if ok > 0 && customerServiceId > 0 {
  587. IC.BaseMysql.Insert(util.SOCIALIZE_CUSTOMER_SERVICE_USER, map[string]interface{}{
  588. "user_id": userId,
  589. "ent_id": entId,
  590. "customer_service_id": customerServiceId,
  591. "unread": quitl.If(sendUserType == 1, 0, 1),
  592. })
  593. }
  594. }
  595. }
  596. // 历史信息查询
  597. func (b MessaggeService) FindMessage(in *messagecenter.MessageReq) *[]map[string]interface{} {
  598. log.Println(in.PositionId, in.NewUserId, in.EntId, in.ChatGroupId)
  599. sqlStr := ""
  600. lastStr := ""
  601. positionStr := ""
  602. if in.LastId > 0 {
  603. if in.Sort == "asc" {
  604. lastStr = fmt.Sprintf("AND a.messag_id > %d ", in.LastId)
  605. } else {
  606. lastStr = fmt.Sprintf("AND a.messag_id < %d ", in.LastId)
  607. }
  608. }
  609. switch in.MsgType {
  610. case 2: //点对点聊天
  611. 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 "+
  612. "FROM %s a "+
  613. "LEFT JOIN %s b on a.messag_id=b.id "+
  614. "LEFT JOIN %s c on c.id=a.send_user_id "+
  615. "LEFT JOIN %s d on d.id=a.receive_user_id "+
  616. "where a.own_id= %d and a.iswithdraw = 0 "+
  617. "AND ((a.send_user_id= %d AND a.receive_user_id= %d) or (a.send_user_id= %d AND a.receive_user_id= %d)) "+
  618. "AND a.type IN ( 2, 6 ) %s "+
  619. "AND a.chat_group_id IS null "+
  620. "AND a.send_user_type = a.receive_user_type "+
  621. "ORDER BY a.create_time desc,a.id asc "+
  622. "limit 0 , %d ",
  623. util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_MESSAGE, util.BASE_USER, util.BASE_USER,
  624. in.PositionId, in.PositionId, in.SendId, in.SendId, in.PositionId, lastStr, in.PageSize)
  625. break
  626. case 3: //群聊天
  627. sqlStr = fmt.Sprintf("SELECT a.messag_id AS messageId,b.*,a.send_user_type,a.type AS itemType,"+
  628. "IF ( a.own_id = a.send_user_id, 1, 2 ) AS fool,"+
  629. "IF ( a.own_id = a.send_user_id, 0, a.send_user_id ) AS send_position_id,"+
  630. "a.send_user_type,a.type AS itemType FROM %s a "+
  631. "LEFT JOIN %s b ON a.messag_id = b.id "+
  632. "WHERE a.own_type = 2 and a.iswithdraw = 0 AND a.own_id = %d "+
  633. "AND a.chat_group_id = %d AND a.type IN ( 3, 6 ) %s "+
  634. "ORDER BY a.create_time desc,a.id DESC "+
  635. "LIMIT 0, %d",
  636. util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_MESSAGE, in.PositionId,
  637. in.ChatGroupId, lastStr, in.PageSize)
  638. case 4, 5, 6, 7: //客服聊天
  639. //查询用户所有的职位id
  640. positionStr = GetUserAllPosition(in.NewUserId)
  641. if in.UserType == 1 {
  642. //客服聊天记录查看
  643. 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 "+
  644. "FROM %s a "+
  645. "LEFT JOIN %s b ON a.messag_id = b.id "+
  646. "LEFT JOIN %s c ON a.own_type = 1 AND a.own_id=c.id "+
  647. "WHERE a.own_type = 1 and a.iswithdraw = 0 "+
  648. "AND (a.type = 5 or a.type=4 or a.type=6 or a.type=7 or a.type=8 ) "+
  649. "AND c.ent_id = %d "+
  650. "AND c.user_id = %d %s "+
  651. "AND a.send_user_type != a.receive_user_type "+
  652. "ORDER BY a.create_time desc ,a.id asc "+
  653. "limit 0 , %d ",
  654. util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_MESSAGE, util.SOCIALIZE_CHAT_SESSION,
  655. in.EntId, in.SendId, lastStr, in.PageSize)
  656. } else {
  657. //用户聊天记录查看
  658. 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 "+
  659. "FROM %s a "+
  660. "LEFT JOIN %s b ON a.messag_id = b.id "+
  661. "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 "+
  662. "LEFT JOIN %s d on c.ent_id=d.ent_id "+
  663. "LEFT JOIN %s e on e.messag_id=b.id "+
  664. "WHERE a.own_type = 2 and a.iswithdraw = 0 "+
  665. "AND a.own_id = %d "+
  666. "AND c.ent_id = %d "+
  667. "AND c.user_id = %d "+
  668. "AND a.send_user_type != a.receive_user_type "+
  669. "AND ( a.type = 4 OR a.type = 5 or a.type=6 or a.type=7 or a.type=8) %s "+
  670. "ORDER BY a.create_time desc,a.id asc "+
  671. "limit 0 , %d ",
  672. util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_MESSAGE, util.SOCIALIZE_CHAT_SESSION, in.SendId, in.NewUserId, util.SOCIALIZE_TENANT_ROBOT, util.SOCIALIZE_APPRAISE,
  673. in.NewUserId, in.SendId, in.NewUserId, lastStr, in.PageSize)
  674. }
  675. break
  676. }
  677. log.Println(sqlStr)
  678. data := IC.BaseMysql.SelectBySql(sqlStr)
  679. //查询非自己发送消息得发送人名字
  680. //自己头像处理
  681. if in.UserType == 2 {
  682. userData := IC.BaseMysql.FindOne(util.BASE_USER, map[string]interface{}{"id": in.NewUserId}, "headimg", "")
  683. if userData != nil {
  684. for key := range *data {
  685. (*data)[key]["ownImg"] = (*userData)["headimg"]
  686. }
  687. }
  688. }
  689. if (in.MsgType == 3 || in.MsgType == 2) && data != nil && len(*data) > 0 {
  690. _, _, positionData := EntPerson(in.EntId, true)
  691. for _, v := range *data {
  692. positionId := quitl.IntAll(v["send_position_id"])
  693. if positionId != 0 {
  694. v["userName"] = positionData[positionId]
  695. //log.Println(v["userName"], positionData[positionId])
  696. }
  697. }
  698. }
  699. go func() {
  700. updateMap := map[string]interface{}{}
  701. if len(*data) > 0 && data != nil {
  702. //if true {
  703. //未读信息修改
  704. switch in.MsgType {
  705. case 2: //点对点聊天
  706. updateMap = map[string]interface{}{
  707. "own_type": 2,
  708. "own_id": in.NewUserId,
  709. "send_user_id": in.SendId,
  710. "type": 2,
  711. "isread": 0,
  712. }
  713. IC.BaseMysql.Update(util.SOCIALIZE_MESSAGE_MAILBOX, updateMap, map[string]interface{}{"isread": 1, "read_time": time.Now().Local().Format(util.Date_Full_Layout)})
  714. //更新socialize_summary表未读消息数量
  715. updateQuery := map[string]interface{}{
  716. "my_position_id": in.NewUserId,
  717. "your_position_id": in.SendId,
  718. }
  719. IC.BaseMysql.Update(util.SOCIALIZE_SUMMARY, updateQuery, map[string]interface{}{"unread": 0})
  720. break
  721. case 3: //群聊天
  722. sqlStr = fmt.Sprintf("UPDATE %s a SET a.isread = 1, a.read_time = now( ) "+
  723. "WHERE a.own_type = 1 "+
  724. "AND a.type IN (3,6) "+
  725. "AND a.isread = 0 "+
  726. "AND a.own_id = %d AND a.chat_group_id = %d",
  727. util.SOCIALIZE_MESSAGE_MAILBOX, in.SendId, in.ChatGroupId)
  728. IC.BaseMysql.UpdateOrDeleteBySql(sqlStr)
  729. //更新socialize_summary表未读消息数量
  730. updateQuery := map[string]interface{}{
  731. "my_position_id": in.NewUserId,
  732. "chat_group_id": in.ChatGroupId,
  733. }
  734. IC.BaseMysql.Update(util.SOCIALIZE_SUMMARY, updateQuery, map[string]interface{}{"unread": 0})
  735. case 4, 5:
  736. sqlStr := ""
  737. unreadSql := ""
  738. if in.UserType == 1 { //1客服
  739. sqlStr = fmt.Sprintf("UPDATE %s a SET a.isread = 1, a.read_time = now( ) "+
  740. "WHERE a.own_type = 1 and a.iswithdraw = 0 "+
  741. "AND a.type IN ( 4,5,6,7) "+
  742. "AND a.isread = 0 "+
  743. "AND a.own_id IN (SELECT id FROM %s WHERE user_id = %d)",
  744. util.SOCIALIZE_MESSAGE_MAILBOX, util.BASE_POSITION, in.NewUserId)
  745. unreadSql = fmt.Sprintf("UPDATE %s SET unread = 0 WHERE user_id = %d", util.Socialize_customer_service_user, in.NewUserId)
  746. } else { //2用户
  747. sqlStr = fmt.Sprintf("UPDATE %s a SET a.isread = 1, a.read_time = now( ) "+
  748. "WHERE a.own_type = 2 and a.iswithdraw = 0 "+
  749. "AND a.type IN ( 4,5,6,7 ) "+
  750. "AND a.isread = 0 "+
  751. "AND a.own_id in (%s) ", util.SOCIALIZE_MESSAGE_MAILBOX, positionStr)
  752. unreadSql = fmt.Sprintf("UPDATE %s SET unread = 0 WHERE user_id = %d", util.SOCIALIZE_SUMMARY, in.NewUserId)
  753. }
  754. IC.BaseMysql.UpdateOrDeleteBySql(sqlStr)
  755. IC.BaseMysql.UpdateOrDeleteBySql(unreadSql)
  756. break
  757. }
  758. //redis缓存处理
  759. //b.Count(in.NewUserId, in.UserType, in.EntUserId, true)
  760. }
  761. }()
  762. return data
  763. }
  764. // 创建会话
  765. func (b MessaggeService) CreateChatSession(in *messagecenter.ChatSessionReq) (fool bool, sessionId int64) {
  766. fool = IC.BaseMysql.ExecTx("会话新建", func(tx *sql.Tx) bool {
  767. customerserviceName := in.CustomerserviceName
  768. if in.CustomerServiceId != 0 {
  769. sqlStr := fmt.Sprintf("select customer_service_name from %s "+
  770. "where ent_id= %d "+
  771. "AND customer_service_id= %d ",
  772. util.SOCIALIZE_CHAT_SESSION, in.EntId, in.CustomerServiceId)
  773. customerList := IC.BaseMysql.SelectBySql(sqlStr)
  774. if len(*customerList) > 0 {
  775. customerserviceName = quitl.InterfaceToStr((*customerList)[0]["customer_service_name"])
  776. }
  777. }
  778. //查询企业是否存在
  779. count := IC.BaseMysql.Count(util.SOCIALIZE_TENANT_ROBOT, map[string]interface{}{
  780. "ent_id": in.EntId,
  781. })
  782. if count < 1 {
  783. return false
  784. }
  785. chatMession := map[string]interface{}{
  786. "handle_status": 0,
  787. "start_time": time.Now().Local().Format(util.Date_Full_Layout),
  788. "appid": in.AppId,
  789. "ent_id": in.EntId,
  790. "customer_service_id": in.CustomerServiceId,
  791. "user_id": in.UserId,
  792. "customer_service_name": customerserviceName,
  793. }
  794. sessionId = IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_CHAT_SESSION, chatMession)
  795. return sessionId > 0
  796. })
  797. return
  798. }
  799. // 结束会话
  800. func (b MessaggeService) CloseChatSession(in *messagecenter.CloseSessionReq) bool {
  801. fool := IC.BaseMysql.ExecTx("关闭会话", func(tx *sql.Tx) bool {
  802. updateMap := map[string]interface{}{
  803. "id": in.SessionId,
  804. }
  805. fool := IC.BaseMysql.Update(util.SOCIALIZE_CHAT_SESSION, updateMap, map[string]interface{}{"start_time": time.Now().Local().Format(util.Date_Full_Layout)})
  806. return fool
  807. })
  808. return fool
  809. }
  810. // 创建会话并保存信息
  811. func (b *MessaggeService) SaveAutoReplyMsg(userType, entId, entUserId, userId int64, content, appId, nowFormat string) (bool, int64) {
  812. var customer_service_id, userid, entid, message_id int64
  813. messageId := int64(0)
  814. ok1 := IC.BaseMysql.ExecTx("保存自动回复消息", func(tx *sql.Tx) bool {
  815. entUserName := ""
  816. if entUserId > 0 {
  817. 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)
  818. if list != nil && len(*list) > 0 {
  819. entUserName, _ = (*list)[0]["customer_service_name"].(string)
  820. }
  821. }
  822. messageId = IC.BaseMysql.InsertBySqlByTx(tx, `insert into socialize_message (appid,content,item,type,create_time,create_person) values (?,?,?,?,?,?)`, appId, content, 8, 1, nowFormat, "admin")
  823. 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)
  824. ok := false
  825. if userType == 0 {
  826. //客服给用户发送,归属客服已读
  827. 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
  828. //客服给用户发送,归属用户未读
  829. 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
  830. ok = ok1 && ok2
  831. userType = 1
  832. } else if userType == 1 {
  833. // 客服给用户发送 客服接受已读系统信息
  834. 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
  835. userType = 2
  836. } else if userType == 2 {
  837. //客服给用户发送消息 用户接受未读读系统信息
  838. 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
  839. userType = 1
  840. }
  841. message_id = messageId
  842. return messageId > 0 && sessionId > 0 && ok
  843. })
  844. if ok1 {
  845. customer_service_id = entUserId
  846. userid = userId
  847. entid = entId
  848. go UserSynchronousList(customer_service_id, userid, entid, message_id, nowFormat, userType)
  849. }
  850. return ok1, messageId
  851. }
  852. // 修改未读状态
  853. func (b MessaggeService) UpdateReadById(in *messagecenter.ReadStateReq) bool {
  854. fool := IC.BaseMysql.ExecTx("已读状态修改", func(tx *sql.Tx) bool {
  855. updateMap := map[string]interface{}{
  856. "messag_id": in.MessageId,
  857. "isread": 0,
  858. }
  859. fool := IC.BaseMysql.Update(util.SOCIALIZE_MESSAGE_MAILBOX, updateMap, map[string]interface{}{"read_time": time.Now().Local().Format(util.Date_Full_Layout), "isread": 1})
  860. if fool {
  861. //查询此条信息拥有者
  862. data := IC.BaseMysql.FindOne(util.SOCIALIZE_MESSAGE_MAILBOX, updateMap, "receive_user_type", "")
  863. if data != nil {
  864. userType := int64(1)
  865. userId := int64(0)
  866. if (*data)["receive_user_type"] == 2 {
  867. userType = 2
  868. userId = in.EntUserId
  869. } else {
  870. userType = 1
  871. userId = in.NewUserId
  872. }
  873. pc_a, err := util.GetData(userType, userId)
  874. if fool {
  875. if err == nil && pc_a != nil {
  876. //id一致
  877. if in.MessageId == pc_a.Data["id"] {
  878. util.SetData(userType, userId, map[string]interface{}{"data": map[string]interface{}{}, "count": pc_a.Count - 1}, IC.SurvivalTime)
  879. } else {
  880. util.SetData(userType, userId, map[string]interface{}{"data": data, "count": pc_a.Count - 1}, IC.SurvivalTime)
  881. }
  882. }
  883. }
  884. }
  885. }
  886. return fool
  887. })
  888. return fool
  889. }
  890. // WithdrawMessage 撤回消息
  891. func (b MessaggeService) WithdrawMessage(in *messagecenter.ReadWithdrawReq) bool {
  892. messageId := encrypt.SE.Decode4Hex(in.MessageId)
  893. msg := IC.BaseMysql.FindOne(util.SOCIALIZE_MESSAGE, map[string]interface{}{"id": messageId}, "create_time", "")
  894. if msg == nil || len(*msg) <= 0 {
  895. log.Println("查询消息id失败")
  896. return false
  897. }
  898. createTime, _ := time.Parse(util.Date_Full_Layout, quitl.InterfaceToStr((*msg)["create_time"]))
  899. if createTime.Unix()+60*2 < time.Now().Unix() {
  900. log.Println("消息已超过2分钟,撤回失败")
  901. return false
  902. }
  903. nowForm := time.Now().Local()
  904. m := IC.BaseMysql.Update(util.SOCIALIZE_MESSAGE_MAILBOX,
  905. map[string]interface{}{"messag_id": messageId}, map[string]interface{}{"iswithdraw": 1, "withdraw_time": nowForm.Format(util.Date_Full_Layout)})
  906. if m {
  907. go SynchronousInfo(in.SenderId, in.RecipientId, in.ConversationType, quitl.Int64All(messageId), in.UserType, in.EntId, in.ChatGroupId)
  908. }
  909. return m
  910. }
  911. // 撤回消息同步信息
  912. func SynchronousInfo(sender, recipient, conversationType, messageId, userType, entId, chatGroupId int64) {
  913. switch conversationType {
  914. case 1: //1v1用户聊天
  915. if IC.BaseMysql.Count(util.SOCIALIZE_MESSAGE_MAILBOX, map[string]interface{}{"messag_id": messageId, "own_id": recipient, "isread": 0}) > 0 {
  916. 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))
  917. }
  918. case 2: //用户与客服
  919. if IC.BaseMysql.Count(util.SOCIALIZE_MESSAGE_MAILBOX, map[string]interface{}{"messag_id": messageId, "own_id": recipient, "isread": 0}) > 0 {
  920. if userType == 2 { //发送人是用户
  921. //接收人是会话标识 查询客服id
  922. data := IC.BaseMysql.FindOne(util.SOCIALIZE_CHAT_SESSION, map[string]interface{}{"id": recipient}, "", "")
  923. if data != nil && len(*data) > 0 {
  924. 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))
  925. }
  926. } else { //发送人是客服
  927. 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))
  928. }
  929. }
  930. case 3: //一对群
  931. data := IC.BaseMysql.Find(util.SOCIALIZE_MESSAGE_MAILBOX, map[string]interface{}{"messag_id": messageId, "chat_group_id": chatGroupId, "isread": 0}, "own_id", "", -1, -1)
  932. if data != nil && len(*data) > 0 {
  933. var ownIds []string
  934. for _, v := range *data {
  935. ownIds = append(ownIds, quitl.InterfaceToStr(v["own_id"]))
  936. }
  937. 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, ",")))
  938. }
  939. }
  940. }
  941. // AppraiseMessage 消息评价
  942. func (b MessaggeService) AppraiseMessage(in *messagecenter.AppraiseReq) error {
  943. messageId := encrypt.SE.Decode4Hex(in.MessageId)
  944. //查询此条消息是否是当前用户的
  945. if IC.BaseMysql.Count(util.SOCIALIZE_MESSAGE_MAILBOX, map[string]interface{}{
  946. "messag_id": messageId,
  947. "receive_user_id": in.NewUserId,
  948. "receive_user_type": 2,
  949. "type": 8,
  950. }) == 0 {
  951. return fmt.Errorf("未查询到信息")
  952. }
  953. if IC.BaseMysql.Count(util.SOCIALIZE_APPRAISE, map[string]interface{}{
  954. "appid": in.Appid,
  955. "messag_id": messageId,
  956. }) > 0 {
  957. return fmt.Errorf("请勿重复评价")
  958. }
  959. //插入评价
  960. if IC.BaseMysql.Insert(util.SOCIALIZE_APPRAISE, map[string]interface{}{
  961. "appid": in.Appid,
  962. "messag_id": messageId,
  963. "create_time": time.Now().Local().Format(util.Date_Full_Layout),
  964. "appraise": in.Appraise,
  965. }) > 0 {
  966. return nil
  967. }
  968. return fmt.Errorf("评价消息异常")
  969. }
  970. // 聊天
  971. // 包含 1v1 ,群聊,群发
  972. /*
  973. 类型;1:站内信消息 2:点对点消息 3:群消息 4:机器人消息 5:客服消息 6系统信息 7:客服自动回复 8:评价 9:其它系统消息 (除客服以外的) 10:撤回(自己看到的) 11:撤回(其他人看到的)
  974. 群撤回自己看到的和用户看到的不一样
  975. */
  976. func (this *MessaggeService) Chat(in *messagecenter.MessageEntity) (fool bool, errorMsg string, content string, messageId, nowInt int64) {
  977. now := time.Now()
  978. nowTime := now.Format(date.Date_Full_Layout)
  979. messageId = int64(0)
  980. fool = IC.BaseMysql.ExecTx("消息存储", func(tx *sql.Tx) bool {
  981. isGroup := len(in.GroupIds) > 0
  982. isOneToOne := len(in.ReceiverIds) > 0
  983. isWithdrawByMyself := in.ItemType == 10
  984. isWithdrawByOthers := in.ItemType == 11
  985. createperson := strconv.Itoa(int(in.SendId))
  986. messageId = MessageAdd(tx, in.Appid, in.Title, in.Content, createperson, in.Link, in.Item, in.Type)
  987. //是否客服介入
  988. isCustomerServiceAccess := 0
  989. //除客服消息以外的系统消息
  990. if in.ItemType == 9 || in.ItemType == 10 || in.ItemType == 11 {
  991. in.ItemType = 6
  992. }
  993. //群聊
  994. if isGroup {
  995. //修改类型为群聊
  996. if in.ItemType != 6 {
  997. in.ItemType = 3
  998. }
  999. 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"}
  1000. for _, v := range in.GroupIds {
  1001. args := []interface{}{}
  1002. //发送人自己
  1003. if !isWithdrawByOthers {
  1004. args = append(args, in.Appid, messageId, in.ItemType, in.SendId, 2, in.SendId, 2, 2, in.SendId, nowTime, v, 1)
  1005. //最后一次聊天
  1006. SocializeSummaryAddOrUpdate(tx, v, in.SendId, 0, messageId, isCustomerServiceAccess, nowTime)
  1007. }
  1008. if !isWithdrawByMyself {
  1009. groupUser := GetUserByGroupId(tx, v, in.SendId)
  1010. for _, vv := range groupUser {
  1011. log.Println("获取到群组下员工:", vv)
  1012. //接收人其他用户
  1013. args = append(args, in.Appid, messageId, in.ItemType, in.SendId, 2, vv, 2, 2, vv, nowTime, v, 0)
  1014. //最后一次聊天
  1015. SocializeSummaryAddOrUpdate(tx, v, 0, vv, messageId, isCustomerServiceAccess, nowTime)
  1016. }
  1017. }
  1018. MessageMailBoxAdd(tx, fieids, args)
  1019. }
  1020. }
  1021. //1v1
  1022. if isOneToOne {
  1023. //修改类型为个人
  1024. if in.ItemType != 6 {
  1025. in.ItemType = 2
  1026. }
  1027. 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"}
  1028. args := []interface{}{}
  1029. if !isWithdrawByOthers {
  1030. args = append(args, in.Appid, messageId, in.ItemType, in.SendId, 2, in.SendId, 2, 2, in.SendId, nowTime, 1)
  1031. }
  1032. if !isWithdrawByMyself {
  1033. for _, v := range in.ReceiverIds {
  1034. args = append(args, in.Appid, messageId, in.ItemType, in.SendId, 2, v, 2, 2, v, nowTime, 0)
  1035. //最后一次聊天
  1036. SocializeSummaryAddOrUpdate(tx, 0, in.SendId, v, messageId, isCustomerServiceAccess, nowTime)
  1037. // SocializeSummaryAddOrUpdate(tx, 0, v, in.SendId, messageId, isCustomerServiceAccess, nowTime)
  1038. }
  1039. MessageMailBoxAdd(tx, fieids, args)
  1040. }
  1041. }
  1042. return true
  1043. })
  1044. return fool, "", in.Content, messageId, now.Unix()
  1045. }
  1046. // 消息存储
  1047. func MessageAdd(tx *sql.Tx, appid, title, content, createperson, link string, item, messageType int64) int64 {
  1048. nowTime := time.Now()
  1049. message := map[string]interface{}{
  1050. "appid": appid,
  1051. "title": title,
  1052. "content": content,
  1053. "item": item,
  1054. "type": messageType,
  1055. "link": link,
  1056. "create_time": nowTime.Format(date.Date_Full_Layout),
  1057. "create_person": createperson, //系统消息时,创建人是群聊id或接收人id
  1058. }
  1059. return IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_MESSAGE, message)
  1060. }
  1061. // 消息信息箱存储
  1062. // types 2:点对点 3:群消息
  1063. func MessageMailBoxAdd(tx *sql.Tx, fieids []string, args []interface{}) (int64, int64) {
  1064. length, lastId := IC.BaseMysql.InsertBatchByTx(tx, util.SOCIALIZE_MESSAGE_MAILBOX, fieids, args)
  1065. log.Println("MessageMailBoxAdd length:", length, "MessageMailBoxAdd lastId:", lastId)
  1066. return length, lastId
  1067. }
  1068. // 获取除发送人以外的群成员
  1069. func GetUserByGroupId(tx *sql.Tx, groupId, sendId int64) []int64 {
  1070. arr := []int64{}
  1071. 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)
  1072. if data == nil || len(*data) <= 0 {
  1073. return arr
  1074. }
  1075. for _, v := range *data {
  1076. position_id := quitl.Int64All(v["position_id"])
  1077. if position_id == 0 {
  1078. continue
  1079. }
  1080. arr = append(arr, position_id)
  1081. }
  1082. return arr
  1083. }
  1084. // 最后一次聊天存储
  1085. //1v1是双方的
  1086. //群聊是发送人和其他人的
  1087. func SocializeSummaryAddOrUpdate(tx *sql.Tx, groupId, myPositionId, yourPositionId, messageId int64, isCustomerServiceAccess int, timestamp string) bool {
  1088. //判断是否存在
  1089. if groupId > 0 {
  1090. isSend := myPositionId != 0
  1091. if isSend {
  1092. 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 {
  1093. //存在更新
  1094. return IC.BaseMysql.UpdateByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
  1095. "chat_group_id": groupId,
  1096. "my_position_id": myPositionId,
  1097. }, map[string]interface{}{
  1098. "message_id": messageId,
  1099. "timestamp": timestamp,
  1100. })
  1101. } else {
  1102. //新增
  1103. return IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
  1104. "chat_group_id": groupId,
  1105. "my_position_id": myPositionId,
  1106. "message_id": messageId,
  1107. "timestamp": timestamp,
  1108. "unread": 0,
  1109. }) > 0
  1110. }
  1111. } else {
  1112. 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 {
  1113. //存在更新
  1114. return IC.BaseMysql.UpdateByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
  1115. "chat_group_id": groupId,
  1116. "my_position_id": yourPositionId,
  1117. }, map[string]interface{}{
  1118. "message_id": messageId,
  1119. "timestamp": timestamp,
  1120. "unread": gconv.Int((*r)[0]["unread"]) + 1,
  1121. })
  1122. } else {
  1123. //新增
  1124. return IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
  1125. "chat_group_id": groupId,
  1126. "my_position_id": yourPositionId,
  1127. "message_id": messageId,
  1128. "timestamp": timestamp,
  1129. "unread": 1,
  1130. }) > 0
  1131. }
  1132. }
  1133. } else {
  1134. if yourPositionId > 0 {
  1135. ok_my := true
  1136. ok_your := true
  1137. //发送方
  1138. 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 {
  1139. //存在更新
  1140. ok_my = IC.BaseMysql.UpdateByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
  1141. "my_position_id": myPositionId,
  1142. "your_position_id": yourPositionId,
  1143. }, map[string]interface{}{
  1144. "message_id": messageId,
  1145. "timestamp": timestamp,
  1146. })
  1147. } else {
  1148. //新增
  1149. ok_my = IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
  1150. "my_position_id": myPositionId,
  1151. "your_position_id": yourPositionId,
  1152. "message_id": messageId,
  1153. "timestamp": timestamp,
  1154. "unread": 0,
  1155. "customer_service_access": isCustomerServiceAccess,
  1156. }) > 0
  1157. }
  1158. //接收方
  1159. 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), yourPositionId, myPositionId); r != nil && len(*r) > 0 {
  1160. //存在更新
  1161. ok_your = IC.BaseMysql.UpdateByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
  1162. "my_position_id": yourPositionId,
  1163. "your_position_id": myPositionId,
  1164. }, map[string]interface{}{
  1165. "message_id": messageId,
  1166. "timestamp": timestamp,
  1167. "unread": gconv.Int((*r)[0]["unread"]) + 1,
  1168. })
  1169. } else {
  1170. //新增
  1171. ok_your = IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
  1172. "my_position_id": yourPositionId,
  1173. "your_position_id": myPositionId,
  1174. "message_id": messageId,
  1175. "timestamp": timestamp,
  1176. "unread": 1,
  1177. "customer_service_access": isCustomerServiceAccess,
  1178. }) > 0
  1179. }
  1180. return ok_my && ok_your
  1181. }
  1182. }
  1183. return true
  1184. }
  1185. // 群组人员未读消息更新
  1186. func GroupUserUnReadUpdate(tx *sql.Tx, ids []int64) bool {
  1187. whs := []string{}
  1188. for i := 0; i < len(ids); i++ {
  1189. whs = append(whs, "?")
  1190. }
  1191. wh := strings.Join(whs, ",")
  1192. interfaces := gconv.Interfaces(ids)
  1193. count := IC.BaseMysql.UpdateOrDeleteBySql(`UPDATE `+util.SOCIALIZE_CHAT_GROUP_PERSON+` SET unread = unread + 1 WHERE id in (`+wh+`)`, interfaces...)
  1194. if count > 0 {
  1195. return true
  1196. }
  1197. return true
  1198. }
  1199. // GetUserAllPosition 用户下所有职位id
  1200. func GetUserAllPosition(baseUserId int64) (positionStr string) {
  1201. //查询用户所有的职位id
  1202. sqlPosition := fmt.Sprintf("SELECT id FROM %s WHERE user_id = %d", util.BASE_POSITION, baseUserId)
  1203. positionArr := IC.BaseMysql.SelectBySql(sqlPosition)
  1204. if positionArr != nil && len(*positionArr) > 0 {
  1205. for k, val := range *positionArr {
  1206. if k < len(*positionArr)-1 {
  1207. positionStr += strconv.Itoa(quitl.IntAll(val["id"])) + ","
  1208. } else {
  1209. positionStr += strconv.Itoa(quitl.IntAll(val["id"]))
  1210. }
  1211. }
  1212. }
  1213. return positionStr
  1214. }