message_mail_box.go 48 KB

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