平安校园
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

185 lines
7.4 KiB

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