message_mail_box.go 53 KB

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