message_mail_box.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. package service
  2. import (
  3. quitl "app.yhyue.com/moapp/jybase/common"
  4. "app.yhyue.com/moapp/jybase/encrypt"
  5. util "bp.jydev.jianyu360.cn/SocialPlatform/messageCenter/entity"
  6. "bp.jydev.jianyu360.cn/SocialPlatform/messageCenter/rpc/messagecenter/messagecenter"
  7. "database/sql"
  8. "fmt"
  9. "log"
  10. "time"
  11. )
  12. type MessaggeService struct{}
  13. // 未读消息查询
  14. func (b MessaggeService) Count(newUserId, userType, entUserId int64, isClean bool) (count int, last map[string]interface{}, err error) {
  15. log.Printf("用户id:%d,userType:%d,entUserId:%d,isClean:%v", newUserId, userType, entUserId, isClean)
  16. v := make([]interface{}, 0)
  17. sqlStr := ""
  18. if userType == 1 {
  19. //查询缓存里边是否有数据
  20. pc_a, err := util.GetData(userType, entUserId)
  21. if err == nil && pc_a != nil {
  22. // 缓存有值
  23. if !isClean {
  24. return pc_a.Count, pc_a.Data, err
  25. }
  26. }
  27. sqlStr = fmt.Sprintf("select count(b.id) from %s a "+
  28. "LEFT JOIN %s b ON a.id=b.own_id "+
  29. "where b.type=5 "+
  30. "AND a.customer_service_id=%d "+
  31. "AND b.iswithdraw = 0 "+
  32. "AND b.isread=0 "+
  33. "AND own_type = 1 "+
  34. "order by create_time", util.SOCIALIZE_CHAT_SESSION, util.SOCIALIZE_MESSAGE_MAILBOX, entUserId)
  35. } else {
  36. pc_a, err := util.GetData(userType, newUserId)
  37. if err == nil && pc_a != nil {
  38. if !isClean {
  39. return pc_a.Count, pc_a.Data, err
  40. }
  41. }
  42. sqlStr = fmt.Sprintf("select count(b.id) from %s b "+
  43. "where b.send_user_id != %d "+
  44. "AND b.own_id=%d "+
  45. "AND b.iswithdraw = 0 "+
  46. "AND b.isread=0 "+
  47. "AND own_type = 2 "+
  48. "order by create_time", util.SOCIALIZE_MESSAGE_MAILBOX, newUserId, newUserId)
  49. }
  50. log.Println(sqlStr, v)
  51. rs := util.Mysql.CountBySql(sqlStr, v...)
  52. log.Println(rs)
  53. count = int(rs)
  54. //最后一条信息查询
  55. sqlStr = fmt.Sprintf("SELECT c.* FROM %s b "+
  56. "LEFT join %s c on b.messag_id=c.id "+
  57. "WHERE b.send_user_id != %d "+
  58. "AND b.own_id = %d "+
  59. "AND b.iswithdraw = 0 "+
  60. "AND b.isread=0 "+
  61. "AND own_type = 2 "+
  62. "ORDER BY create_time DESC "+
  63. "LIMIT 0,1", util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_MESSAGE,
  64. newUserId, newUserId)
  65. lastData := util.Mysql.SelectBySql(sqlStr)
  66. if len(*lastData) > 0 {
  67. last = (*lastData)[0]
  68. if userType == 1 {
  69. util.SetData(userType, entUserId, map[string]interface{}{"data": last, "count": count}, util.SurvivalTime)
  70. } else {
  71. util.SetData(userType, newUserId, map[string]interface{}{"data": last, "count": count}, util.SurvivalTime)
  72. }
  73. } else {
  74. if userType == 1 {
  75. util.SetData(userType, entUserId, map[string]interface{}{"data": map[string]interface{}{}, "count": count}, util.SurvivalTime)
  76. } else {
  77. util.SetData(userType, newUserId, map[string]interface{}{"data": map[string]interface{}{}, "count": count}, util.SurvivalTime)
  78. }
  79. }
  80. return
  81. }
  82. // 用户列表查询
  83. func (b MessaggeService) UserList(in *messagecenter.UserReq) (data *[]map[string]interface{}, count int64, err error) {
  84. sqlStr := ""
  85. tm := time.Now()
  86. if in.UserType == 2 {
  87. //用户最后一次信息查询
  88. userSql := fmt.Sprintf("SELECT MAX( c.id ) as messageId FROM socialize_message_mailbox c "+
  89. "WHERE c.own_id = %d "+
  90. "AND c.iswithdraw = 0 "+
  91. "AND c.type = 2 "+
  92. "AND c.own_type = 2 "+
  93. "GROUP BY ( CASE WHEN c.send_user_id > c.receive_user_id "+
  94. "THEN CONCAT( c.send_user_id, c.receive_user_id ) "+
  95. "WHEN c.send_user_id < c.receive_user_id "+
  96. "THEN CONCAT( c.receive_user_id, c.send_user_id ) END ) ", in.NewUserId,
  97. )
  98. data = util.Mysql.SelectBySql(userSql)
  99. userMessageId := util.Inhandle(data)
  100. //客服最后一次信息查询
  101. customerSql := fmt.Sprintf("SELECT MAX( c.id ) as messageId FROM %s c "+
  102. "LEFT JOIN %s d ON IF ( c.send_user_type = 1, d.id = c.send_user_id, d.id = c.receive_user_id ) "+
  103. "WHERE c.own_id = %d "+
  104. "AND c.iswithdraw = 0 "+
  105. "AND ( c.type = 4 OR c.type = 5 or c.type=6 or c.type=7 ) "+
  106. "AND c.own_type = 2 "+
  107. "AND d.user_id=c.own_id "+
  108. "GROUP BY d.ent_id ", util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_CHAT_SESSION, in.NewUserId)
  109. data = util.Mysql.SelectBySql(customerSql)
  110. customerMessageId := util.Inhandle(data)
  111. //用户的列表
  112. sqlStr = fmt.Sprintf("SELECT "+
  113. "( CASE WHEN SUBSTR( b.nickname, 1, 3 ) = 'JY_' THEN CONCAT( SUBSTR( b.phone, 1, 3 ), '****', SUBSTR( b.phone, 8, 11 ) ) WHEN b.nickname = '' or b.nickname is null THEN CONCAT( SUBSTR( b.phone, 1, 3 ), '****', SUBSTR( b.phone, 8, 11 ) ) ELSE b.nickname END )"+
  114. "AS name, b.id, e.title, b.headimg, e.type, e.link, e.content, 2 AS userType, a.create_time, a.type AS itemType, "+
  115. "( SELECT count( h.id ) FROM %s h "+
  116. "WHERE h.type = 2 "+
  117. "AND h.own_id = %d "+
  118. "AND h.own_type = 2 "+
  119. "AND h.send_user_id=b.id "+
  120. "AND h.isread = 0 AND h.iswithdraw = 0 ) AS number FROM %s a "+
  121. "LEFT JOIN %s b ON b.id = a.receive_user_id or b.id = a.send_user_id "+
  122. "LEFT JOIN %s e ON e.id = a.messag_id "+
  123. "WHERE a.id IN ( %s ) AND b.id != %d "+
  124. "UNION ALL "+
  125. "SELECT f.nickname AS name, b.ent_id AS id, e.title,f.headimage AS headimg, e.type, e.link, e.content, 1 AS userType, a.create_time, a.type AS itemType, "+
  126. "( SELECT count( h.id ) FROM %s h WHERE ( h.type = 4 OR h.type = 5 ) AND h.own_id = %d AND h.own_type = 2 AND h.send_user_type = 1 AND h.receive_user_id = %d AND h.isread = 0 ) AS number "+
  127. "FROM %s a "+
  128. "LEFT JOIN %s b ON IF ( a.send_user_type = 1, a.send_user_id, a.receive_user_id ) = b.id "+
  129. "LEFT JOIN %s e ON e.id = a.messag_id "+
  130. "LEFT join %s f on f.ent_id=b.ent_id "+
  131. "WHERE a.id IN ( %s ) "+
  132. "ORDER BY create_time DESC",
  133. util.SOCIALIZE_MESSAGE_MAILBOX,
  134. in.NewUserId,
  135. util.SOCIALIZE_MESSAGE_MAILBOX,
  136. util.BASE_USER,
  137. util.SOCIALIZE_MESSAGE,
  138. userMessageId,
  139. in.NewUserId,
  140. util.SOCIALIZE_MESSAGE_MAILBOX,
  141. in.NewUserId,
  142. in.NewUserId,
  143. util.SOCIALIZE_MESSAGE_MAILBOX,
  144. util.SOCIALIZE_CHAT_SESSION,
  145. util.SOCIALIZE_MESSAGE,
  146. util.SOCIALIZE_TENANT_ROBOT,
  147. customerMessageId)
  148. } else {
  149. phoneSql := ""
  150. if in.Phone != "" {
  151. phoneSql = "AND b.phone like '%" + in.Phone + "%'"
  152. }
  153. startTimeSql := ""
  154. if in.StartTime != "" {
  155. startTimeSql = "AND DATE_FORMAT(c.create_time,'%Y-%m-%d') >= '" + in.StartTime + "' "
  156. }
  157. idSql := fmt.Sprintf("(SELECT COUNT(e.id) FROM socialize_chat_session e WHERE e.customer_service_id > 0 AND e.user_id = d.user_id ) =0 or d.customer_service_id=%d ", in.EntUserId)
  158. if in.IsArtificial == 1 {
  159. idSql = fmt.Sprintf("d.customer_service_id = %d ", in.EntUserId)
  160. } else if in.IsArtificial == 2 {
  161. idSql = "(SELECT COUNT(e.id) FROM socialize_chat_session e WHERE e.customer_service_id > 0 AND e.user_id = d.user_id ) =0 "
  162. }
  163. endTimeSql := ""
  164. if in.EndTime != "" {
  165. endTimeSql = "AND DATE_FORMAT(c.create_time,'%Y-%m-%d') <= '" + in.EndTime + "' "
  166. }
  167. if in.Page <= 0 {
  168. in.Page = 1
  169. }
  170. if in.Size <= 0 || in.Size > 100 {
  171. in.Size = 50
  172. }
  173. userSql := fmt.Sprintf("SELECT MAX( c.id ) as messageId FROM %s c "+
  174. "LEFT JOIN %s d ON c.own_type=1 AND c.own_id=d.id "+
  175. "LEFT JOIN %s b ON if (c.send_user_type=1 ,c.receive_user_id,c.send_user_id)=b.id "+
  176. "WHERE c.own_type = 1 "+
  177. "AND c.iswithdraw = 0 "+
  178. "AND (%s) "+
  179. "AND ( c.type = 4 OR c.type = 5 or c.type=6 or c.type=7 ) "+
  180. " %s %s %s "+
  181. "GROUP BY ( CASE WHEN c.send_user_type =2 THEN CONCAT( c.send_user_id ) WHEN c.send_user_type =1 THEN CONCAT( c.receive_user_id ) END ) ",
  182. util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_CHAT_SESSION, util.BASE_USER,
  183. idSql, startTimeSql, endTimeSql, phoneSql)
  184. countSql := fmt.Sprintf("SELECT * FROM (%s) as data order by messageId desc ", userSql)
  185. countData := util.Mysql.SelectBySql(countSql)
  186. log.Println("查询最新消息数量sql:", countSql)
  187. if countData != nil && len(*countData) > 0 {
  188. log.Printf("查询耗时1:%d;查询数量:%d", time.Since(tm), count)
  189. count = quitl.Int64All(len(*countData))
  190. var d []map[string]interface{}
  191. if in.Page*in.Size >= count {
  192. d = (*countData)[(in.Page-1)*in.Size:]
  193. } else {
  194. d = (*countData)[(in.Page-1)*in.Size : in.Page*in.Size]
  195. }
  196. customerMessageId := util.Inhandle(&d)
  197. //客服的用户列表
  198. sqlStr = fmt.Sprintf("SELECT "+
  199. "( CASE WHEN SUBSTR( b.nickname, 1, 3 ) = 'JY_' THEN CONCAT( SUBSTR( b.phone, 1, 3 ), '****', SUBSTR( b.phone, 8, 11 ) ) WHEN b.nickname = '' or b.nickname is null THEN CONCAT( SUBSTR( b.phone, 1, 3 ), '****', SUBSTR( b.phone, 8, 11 ) ) ELSE b.nickname END )"+
  200. " AS name, b.id, e.title, b.headimg, e.type, e.link, e.content, a.create_time, "+
  201. "( SELECT count( h.id ) FROM %s h "+
  202. "LEFT JOIN %s i ON h.own_type = 1 AND h.own_id = i.id "+
  203. "WHERE h.own_type = 1 "+
  204. "AND i.ent_id=f.ent_id "+
  205. "AND i.user_id=f.user_id "+
  206. "AND h.isread = 0 "+
  207. "AND h.iswithdraw = 0 "+
  208. "AND i.customer_service_id= %d) AS number "+
  209. "FROM %s a "+
  210. "LEFT JOIN %s b ON if (a.send_user_type=1 ,a.receive_user_id,a.send_user_id)=b.id "+
  211. "LEFT JOIN %s e ON e.id = a.messag_id "+
  212. "LEFT JOIN %s f ON a.own_type=1 AND a.own_id=f.id "+
  213. "WHERE a.id IN ( %s) %s ORDER BY a.create_time DESC",
  214. util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_CHAT_SESSION,
  215. in.EntUserId, util.SOCIALIZE_MESSAGE_MAILBOX, util.BASE_USER, util.SOCIALIZE_MESSAGE, util.SOCIALIZE_CHAT_SESSION, customerMessageId, phoneSql)
  216. }
  217. }
  218. if sqlStr != "" {
  219. log.Println("查询列表sql:", sqlStr)
  220. data = util.Mysql.SelectBySql(sqlStr)
  221. log.Println("查询耗时2:", time.Since(tm), count)
  222. if in.UserType == 2 && data != nil && len(*data) > 0 {
  223. count = quitl.Int64All(len(*data))
  224. }
  225. }
  226. return
  227. }
  228. // 消息保存
  229. func (b MessaggeService) SaveMessage(in *messagecenter.MessageEntity) (fool bool, errorMsg string, content string, messageId, nowInt int64) {
  230. //先插入信息表
  231. //判断会话标识是否属于本人
  232. nowForm := time.Now().Local()
  233. if in.ItemType != 2 {
  234. userId := int64(0)
  235. sessionId := int64(0)
  236. switch in.ItemType {
  237. case 4, 5, 8:
  238. if in.OwnType == 1 {
  239. sessionId = in.ReceiveId
  240. userId = in.NewUserId
  241. } else {
  242. sessionId = in.SendId
  243. userId = in.ReceiveId
  244. if in.ItemType == 4 || in.ItemType == 8 {
  245. userId = in.NewUserId
  246. }
  247. }
  248. break
  249. case 6:
  250. if in.OwnType == 1 {
  251. sessionId = in.ReceiveId
  252. userId = in.NewUserId
  253. } else if in.OwnType == 2 {
  254. sessionId = in.SendId
  255. userId = in.ReceiveId
  256. } else {
  257. sessionId = in.ReceiveId
  258. userId = in.NewUserId
  259. }
  260. break
  261. }
  262. //查找会话信息
  263. chatJson := util.Mysql.FindOne(util.SOCIALIZE_CHAT_SESSION, map[string]interface{}{"id": sessionId}, "user_id", "")
  264. if chatJson == nil {
  265. return false, "会话标识不存在", "", 0, nowForm.Unix()
  266. } else {
  267. if userId != quitl.Int64All((*chatJson)["user_id"]) {
  268. return false, "会话标识不属于此用户", "", 0, nowForm.Unix()
  269. }
  270. }
  271. }
  272. fool = util.Mysql.ExecTx("聊天信息保存", func(tx *sql.Tx) bool {
  273. //先插入信息表
  274. create_time := nowForm.Format(util.Date_Full_Layout)
  275. userType := int64(1)
  276. userId := int64(0)
  277. message := map[string]interface{}{
  278. "appid": in.Appid,
  279. "title": in.Title,
  280. "content": in.Content,
  281. "item": in.Item,
  282. "type": in.Type,
  283. "link": in.Link,
  284. "create_time": create_time,
  285. "create_person": in.SendId,
  286. }
  287. data := map[string]interface{}{
  288. "item": in.Item,
  289. "type": in.Type,
  290. "create_time": create_time,
  291. "content": in.Content,
  292. }
  293. ok := util.Mysql.InsertByTx(tx, util.SOCIALIZE_MESSAGE, message)
  294. receiveOk := int64(0)
  295. messageId = ok
  296. data["id"] = ok
  297. //在插入邮箱表socialize_message_mailbox
  298. messageMailBox := map[string]interface{}{
  299. "appid": in.Appid,
  300. "messag_id": ok,
  301. "type": in.ItemType,
  302. "create_time": nowForm.Format(util.Date_Full_Layout),
  303. "isread": 0,
  304. "send_isdel": 0,
  305. "receive_isdel": 0,
  306. "iswithdraw": 0,
  307. }
  308. //系统信息处理
  309. if in.ItemType == 6 {
  310. messageMailBox = map[string]interface{}{
  311. "appid": in.Appid,
  312. "messag_id": ok,
  313. "type": in.ItemType,
  314. "create_time": nowForm.Format(util.Date_Full_Layout),
  315. "read_time": nowForm.Format(util.Date_Full_Layout),
  316. "isread": 1,
  317. "send_isdel": 0,
  318. "receive_isdel": 0,
  319. "iswithdraw": 0,
  320. }
  321. if in.OwnType == 1 {
  322. //用户接受系统信息
  323. messageMailBox["own_type"] = 2
  324. messageMailBox["send_user_type"] = 1
  325. messageMailBox["receive_user_type"] = 2
  326. messageMailBox["own_id"] = in.NewUserId
  327. messageMailBox["send_user_id"] = in.ReceiveId
  328. messageMailBox["receive_user_id"] = in.NewUserId
  329. } else if in.OwnType == 2 {
  330. //客服接受系统信息
  331. messageMailBox["own_type"] = 1
  332. messageMailBox["send_user_type"] = 2
  333. messageMailBox["receive_user_type"] = 1
  334. messageMailBox["own_id"] = in.SendId
  335. messageMailBox["send_user_id"] = in.ReceiveId
  336. messageMailBox["receive_user_id"] = in.SendId
  337. } else {
  338. //客服接受系统信息
  339. messageMailBox["own_type"] = 1
  340. messageMailBox["send_user_type"] = 2
  341. messageMailBox["receive_user_type"] = 1
  342. messageMailBox["own_id"] = in.ReceiveId
  343. messageMailBox["send_user_id"] = in.NewUserId
  344. messageMailBox["receive_user_id"] = in.ReceiveId
  345. }
  346. receiveOk = util.Mysql.InsertByTx(tx, util.SOCIALIZE_MESSAGE_MAILBOX, messageMailBox)
  347. return ok > 1 && receiveOk > 1
  348. }
  349. if in.ItemType == 4 || in.ItemType == 8 || in.ItemType == 5 {
  350. //客服或者机器人聊天
  351. if in.OwnType == 1 {
  352. // (用户发送)客服接受
  353. messageMailBox["own_type"] = 1
  354. messageMailBox["send_user_type"] = 2
  355. messageMailBox["receive_user_type"] = 1
  356. messageMailBox["own_id"] = in.ReceiveId
  357. messageMailBox["send_user_id"] = in.NewUserId
  358. messageMailBox["receive_user_id"] = in.ReceiveId
  359. userType = 1
  360. userId = in.ReceiveId
  361. } else {
  362. //客服发送(用户接收信息)
  363. messageMailBox["own_type"] = 2
  364. messageMailBox["send_user_type"] = 1
  365. messageMailBox["receive_user_type"] = 2
  366. messageMailBox["own_id"] = in.ReceiveId
  367. messageMailBox["send_user_id"] = in.SendId
  368. messageMailBox["receive_user_id"] = in.ReceiveId
  369. userId = in.ReceiveId
  370. if in.ItemType == 4 || in.ItemType == 8 {
  371. messageMailBox["receive_user_id"] = in.NewUserId
  372. userId = in.NewUserId
  373. messageMailBox["own_id"] = in.NewUserId
  374. messageMailBox["isread"] = 1
  375. messageMailBox["read_time"] = nowForm.Format(util.Date_Full_Layout)
  376. }
  377. userType = 2
  378. }
  379. } else {
  380. messageMailBox["own_type"] = 2
  381. messageMailBox["send_user_type"] = 2
  382. messageMailBox["receive_user_type"] = 2
  383. messageMailBox["own_id"] = in.ReceiveId
  384. messageMailBox["send_user_id"] = in.NewUserId
  385. messageMailBox["receive_user_id"] = in.ReceiveId
  386. userType = 2
  387. userId = in.ReceiveId
  388. }
  389. receiveOk = util.Mysql.InsertByTx(tx, util.SOCIALIZE_MESSAGE_MAILBOX, messageMailBox)
  390. messageMailBox = map[string]interface{}{
  391. "appid": in.Appid,
  392. "messag_id": ok,
  393. "type": in.ItemType,
  394. "create_time": nowForm.Format(util.Date_Full_Layout),
  395. "read_time": nowForm.Format(util.Date_Full_Layout),
  396. "isread": 1,
  397. "send_isdel": 0,
  398. "receive_isdel": 0,
  399. "iswithdraw": 0,
  400. }
  401. if in.ItemType == 4 || in.ItemType == 8 || in.ItemType == 5 {
  402. //客服或者机器人聊天
  403. if in.OwnType == 1 {
  404. //用户发送(用户接受)
  405. messageMailBox["own_type"] = 2
  406. messageMailBox["send_user_type"] = 2
  407. messageMailBox["receive_user_type"] = 1
  408. messageMailBox["own_id"] = in.NewUserId
  409. messageMailBox["send_user_id"] = in.NewUserId
  410. messageMailBox["receive_user_id"] = in.ReceiveId
  411. } else {
  412. //客服发送信息(用户接受)
  413. messageMailBox["own_type"] = 1
  414. messageMailBox["send_user_type"] = 1
  415. messageMailBox["receive_user_type"] = 2
  416. messageMailBox["own_id"] = in.SendId
  417. messageMailBox["send_user_id"] = in.SendId
  418. messageMailBox["receive_user_id"] = in.ReceiveId
  419. if in.ItemType == 4 || in.ItemType == 8 {
  420. messageMailBox["receive_user_id"] = in.NewUserId
  421. }
  422. }
  423. } else {
  424. messageMailBox["own_type"] = 2
  425. messageMailBox["send_user_type"] = 2
  426. messageMailBox["receive_user_type"] = 2
  427. messageMailBox["own_id"] = in.NewUserId
  428. messageMailBox["send_user_id"] = in.NewUserId
  429. messageMailBox["receive_user_id"] = in.ReceiveId
  430. }
  431. receiveOk = util.Mysql.InsertByTx(tx, util.SOCIALIZE_MESSAGE_MAILBOX, messageMailBox)
  432. if ok > 1 && receiveOk > 1 {
  433. pc_a, err := util.GetData(userType, userId)
  434. count := 1
  435. if err == nil && pc_a != nil {
  436. count += pc_a.Count
  437. }
  438. util.SetData(userType, userId, map[string]interface{}{"data": data, "count": count}, util.SurvivalTime)
  439. }
  440. return ok > 1 && receiveOk > 1
  441. })
  442. return fool, "", in.Content, messageId, nowForm.Unix()
  443. }
  444. // 历史信息查询
  445. func (b MessaggeService) FindMessage(in *messagecenter.MessageReq) *[]map[string]interface{} {
  446. sqlStr := ""
  447. lastStr := ""
  448. if in.LastId > 0 {
  449. if in.Sort == "asc" {
  450. lastStr = fmt.Sprintf("AND a.messag_id > %d ", in.LastId)
  451. } else {
  452. lastStr = fmt.Sprintf("AND a.messag_id < %d ", in.LastId)
  453. }
  454. }
  455. switch in.MsgType {
  456. case 2: //点对点聊天
  457. sqlStr = fmt.Sprintf("SELECT a.messag_id as messageId,b.* ,if(a.own_id = a.send_user_id,1,2) as fool "+
  458. "FROM %s a "+
  459. "LEFT JOIN %s b on a.messag_id=b.id "+
  460. "LEFT JOIN %s c on c.id=a.send_user_id "+
  461. "LEFT JOIN %s d on d.id=a.receive_user_id "+
  462. "where a.own_id= %d and a.iswithdraw = 0"+
  463. "AND ((a.send_user_id= %d AND a.receive_user_id= %d) or (a.send_user_id= %d AND a.receive_user_id= %d)) "+
  464. "AND a.type=2 %s "+
  465. "ORDER BY a.create_time desc ,a.id asc "+
  466. "limit 0 , %d ",
  467. util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_MESSAGE, util.BASE_USER, util.BASE_USER,
  468. in.NewUserId, in.NewUserId, in.SendId, in.SendId, in.NewUserId, lastStr, in.PageSize)
  469. break
  470. case 4, 5, 6, 7: //客服聊天
  471. if in.UserType == 1 {
  472. //客服聊天记录查看
  473. 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 "+
  474. "FROM %s a "+
  475. "LEFT JOIN %s b ON a.messag_id = b.id "+
  476. "LEFT JOIN %s c ON a.own_type = 1 AND a.own_id=c.id "+
  477. "WHERE a.own_type = 1 and a.iswithdraw = 0 "+
  478. "AND (a.type = 5 or a.type=4 or a.type=6 or a.type=7 or a.type=8 ) "+
  479. "AND c.ent_id = %d "+
  480. "AND c.user_id = %d %s "+
  481. "ORDER BY a.create_time desc ,a.id asc "+
  482. "limit 0 , %d ",
  483. util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_MESSAGE, util.SOCIALIZE_CHAT_SESSION,
  484. in.EntId, in.SendId, lastStr, in.PageSize)
  485. } else {
  486. //用户聊天记录查看
  487. 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 "+
  488. "FROM %s a "+
  489. "LEFT JOIN %s b ON a.messag_id = b.id "+
  490. "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 "+
  491. "LEFT JOIN %s d on c.ent_id=d.ent_id "+
  492. "LEFT JOIN %s e on e.messag_id=b.id "+
  493. "WHERE a.own_type = 2 and a.iswithdraw = 0 "+
  494. "AND a.own_id = %d "+
  495. "AND c.ent_id = %d "+
  496. "AND c.user_id = %d "+
  497. "AND ( a.type = 4 OR a.type = 5 or a.type=6 or a.type=7 or a.type=8) %s "+
  498. "ORDER BY a.create_time desc ,a.id asc "+
  499. "limit 0 , %d ",
  500. util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_MESSAGE, util.SOCIALIZE_CHAT_SESSION, in.SendId, in.NewUserId, util.SOCIALIZE_TENANT_ROBOT, util.SOCIALIZE_APPRAISE,
  501. in.NewUserId, in.SendId, in.NewUserId, lastStr, in.PageSize)
  502. }
  503. break
  504. }
  505. log.Println(sqlStr)
  506. data := util.Mysql.SelectBySql(sqlStr)
  507. //自己头像处理
  508. if in.UserType == 2 {
  509. userData := util.Mysql.FindOne(util.BASE_USER, map[string]interface{}{"id": in.NewUserId}, "headimg", "")
  510. if userData != nil {
  511. for key := range *data {
  512. (*data)[key]["ownImg"] = (*userData)["headimg"]
  513. }
  514. }
  515. }
  516. go func() {
  517. updateMap := map[string]interface{}{}
  518. if len(*data) > 0 && data != nil {
  519. //if true {
  520. //未读信息修改
  521. switch in.MsgType {
  522. case 2: //点对点聊天
  523. updateMap = map[string]interface{}{
  524. "own_type": 2,
  525. "own_id": in.NewUserId,
  526. "type": 2,
  527. "isread": 0,
  528. }
  529. util.Mysql.Update(util.SOCIALIZE_MESSAGE_MAILBOX, updateMap, map[string]interface{}{"isread": 1, "read_time": time.Now().Local().Format(util.Date_Full_Layout)})
  530. break
  531. case 4, 5:
  532. sqlStr := ""
  533. if in.UserType == 1 {
  534. sqlStr = fmt.Sprintf("UPDATE %s a SET a.isread = 1, a.read_time = now( ) "+
  535. "WHERE a.own_type = 1 and a.iswithdraw = 0 "+
  536. "AND a.type IN ( 4,5,6,7) "+
  537. "AND a.isread = 0 "+
  538. "AND a.own_id IN ( SELECT b.id FROM %s b WHERE b.customer_service_id=%d AND b.user_id=%d )",
  539. util.SOCIALIZE_MESSAGE_MAILBOX, util.SOCIALIZE_CHAT_SESSION, in.EntUserId, in.SendId)
  540. } else {
  541. sqlStr = fmt.Sprintf("UPDATE %s a SET a.isread = 1, a.read_time = now( ) "+
  542. "WHERE a.own_type = 2 and a.iswithdraw = 0 "+
  543. "AND a.type IN ( 4,5,6,7 ) "+
  544. "AND a.isread = 0 "+
  545. "AND a.own_id =%d ", util.SOCIALIZE_MESSAGE_MAILBOX, in.NewUserId)
  546. }
  547. util.Mysql.UpdateOrDeleteBySql(sqlStr)
  548. break
  549. }
  550. //redis缓存处理
  551. b.Count(in.NewUserId, in.UserType, in.EntUserId, true)
  552. }
  553. }()
  554. return data
  555. }
  556. // 创建会话
  557. func (b MessaggeService) CreateChatSession(in *messagecenter.ChatSessionReq) (fool bool, sessionId int64) {
  558. fool = util.Mysql.ExecTx("会话新建", func(tx *sql.Tx) bool {
  559. customerserviceName := in.CustomerserviceName
  560. if in.CustomerServiceId != 0 {
  561. sqlStr := fmt.Sprintf("select customer_service_name from %s "+
  562. "where ent_id= %d "+
  563. "AND customer_service_id= %d ",
  564. util.SOCIALIZE_CHAT_SESSION, in.EntId, in.CustomerServiceId)
  565. customerList := util.Mysql.SelectBySql(sqlStr)
  566. if len(*customerList) > 0 {
  567. customerserviceName = quitl.InterfaceToStr((*customerList)[0]["customer_service_name"])
  568. }
  569. }
  570. //查询企业是否存在
  571. count := util.Mysql.Count(util.SOCIALIZE_TENANT_ROBOT, map[string]interface{}{
  572. "ent_id": in.EntId,
  573. })
  574. if count < 1 {
  575. return false
  576. }
  577. chatMession := map[string]interface{}{
  578. "handle_status": 0,
  579. "start_time": time.Now().Local().Format(util.Date_Full_Layout),
  580. "appid": in.AppId,
  581. "ent_id": in.EntId,
  582. "customer_service_id": in.CustomerServiceId,
  583. "user_id": in.UserId,
  584. "customer_service_name": customerserviceName,
  585. }
  586. sessionId = util.Mysql.InsertByTx(tx, util.SOCIALIZE_CHAT_SESSION, chatMession)
  587. return sessionId > 0
  588. })
  589. return
  590. }
  591. // 结束会话
  592. func (b MessaggeService) CloseChatSession(in *messagecenter.CloseSessionReq) bool {
  593. fool := util.Mysql.ExecTx("关闭会话", func(tx *sql.Tx) bool {
  594. updateMap := map[string]interface{}{
  595. "id": in.SessionId,
  596. }
  597. fool := util.Mysql.Update(util.SOCIALIZE_CHAT_SESSION, updateMap, map[string]interface{}{"start_time": time.Now().Local().Format(util.Date_Full_Layout)})
  598. return fool
  599. })
  600. return fool
  601. }
  602. // 创建会话并保存信息
  603. func (b *MessaggeService) SaveAutoReplyMsg(userType, entId, entUserId, userId int64, content, appId, nowFormat string) (bool, int64) {
  604. messageId := int64(0)
  605. return util.Mysql.ExecTx("保存自动回复消息", func(tx *sql.Tx) bool {
  606. entUserName := ""
  607. if entUserId > 0 {
  608. list := util.Mysql.SelectBySql(`select ? from socialize_tenant_seat where appid=? AND ent_id=? AND customer_service_id=?`, util.SOCIALIZE_CHAT_SESSION, appId, entId, entUserId)
  609. if list != nil && len(*list) > 0 {
  610. entUserName, _ = (*list)[0]["customer_service_name"].(string)
  611. }
  612. }
  613. messageId = util.Mysql.InsertBySqlByTx(tx, `insert into socialize_message (appid,content,item,type,create_time,create_person) values (?,?,?,?,?,?)`, appId, content, 8, 1, nowFormat, "admin")
  614. sessionId := util.Mysql.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)
  615. ok := false
  616. if userType == 0 {
  617. ok1 := util.Mysql.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
  618. ok2 := util.Mysql.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
  619. ok = ok1 && ok2
  620. } else if userType == 1 {
  621. ok = util.Mysql.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
  622. } else if userType == 2 {
  623. ok = util.Mysql.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
  624. }
  625. return messageId > 0 && sessionId > 0 && ok
  626. }), messageId
  627. }
  628. // 修改未读状态
  629. func (b MessaggeService) UpdateReadById(in *messagecenter.ReadStateReq) bool {
  630. updateMap := map[string]interface{}{
  631. "messag_id": in.MessageId,
  632. "isread": 0,
  633. }
  634. if util.Mysql.Count(util.SOCIALIZE_MESSAGE_MAILBOX, updateMap) > 0 {
  635. fool := util.Mysql.ExecTx("已读状态修改", func(tx *sql.Tx) bool {
  636. fool := util.Mysql.Update(util.SOCIALIZE_MESSAGE_MAILBOX, updateMap, map[string]interface{}{"read_time": time.Now().Local().Format(util.Date_Full_Layout), "isread": 1})
  637. if fool {
  638. //查询此条信息拥有者
  639. data := util.Mysql.FindOne(util.SOCIALIZE_MESSAGE_MAILBOX, updateMap, "receive_user_type", "")
  640. if data != nil {
  641. userType := int64(1)
  642. userId := int64(0)
  643. if (*data)["receive_user_type"] == 2 {
  644. userType = 2
  645. userId = in.EntUserId
  646. } else {
  647. userType = 1
  648. userId = in.NewUserId
  649. }
  650. pc_a, err := util.GetData(userType, userId)
  651. if fool {
  652. if err == nil && pc_a != nil {
  653. if pc_a.Count >= 1 {
  654. //id一致
  655. if in.MessageId == pc_a.Data["id"] {
  656. util.SetData(userType, userId, map[string]interface{}{"data": map[string]interface{}{}, "count": pc_a.Count - 1}, util.SurvivalTime)
  657. } else {
  658. util.SetData(userType, userId, map[string]interface{}{"data": data, "count": pc_a.Count - 1}, util.SurvivalTime)
  659. }
  660. }
  661. }
  662. }
  663. }
  664. }
  665. return fool
  666. })
  667. return fool
  668. }
  669. return true
  670. }
  671. // WithdrawMessage 撤回消息
  672. func (b MessaggeService) WithdrawMessage(in *messagecenter.ReadWithdrawReq) bool {
  673. messageId := encrypt.SE.Decode4Hex(in.MessageId)
  674. newUserId, entUserId := NewEndId(quitl.Int64All(messageId), in.UserType)
  675. msg := util.Mysql.FindOne(util.SOCIALIZE_MESSAGE, map[string]interface{}{"id": messageId}, "create_time", "")
  676. if msg == nil || len(*msg) <= 0 {
  677. log.Println("查询消息id失败")
  678. return false
  679. }
  680. createTime, _ := time.Parse(util.Date_Full_Layout, quitl.InterfaceToStr((*msg)["create_time"]))
  681. if createTime.Unix()+60*2 < time.Now().Unix() {
  682. log.Println("消息已超过2分钟,撤回失败")
  683. return false
  684. }
  685. nowForm := time.Now().Local()
  686. m := util.Mysql.Update(util.SOCIALIZE_MESSAGE_MAILBOX,
  687. map[string]interface{}{"messag_id": messageId}, map[string]interface{}{"iswithdraw": 1, "withdraw_time": nowForm.Format(util.Date_Full_Layout)})
  688. if m {
  689. //消息撤回 更新对方私信
  690. in.UserType = quitl.Int64All(quitl.If(in.UserType == 1, 2, 1))
  691. b.Count(newUserId, in.UserType, entUserId, true)
  692. }
  693. return m
  694. }
  695. // AppraiseMessage 消息评价
  696. func (b MessaggeService) AppraiseMessage(in *messagecenter.AppraiseReq) error {
  697. messageId := encrypt.SE.Decode4Hex(in.MessageId)
  698. //查询此条消息是否是当前用户的
  699. if util.Mysql.Count(util.SOCIALIZE_MESSAGE_MAILBOX, map[string]interface{}{
  700. "messag_id": messageId,
  701. "receive_user_id": in.NewUserId,
  702. "receive_user_type": 2,
  703. "type": 8,
  704. }) == 0 {
  705. return fmt.Errorf("未查询到信息")
  706. }
  707. if util.Mysql.Count(util.SOCIALIZE_APPRAISE, map[string]interface{}{
  708. "appid": in.Appid,
  709. "messag_id": messageId,
  710. }) > 0 {
  711. return fmt.Errorf("请勿重复评价")
  712. }
  713. //插入评价
  714. if util.Mysql.Insert(util.SOCIALIZE_APPRAISE, map[string]interface{}{
  715. "appid": in.Appid,
  716. "messag_id": messageId,
  717. "create_time": time.Now().Local().Format(util.Date_Full_Layout),
  718. "appraise": in.Appraise,
  719. }) > 0 {
  720. return nil
  721. }
  722. return fmt.Errorf("评价消息异常")
  723. }
  724. // NewEndId 消息撤回 获取对方userid
  725. func NewEndId(messageId, iType int64) (newUserId, entUserId int64) {
  726. data := util.Mysql.FindOne(util.SOCIALIZE_MESSAGE_MAILBOX, map[string]interface{}{"messag_id": messageId, "own_type": iType}, "", "")
  727. if data != nil && len(*data) > 0 {
  728. if iType == 1 { //客服撤回消息 获取客服id与用户id
  729. entUserId = quitl.Int64All((*data)["send_user_id"])
  730. newUserId = quitl.Int64All((*data)["receive_user_id"])
  731. } else {
  732. //用户撤回消息 获取客服id与用户id
  733. newUserId = quitl.Int64All((*data)["send_user_id"])
  734. entUserId = quitl.Int64All((*data)["receive_user_id"])
  735. }
  736. }
  737. return
  738. }