NoticeRepository.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. using System.Transactions;
  5. using AutoMapper;
  6. using Dapper;
  7. using GxPress.Common.AppOptions;
  8. using GxPress.Common.Exceptions;
  9. using GxPress.Common.Page;
  10. using GxPress.Common.Tools;
  11. using GxPress.Entity;
  12. using GxPress.Entity.Middle;
  13. using GxPress.EnumConst;
  14. using GxPress.Repository.Interface;
  15. using GxPress.Request.Notice;
  16. using GxPress.Result.Notice;
  17. using Microsoft.Extensions.Options;
  18. using Datory;
  19. using SqlKata;
  20. using GxPress.Result.Job;
  21. using System.Linq;
  22. namespace GxPress.Repository.Implement
  23. {
  24. public class NoticeRepository : INoticeRepository
  25. {
  26. private readonly Repository<Notice> _repository;
  27. private readonly Repository<Addressee> _noticeAddresseeRepository;
  28. private readonly Repository<Cc> _noticeCcRepository;
  29. private readonly Repository<User> _userRepository;
  30. private readonly Repository<Middle> _middleRepository;
  31. private readonly Repository<Entity.AdminVerify> _adminVerifyRepository;
  32. private readonly IMapper _mapper;
  33. private readonly string _connectionString;
  34. private readonly string _databaseTypeStr;
  35. public NoticeRepository(IOptionsMonitor<DatabaseOptions> dbOptionsAccessor, IMapper mapper)
  36. {
  37. _databaseTypeStr = dbOptionsAccessor.CurrentValue.DatabaseType;
  38. _connectionString = dbOptionsAccessor.CurrentValue.ConnectionString;
  39. var databaseType =
  40. StringUtils.ToEnum<DatabaseType>(dbOptionsAccessor.CurrentValue.DatabaseType, DatabaseType.MySql);
  41. var database = new Database(databaseType, dbOptionsAccessor.CurrentValue.ConnectionString);
  42. _repository = new Repository<Notice>(database);
  43. _noticeAddresseeRepository = new Repository<Addressee>(database);
  44. _noticeCcRepository = new Repository<Cc>(database);
  45. _userRepository = new Repository<User>(database);
  46. _middleRepository = new Repository<Middle>(database);
  47. _adminVerifyRepository = new Repository<Entity.AdminVerify>(database);
  48. _mapper = mapper;
  49. }
  50. public IDatabase Database => _repository.Database;
  51. public string TableName => _repository.TableName;
  52. public List<TableColumn> TableColumns => _repository.TableColumns;
  53. public async Task<Notice> GetAsync(int id)
  54. {
  55. return await _repository.GetAsync(id);
  56. }
  57. public async Task<Notice> GetAsync(SqlKata.Query query)
  58. {
  59. return await _repository.GetAsync(query);
  60. }
  61. /// <summary>
  62. /// 添加通知
  63. /// </summary>
  64. /// <param name="request"></param>
  65. /// <returns></returns>
  66. public async Task<int> InsertAsync(NoticeInRequest request)
  67. {
  68. var noticeId = 0;
  69. try
  70. {
  71. using (TransactionScope transactionScope = new TransactionScope())
  72. {
  73. var userEntity = await _userRepository.GetAsync(request.UserId);
  74. if (userEntity == null)
  75. throw new BusinessException("用户不存在");
  76. //通知
  77. var notice = new Notice
  78. {
  79. NoticeType = request.NoticeType.GetHashCode() == 0 ? NoticeTypeConst.Send : request.NoticeType,
  80. UserId = request.UserId,
  81. Content = request.Content,
  82. Title = request.Title,
  83. UserName = userEntity.Name,
  84. HtmlContent = request.HtmlContent,
  85. SourceId = request.SoureId,
  86. IsDelete = false,
  87. IsTop = true
  88. };
  89. noticeId = await _repository.InsertAsync(notice);
  90. transactionScope.Complete();
  91. }
  92. }
  93. catch (Exception e)
  94. {
  95. throw new BusinessException(e.Message);
  96. }
  97. return noticeId;
  98. }
  99. /// <summary>
  100. /// 根据用户ID查询
  101. /// </summary>
  102. /// <param name="request"></param>
  103. /// <returns></returns>
  104. public async Task<PagedList<Notice>> GetNoticeByUserIdAsync(NoticePageSearchRequest request)
  105. {
  106. var query = Q.NewQuery();
  107. if (request.UserId > 0)
  108. {
  109. query.Where(nameof(Addressee.UserId), request.UserId);
  110. }
  111. if (request.SearchType == 0)
  112. {
  113. query.Where(nameof(Addressee.UserId), request.UserId);
  114. }
  115. if (request.SearchType == 1)
  116. {
  117. query.Where(nameof(Addressee.IsAdmin), true);
  118. }
  119. if (request.SearchType == 2)
  120. {
  121. query.Where(nameof(Addressee.NoticeAddresseeType), NoticeTypeConst.Draft);
  122. }
  123. if (request.SearchType == 3)
  124. {
  125. query.Where(nameof(Addressee.IsDelete), true);
  126. }
  127. if (!string.IsNullOrEmpty(request.Keyword))
  128. {
  129. var like = $"%{request.Keyword}%";
  130. query.WhereLike(nameof(Notice.Title), like);
  131. }
  132. var pagedList = new PagedList<Notice>
  133. {
  134. Total = await _repository.CountAsync(query)
  135. };
  136. var list = await _repository.GetAllAsync(query.ForPage(request.Page, request.PerPage));
  137. pagedList.Items = list;
  138. return pagedList;
  139. }
  140. /// <summary>
  141. /// admin根据用户ID查询
  142. /// </summary>
  143. /// <param name="request"></param>
  144. /// <returns></returns>
  145. public async Task<PagedList<NoticeListPageResult>> GetAdminNoticeByUserIdAsync(NoticePageSearchRequest request)
  146. {
  147. //用户收件人
  148. var noticeQuery = Q.NewQuery();
  149. if (request.SearchType == 2)
  150. {
  151. noticeQuery.Where(nameof(Notice.NoticeType), NoticeTypeConst.Draft);
  152. }
  153. noticeQuery.Where(nameof(Notice.IsDelete), request.SearchType == 3);
  154. if (!string.IsNullOrEmpty(request.Keyword))
  155. {
  156. noticeQuery.WhereLike(nameof(Notice.Title), $"%{request.Keyword}%");
  157. }
  158. var noticeList = await _repository.GetAllAsync(noticeQuery);
  159. var result = new PagedList<NoticeListPageResult>();
  160. result.Total = await _repository.CountAsync(noticeQuery);
  161. var notices = await _repository.GetAllAsync(noticeQuery.OrderByDesc(nameof(Notice.CreatedDate)).ForPage(request.Page, request.PerPage));
  162. var noticeListPageResults = new List<NoticeListPageResult>();
  163. foreach (var notice in notices)
  164. {
  165. var noticeListPageResultEntity = _mapper.Map<NoticeListPageResult>(notice);
  166. var user = await _userRepository.GetAsync(notice.UserId);
  167. if (user != null)
  168. {
  169. noticeListPageResultEntity.AvatarUrl = StringUtils.AddDomain(user.AvatarUrl);
  170. }
  171. //阅读数量
  172. noticeListPageResultEntity.ReadCount = await _noticeAddresseeRepository.CountAsync(
  173. Q.Where(nameof(Addressee.SourceId), notice.Id)
  174. .Where(nameof(Addressee.IsRead), true).Where(nameof(Addressee.IsAdmin), false));
  175. //收件人数量
  176. noticeListPageResultEntity.AllCount = await _noticeAddresseeRepository.CountAsync(
  177. Q.Where(nameof(Addressee.SourceId), notice.Id)
  178. .Where(nameof(Addressee.IsAdmin), false));
  179. noticeListPageResults.Add(noticeListPageResultEntity);
  180. }
  181. result.Items = noticeListPageResults;
  182. return result;
  183. }
  184. /// <summary>
  185. /// 管理员删除
  186. /// </summary>
  187. /// <param name="id"></param>
  188. /// <returns></returns>
  189. public async Task<bool> AdminDeleteAsync(int id)
  190. {
  191. try
  192. {
  193. var notice = await _repository.GetAsync(id);
  194. if (notice == null)
  195. throw new BusinessException("通知不存在");
  196. using (TransactionScope transactionScope = new TransactionScope())
  197. {
  198. //通知
  199. await _repository.DeleteAsync(id);
  200. //抄送
  201. await _noticeCcRepository.DeleteAsync(Q.Where(nameof(Cc.SourceId), id));
  202. //收件人
  203. await _noticeAddresseeRepository.DeleteAsync(Q.Where(nameof(Addressee.SourceId), id));
  204. transactionScope.Complete();
  205. }
  206. }
  207. catch (Exception e)
  208. {
  209. throw new BusinessException(e.Message);
  210. }
  211. return true;
  212. }
  213. /// <summary>
  214. /// 自己删除
  215. /// </summary>
  216. /// <param name="request"></param>
  217. /// <returns></returns>
  218. public async Task<bool> DeleteAsync(NoticeDeRequest request)
  219. {
  220. try
  221. {
  222. using (TransactionScope transactionScope = new TransactionScope())
  223. {
  224. //var notice = await _repository.GetAsync(request.NoticeId);
  225. //if (notice == null)
  226. // throw new BusinessException("通知不存在");
  227. //notice.IsDelete = true;
  228. //await _repository.UpdateAsync(notice);
  229. //
  230. await _noticeAddresseeRepository.UpdateAsync(Q.Set(nameof(Addressee.IsDelete), true)
  231. .WhereIn(nameof(Addressee.Id), request.MiddleIds));
  232. transactionScope.Complete();
  233. }
  234. }
  235. catch (Exception e)
  236. {
  237. throw new BusinessException(e.Message);
  238. }
  239. return true;
  240. }
  241. /// <summary>
  242. /// 恢复删除通知
  243. /// </summary>
  244. /// <param name="request"></param>
  245. /// <returns></returns>
  246. public async Task<bool> RecoverDeleteAsync(NoticeDeRequest request)
  247. {
  248. try
  249. {
  250. using (TransactionScope transactionScope = new TransactionScope())
  251. {
  252. //
  253. await _noticeAddresseeRepository.UpdateAsync(Q.Set(nameof(Addressee.IsDelete), false)
  254. .Where(nameof(Addressee.Id), request.MiddleIds));
  255. transactionScope.Complete();
  256. }
  257. }
  258. catch (Exception e)
  259. {
  260. throw new BusinessException(e.Message);
  261. }
  262. return true;
  263. }
  264. /// <summary>
  265. /// 通知修改
  266. /// </summary>
  267. /// <param name="id"></param>
  268. /// <param name="request"></param>
  269. /// <returns></returns>
  270. public async Task<bool> UpdateNoticeAsync(Notice notice)
  271. {
  272. return await _repository.UpdateAsync(notice);
  273. }
  274. /// <summary>
  275. /// 通知修改
  276. /// </summary>
  277. /// <param name="id"></param>
  278. /// <param name="request"></param>
  279. /// <returns></returns>
  280. public async Task<bool> UpdateAsync(SqlKata.Query query)
  281. {
  282. return await _repository.UpdateAsync(query) > 0;
  283. }
  284. /// <summary>
  285. /// 获取通知列表
  286. /// </summary>
  287. /// <param name="request"></param>
  288. /// <returns></returns>
  289. public async Task<PagedList<NoticeListPageResult>> GetNoticeListPageAsync(NoticePageSearchRequest request)
  290. {
  291. //用户收件人
  292. string sb = "";
  293. if (request.SearchType == 1)
  294. sb += " AND a.IsAdmin = 1 and a.NoticeAddresseeType=1 AND a.IsDelete = 0";
  295. else if (request.SearchType == 2)
  296. sb += " and a.NoticeAddresseeType=2 AND a.AttributeValue=1 AND a.IsDelete = 0";
  297. else if (request.SearchType == 3)
  298. sb += " AND a.IsDelete = 1 AND a.AttributeValue=1";
  299. else
  300. sb += " AND a.IsDelete = 0 AND a.NoticeAddresseeType != 2";
  301. if (!string.IsNullOrEmpty(request.Keyword))
  302. {
  303. if (request.NoticeFolderId > 0)
  304. sb += $@" AND a.ParentId ={request.NoticeFolderId} AND a.AttributeValue != 2 and (b.Title LIKE '%{request.Keyword}%'
  305. OR b.Content LIKE '%{request.Keyword}%'
  306. OR c.Name LIKE '%{request.Keyword}%'
  307. OR d.UserName LIKE '%{request.Keyword}%'
  308. OR a.CreatedDate LIKE '%{request.Keyword}%' or a.MiddleId in (SELECT
  309. g.NoticeId
  310. FROM
  311. tede_addressee g
  312. INNER JOIN
  313. tede_user h ON g.UserId = h.Id
  314. WHERE
  315. g.SourceId =a.MiddleId AND h.Name LIKE '%{request.Keyword}%'))";
  316. else
  317. sb += $@" AND a.AttributeValue != 2 AND (b.Title LIKE '%{request.Keyword}%'
  318. OR b.Content LIKE '%{request.Keyword}%'
  319. OR c.Name LIKE '%{request.Keyword}%'
  320. OR d.UserName LIKE '%{request.Keyword}%'
  321. OR a.CreatedDate LIKE '%{request.Keyword}%' or a.MiddleId in (SELECT
  322. g.NoticeId
  323. FROM
  324. tede_addressee g
  325. INNER JOIN
  326. tede_user h ON g.UserId = h.Id
  327. WHERE
  328. g.SourceId =a.MiddleId AND h.Name LIKE '%{request.Keyword}%'))";
  329. }
  330. else
  331. {
  332. var searchList = new List<int> { 1, 2, 3 };
  333. if (!searchList.Contains(request.SearchType))
  334. sb += " AND a.ParentId = " + request.NoticeFolderId;
  335. }
  336. var noticeTypeValue = GxPress.EnumConst.AllTypeConst.Notice.GetHashCode();
  337. var sql = $@"SELECT a.*,(SELECT GROUP_CONCAT(SourceName Separator'、') from tede_user_middle where MiddleType=10 and DataSourceId=a.MiddleId) as EnjoyUser,(SELECT
  338. COUNT(1)
  339. FROM
  340. tede_analyze
  341. WHERE
  342. TypeValue = {noticeTypeValue}
  343. AND SourceId = a.MiddleId
  344. AND AnalyzeType = 1) AS PraiseCount,
  345. (SELECT
  346. COUNT(1)
  347. FROM
  348. tede_analyze
  349. WHERE
  350. UserId = {request.UserId} AND TypeValue = {noticeTypeValue}
  351. AND SourceId = a.MiddleId
  352. AND AnalyzeType = 1
  353. LIMIT 0 , 1) AS IsLaud,
  354. (SELECT
  355. COUNT(1)
  356. FROM
  357. tede_comment
  358. WHERE
  359. ArticleId = a.MiddleId and pid=0
  360. AND TypeValue = {noticeTypeValue}) AS CommentCount,
  361. (SELECT
  362. COUNT(1)
  363. FROM
  364. tede_analyze
  365. WHERE
  366. UserId = {request.UserId} AND TypeValue = {noticeTypeValue}
  367. AND SourceId = a.MiddleId
  368. AND AnalyzeType = 4) AS RetransmissionCount,
  369. (SELECT
  370. COUNT(1)
  371. FROM
  372. tede_analyze
  373. WHERE
  374. UserId = {request.UserId} AND TypeValue = {noticeTypeValue}
  375. AND SourceId = a.MiddleId
  376. AND AnalyzeType = 4
  377. LIMIT 0 , 1) AS IsRetransmission,
  378. (SELECT
  379. COUNT(1)
  380. FROM
  381. tede_analyze
  382. WHERE
  383. UserId = {request.UserId} AND TypeValue = {noticeTypeValue}
  384. AND SourceId = a.MiddleId
  385. AND AnalyzeType = 4
  386. LIMIT 0 , 1) AS IsCollect,
  387. (SELECT
  388. COUNT(1)
  389. FROM
  390. tede_analyze
  391. WHERE
  392. UserId = {request.UserId} AND TypeValue = {noticeTypeValue}
  393. AND SourceId = a.MiddleId
  394. AND AnalyzeType = 4) AS CollectCount,
  395. (SELECT
  396. COUNT(1)
  397. FROM
  398. tede_middle
  399. WHERE
  400. ParentId = a.Id and IsDelete=0 and NoticeAddresseeType<>2) as FileCount,(SELECT
  401. COUNT(1)
  402. FROM
  403. tede_addressee
  404. WHERE
  405. SourceId = a.MiddleId AND IsRead = 1) as ReadCount,(SELECT
  406. COUNT(1)
  407. FROM
  408. tede_addressee
  409. WHERE
  410. SourceId = a.MiddleId ) as AllCount,(SELECT
  411. COUNT(1)
  412. FROM
  413. tede_addressee
  414. WHERE
  415. SourceId = a.MiddleId AND IsRead = 1 and UserId={request.UserId} limit 0,1) as IsRead, b.*, c.Name, c.AvatarUrl, d.*
  416. FROM
  417. tede_middle a
  418. left JOIN
  419. tede_notice b ON a.MiddleId = b.Id
  420. left JOIN
  421. tede_user c ON b.UserId = c.Id
  422. left JOIN
  423. tede_addressee d ON d.Id = a.MiddleSonId
  424. WHERE
  425. a.UserId = {request.UserId} and a.FolderType=1
  426. {sb}
  427. ORDER BY a.IsTop desc,a.LastModifiedDate desc,a.AttributeValue desc
  428. LIMIT {(request.Page - 1) * request.PerPage},{request.PerPage}";
  429. var countSql = string.Format(@"SELECT
  430. count(1)
  431. FROM
  432. tede_middle a
  433. left JOIN
  434. tede_notice b ON a.MiddleId = b.Id
  435. left JOIN
  436. tede_user c ON b.UserId = c.Id
  437. left JOIN
  438. tede_addressee d ON d.Id = a.MiddleSonId
  439. WHERE
  440. a.UserId = {1} and a.FolderType=1
  441. {0}", sb, request.UserId);
  442. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  443. var database = new Database(databaseType, _connectionString);
  444. var connection = database.GetConnection();
  445. var items = await connection
  446. .QueryAsync<NoticeListPageResult, Notice, User, Addressee, NoticeListPageResult>(sql,
  447. (noticeListPageResult, notice, user, noticeAddressee) =>
  448. {
  449. noticeListPageResult.Title = notice != null ? notice.Title : "";
  450. noticeListPageResult.Content = notice != null ? notice.Content : "[]";
  451. noticeListPageResult.UserName = user != null ? user.Name : "";
  452. noticeListPageResult.SourceId = notice != null ? notice.SourceId : 0;
  453. noticeListPageResult.AvatarUrl = user != null ? StringUtils.AddDomainMin(user.AvatarUrl) : "";
  454. noticeListPageResult.NoticeAddresseeId = noticeAddressee?.Id ?? 0;
  455. noticeListPageResult.NoticeId = noticeAddressee?.SourceId ?? 0;
  456. return noticeListPageResult;
  457. },
  458. splitOn: "Id,Name,Id");
  459. foreach (var item in items)
  460. {
  461. if (item.AttributeValue == 3)
  462. item.UReadCount = await _adminVerifyRepository.CountAsync(Q.Where(nameof(Entity.AdminVerify.AdminId), request.UserId).Where(nameof(Entity.AdminVerify.DisposeType), AdminVerifyTypeConst.UDispose.GetHashCode()));
  463. }
  464. PagedList<NoticeListPageResult> result = new PagedList<NoticeListPageResult>
  465. {
  466. Total = await CountAsync(countSql),
  467. Items = items
  468. };
  469. return result;
  470. }
  471. public async Task<int> CountAsync(string sql)
  472. {
  473. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  474. var database = new Database(databaseType, _connectionString);
  475. var connection = database.GetConnection();
  476. return await connection.ExecuteScalarAsync<int>(sql);
  477. }
  478. public async Task<IEnumerable<Notice>> GetAllAsync()
  479. {
  480. return await _repository.GetAllAsync();
  481. }
  482. public async Task<bool> DeleteAsync(Query query)
  483. {
  484. return await _repository.DeleteAsync(query) > 0;
  485. }
  486. /// <summary>
  487. ///
  488. /// </summary>
  489. /// <returns></returns>
  490. public async Task<List<JobNoticeResult>> ElasticSearchNotice()
  491. {
  492. var sql = "select a.Id,a.UserId,a.GuId,a.CreatedDate,b.Id,b.Title,b.Content,b.CreatedDate,c.Name,c.AvatarUrl from tede_middle a inner join tede_notice b on a.MiddleId=b.Id inner join tede_user c on c.Id=b.UserId where a.FolderType=1 and a.IsUpload=0 order by a.CreatedDate desc limit 0,100";
  493. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  494. var database = new Database(databaseType, _connectionString);
  495. var connection = database.GetConnection();
  496. var items = await connection
  497. .QueryAsync<JobNoticeResult, Notice, User, JobNoticeResult>(sql,
  498. (jobNoticeResult, notice, user) =>
  499. {
  500. jobNoticeResult.MiddleId = jobNoticeResult.Id;
  501. jobNoticeResult.Id = notice.Id;
  502. jobNoticeResult.Title = notice != null ? notice.Title : "";
  503. jobNoticeResult.Content = notice != null ? notice.Content : "";
  504. jobNoticeResult.AvatarUrl = user != null ? user.AvatarUrl : "";
  505. jobNoticeResult.Name = user != null ? user.Name : "";
  506. return jobNoticeResult;
  507. },
  508. splitOn: "Id,Id,Name");
  509. return items.ToList();
  510. }
  511. }
  512. }