NoticeRepository.cs 24 KB

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