message_mail_box.go 47 KB

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