message_mail_box.go 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  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 = 2 AND a.own_id = %d "+
  669. "AND a.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.PositionId,
  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.user_id in (%s) "+
  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, positionStr, util.SOCIALIZE_TENANT_ROBOT,
  707. util.SOCIALIZE_APPRAISE, positionStr, 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 in.ItemType == 9 {
  1014. in.ItemType = 6
  1015. }
  1016. //群聊
  1017. if isGroup {
  1018. //修改类型为群聊
  1019. if in.ItemType != 6 {
  1020. in.ItemType = 3
  1021. }
  1022. 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"}
  1023. for _, v := range in.GroupIds {
  1024. args := []interface{}{}
  1025. args = append(args, in.Appid, messageId, in.ItemType, in.SendId, 2, in.SendId, 2, 2, in.SendId, nowTime, v, 1)
  1026. groupUser := GetUserByGroupId(tx, v, in.SendId)
  1027. for _, vv := range groupUser {
  1028. log.Println("获取到群组下员工:", vv)
  1029. args = append(args, in.Appid, messageId, in.ItemType, in.SendId, 2, vv, 2, 2, vv, nowTime, v, 0)
  1030. }
  1031. MessageMailBoxAdd(tx, fieids, args)
  1032. //最后一次聊天
  1033. SocializeSummaryAddOrUpdate(tx, v, 0, 0, messageId, isCustomerServiceAccess, nowTime)
  1034. //更新未读消息
  1035. GroupUserUnReadUpdate(tx, groupUser)
  1036. }
  1037. }
  1038. //1v1
  1039. if isOneToOne {
  1040. //修改类型为个人
  1041. if in.ItemType != 6 {
  1042. in.ItemType = 2
  1043. }
  1044. 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"}
  1045. args := []interface{}{}
  1046. args = append(args, in.Appid, messageId, in.ItemType, in.SendId, 2, in.SendId, 2, 2, in.SendId, nowTime, 1)
  1047. for _, v := range in.ReceiverIds {
  1048. args = append(args, in.Appid, messageId, in.ItemType, in.SendId, 2, v, 2, 2, v, nowTime, 0)
  1049. //最后一次聊天
  1050. SocializeSummaryAddOrUpdate(tx, 0, in.SendId, v, messageId, isCustomerServiceAccess, nowTime)
  1051. SocializeSummaryAddOrUpdate(tx, 0, v, in.SendId, messageId, isCustomerServiceAccess, nowTime)
  1052. }
  1053. MessageMailBoxAdd(tx, fieids, args)
  1054. }
  1055. return true
  1056. })
  1057. return fool, "", in.Content, messageId, now.Unix()
  1058. }
  1059. // 消息存储
  1060. func MessageAdd(tx *sql.Tx, appid, title, content, createperson, link string, item, messageType int64) int64 {
  1061. nowTime := time.Now()
  1062. message := map[string]interface{}{
  1063. "appid": appid,
  1064. "title": title,
  1065. "content": content,
  1066. "item": item,
  1067. "type": messageType,
  1068. "link": link,
  1069. "create_time": nowTime.Format(date.Date_Full_Layout),
  1070. "create_person": createperson, //系统消息时,创建人是群聊id或接收人id
  1071. }
  1072. return IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_MESSAGE, message)
  1073. }
  1074. // 消息信息箱存储
  1075. // types 2:点对点 3:群消息
  1076. func MessageMailBoxAdd(tx *sql.Tx, fieids []string, args []interface{}) (int64, int64) {
  1077. length, lastId := IC.BaseMysql.InsertBatchByTx(tx, util.SOCIALIZE_MESSAGE_MAILBOX, fieids, args)
  1078. log.Println("MessageMailBoxAdd length:", length, "MessageMailBoxAdd lastId:", lastId)
  1079. return length, lastId
  1080. }
  1081. // 获取除发送人以外的群成员
  1082. func GetUserByGroupId(tx *sql.Tx, groupId, sendId int64) []int64 {
  1083. arr := []int64{}
  1084. 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)
  1085. if data == nil || len(*data) <= 0 {
  1086. return arr
  1087. }
  1088. for _, v := range *data {
  1089. position_id := quitl.Int64All(v["position_id"])
  1090. if position_id == 0 {
  1091. continue
  1092. }
  1093. arr = append(arr, position_id)
  1094. }
  1095. return arr
  1096. }
  1097. // 最后一次聊天存储
  1098. func SocializeSummaryAddOrUpdate(tx *sql.Tx, groupId, myPositionId, yourPositionId, messageId int64, isCustomerServiceAccess int, timestamp string) bool {
  1099. //判断是否存在
  1100. if groupId > 0 {
  1101. if IC.BaseMysql.CountBySql(fmt.Sprintf(`select count(1) from %s where chat_group_id =?`, util.SOCIALIZE_SUMMARY), groupId) > 0 {
  1102. //存在更新
  1103. return IC.BaseMysql.UpdateByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
  1104. "chat_group_id": groupId,
  1105. }, map[string]interface{}{
  1106. "message_id": messageId,
  1107. "timestamp": timestamp,
  1108. })
  1109. } else {
  1110. //新增
  1111. return IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
  1112. "chat_group_id": groupId,
  1113. "message_id": messageId,
  1114. "timestamp": timestamp,
  1115. }) > 0
  1116. }
  1117. }
  1118. if yourPositionId > 0 {
  1119. ok_my := true
  1120. ok_your := true
  1121. //发送方
  1122. 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 {
  1123. //存在更新
  1124. ok_my = IC.BaseMysql.UpdateByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
  1125. "my_position_id": myPositionId,
  1126. "your_position_id": yourPositionId,
  1127. }, map[string]interface{}{
  1128. "message_id": messageId,
  1129. "timestamp": timestamp,
  1130. })
  1131. } else {
  1132. //新增
  1133. ok_my = IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
  1134. "my_position_id": myPositionId,
  1135. "your_position_id": yourPositionId,
  1136. "message_id": messageId,
  1137. "timestamp": timestamp,
  1138. "unread": 0,
  1139. "customer_service_access": isCustomerServiceAccess,
  1140. }) > 0
  1141. }
  1142. //接收方
  1143. 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 {
  1144. //存在更新
  1145. ok_your = IC.BaseMysql.UpdateByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
  1146. "my_position_id": yourPositionId,
  1147. "your_position_id": myPositionId,
  1148. }, map[string]interface{}{
  1149. "message_id": messageId,
  1150. "timestamp": timestamp,
  1151. "unread": 1,
  1152. })
  1153. } else {
  1154. //新增
  1155. ok_your = IC.BaseMysql.InsertByTx(tx, util.SOCIALIZE_SUMMARY, map[string]interface{}{
  1156. "my_position_id": yourPositionId,
  1157. "your_position_id": myPositionId,
  1158. "message_id": messageId,
  1159. "timestamp": timestamp,
  1160. "unread": 1,
  1161. "customer_service_access": isCustomerServiceAccess,
  1162. }) > 0
  1163. }
  1164. return ok_my && ok_your
  1165. }
  1166. return true
  1167. }
  1168. // 群组人员未读消息更新
  1169. func GroupUserUnReadUpdate(tx *sql.Tx, ids []int64) bool {
  1170. whs := []string{}
  1171. for i := 0; i < len(ids); i++ {
  1172. whs = append(whs, "?")
  1173. }
  1174. wh := strings.Join(whs, ",")
  1175. interfaces := gconv.Interfaces(ids)
  1176. count := IC.BaseMysql.UpdateOrDeleteBySql(`UPDATE `+util.SOCIALIZE_CHAT_GROUP_PERSON+` SET unread = unread + 1 WHERE id in (`+wh+`)`, interfaces...)
  1177. if count > 0 {
  1178. return true
  1179. }
  1180. return true
  1181. }
  1182. // GetUserAllPosition 用户下所有职位id
  1183. func GetUserAllPosition(baseUserId int64) (positionStr string) {
  1184. //查询用户所有的职位id
  1185. sqlPosition := fmt.Sprintf("SELECT id FROM %s WHERE user_id = %d", util.BASE_POSITION, baseUserId)
  1186. positionArr := IC.BaseMysql.SelectBySql(sqlPosition)
  1187. if positionArr != nil && len(*positionArr) > 0 {
  1188. for k, val := range *positionArr {
  1189. if k < len(*positionArr)-1 {
  1190. positionStr += strconv.Itoa(quitl.IntAll(val["id"])) + ","
  1191. } else {
  1192. positionStr += strconv.Itoa(quitl.IntAll(val["id"]))
  1193. }
  1194. }
  1195. }
  1196. return positionStr
  1197. }