message_mail_box.go 45 KB

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