message_mail_box.go 42 KB

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