message_mail_box.go 53 KB

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