平安校园
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

MessageService.cs 7.4 KiB

vor 4 Monaten
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. 
  2. //
  3. namespace SafeCampus.System;
  4. /// <summary>
  5. /// <inheritdoc cref="IMessageService"/>
  6. /// </summary>
  7. public class MessageService : DbRepository<SysMessage>, IMessageService
  8. {
  9. private readonly ILogger<MessageService> _logger;
  10. private readonly ISimpleCacheService _simpleCacheService;
  11. private readonly IRelationService _relationService;
  12. private readonly IEventPublisher _eventPublisher;
  13. public MessageService(ILogger<MessageService> logger, ISimpleCacheService simpleCacheService, IRelationService relationService,
  14. IEventPublisher eventPublisher)
  15. {
  16. _logger = logger;
  17. _simpleCacheService = simpleCacheService;
  18. _relationService = relationService;
  19. _eventPublisher = eventPublisher;
  20. }
  21. /// <inheritdoc />
  22. public async Task<SqlSugarPagedList<SysMessage>> Page(MessagePageInput input)
  23. {
  24. var query = Context.Queryable<SysMessage>().WhereIF(!string.IsNullOrEmpty(input.Category), it => it.Category == input.Category)//根据分类查询
  25. .WhereIF(!string.IsNullOrEmpty(input.SearchKey),
  26. it => it.Subject.Contains(input.SearchKey) || it.Content.Contains(input.SearchKey))//根据关键字查询
  27. .OrderByIF(!string.IsNullOrEmpty(input.SortField), $"{input.SortField} {input.SortOrder}")//排序
  28. .OrderBy(it => it.CreateTime, OrderByType.Desc);
  29. var pageInfo = await query.ToPagedListAsync(input.PageNum, input.PageSize);//分页
  30. return pageInfo;
  31. }
  32. /// <inheritdoc />
  33. public async Task<SqlSugarPagedList<SysMessage>> MyMessagePage(MessagePageInput input, long userId)
  34. {
  35. var query = Context.Queryable<SysMessageUser>().LeftJoin<SysMessage>((u, m) => u.MessageId == m.Id)
  36. .Where((u, m) => u.IsDelete == false && u.UserId == userId)
  37. .WhereIF(!string.IsNullOrEmpty(input.Category), (u, m) => m.Category == input.Category)//根据分类查询
  38. .OrderBy((u, m) => u.Read, OrderByType.Asc).OrderBy((u, m) => m.CreateTime, OrderByType.Desc).Select((u, m) => new SysMessage
  39. {
  40. Id = m.Id.SelectAll(),
  41. Read = u.Read
  42. });
  43. var pageInfo = await query.ToPagedListAsync(input.PageNum, input.PageSize);//分页
  44. return pageInfo;
  45. }
  46. /// <inheritdoc />
  47. public async Task Send(MessageSendInput input)
  48. {
  49. var message = input.Adapt<SysMessage>();//实体转换
  50. var messageUsers = new List<SysMessageUser>();
  51. input.ReceiverIdList.ForEach(it =>
  52. {
  53. //遍历用户ID列表,生成拓展列表
  54. messageUsers.Add(new SysMessageUser { UserId = it, Read = false, IsDelete = false });
  55. });
  56. //事务
  57. var result = await Tenant.UseTranAsync(async () =>
  58. {
  59. message = await InsertReturnEntityAsync(message);//添加消息
  60. messageUsers.ForEach(it => it.MessageId = message.Id);//添加关系
  61. await Context.Insertable(messageUsers).ExecuteCommandAsync();
  62. });
  63. if (result.IsSuccess)//如果成功了
  64. {
  65. await _eventPublisher.PublishAsync(EventSubscriberConst.NEW_MESSAGE, new NewMessageEvent
  66. {
  67. UserIds = input.ReceiverIdList.Select(it => it.ToString()).ToList(),
  68. Message = input.Subject
  69. });//通知用户有新的消息
  70. }
  71. else
  72. {
  73. //写日志
  74. _logger.LogError(result.ErrorMessage, result.ErrorException);
  75. throw Oops.Oh(ErrorCodeEnum.A0003);
  76. }
  77. }
  78. /// <inheritdoc />
  79. public async Task<MessageDetailOutPut> Detail(BaseIdInput input, bool isSelf = false)
  80. {
  81. //获取消息
  82. var message = await GetFirstAsync(it => it.Id == input.Id);
  83. if (message != null)
  84. {
  85. var messageDetail = message.Adapt<MessageDetailOutPut>();//实体转换
  86. var messageUserRep = ChangeRepository<DbRepository<SysMessageUser>>();//切换仓储
  87. var messageUsers = await messageUserRep.GetListAsync(it => it.MessageId == message.Id);
  88. var myMessage = messageUsers.Where(it => it.UserId == UserManager.UserId && it.MessageId == input.Id).FirstOrDefault();//查询是否发给自己
  89. if (myMessage != null)
  90. {
  91. myMessage.Read = true;//设置已读
  92. await messageUserRep.UpdateAsync(myMessage);//修改状态
  93. }
  94. if (!isSelf)//如果不是自己则把所有的用户都列出来
  95. {
  96. var userIds = messageUsers.Select(it => it.UserId).ToList();//获取用户ID列表
  97. var userInfos = await Context.Queryable<SysUser>().Where(it => userIds.Contains(it.Id)).Select(it => new { it.Id, it.Name })
  98. .ToListAsync();//获取用户姓名信息列表
  99. //遍历关系
  100. messageUsers.ForEach(messageUser =>
  101. {
  102. var user = userInfos.Where(u => u.Id == messageUser.UserId).FirstOrDefault();//获取用户信息
  103. if (user != null)
  104. {
  105. //添加到已读列表
  106. messageDetail.ReceiveInfoList.Add(new MessageDetailOutPut.ReceiveInfo
  107. {
  108. ReceiveUserId = user.Id,
  109. ReceiveUserName = user.Name,
  110. Read = messageUser.Read
  111. });
  112. }
  113. else//用户ID没找到
  114. {
  115. //添加到已读列表
  116. messageDetail.ReceiveInfoList.Add(new MessageDetailOutPut.ReceiveInfo
  117. {
  118. ReceiveUserId = messageUser.UserId,
  119. ReceiveUserName = "未知用户",
  120. Read = messageUser.Read
  121. });
  122. }
  123. });
  124. }
  125. return messageDetail;
  126. }
  127. return null;
  128. }
  129. /// <inheritdoc />
  130. public async Task Delete(BaseIdListInput input)
  131. {
  132. //获取所有ID
  133. var ids = input.Ids;
  134. if (ids.Count > 0)
  135. {
  136. //事务
  137. var result = await Tenant.UseTranAsync(async () =>
  138. {
  139. await DeleteAsync(it => ids.Contains(it.Id));
  140. await Context.Deleteable<SysMessageUser>().Where(it => ids.Contains(it.MessageId)).ExecuteCommandAsync();
  141. });
  142. if (!result.IsSuccess)//如果失败了
  143. {
  144. //写日志
  145. _logger.LogError(result.ErrorMessage, result.ErrorException);
  146. throw Oops.Oh(ErrorCodeEnum.A0002);
  147. }
  148. }
  149. }
  150. /// <inheritdoc />
  151. public async Task DeleteMyMessage(BaseIdInput input, long userId)
  152. {
  153. var messageUserRep = ChangeRepository<DbRepository<SysMessageUser>>();//切换仓储
  154. await Context.Deleteable<SysMessageUser>().Where(it => it.UserId == userId && it.MessageId == input.Id).IsLogic().ExecuteCommandAsync();//逻辑删除
  155. }
  156. /// <inheritdoc />
  157. public async Task<int> UnReadCount(long userId)
  158. {
  159. var messageUserRep = ChangeRepository<DbRepository<SysMessageUser>>();//切换仓储
  160. //获取未读数量
  161. var unRead = await messageUserRep.CountAsync(it => it.UserId == userId && it.Read == false && it.IsDelete == false);
  162. return unRead;
  163. }
  164. }