NoticeRepository.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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 sql = $@"SELECT a.*,(SELECT GROUP_CONCAT(SourceName Separator'、') from tede_user_middle where MiddleType=10 and DataSourceId=a.MiddleId) as EnjoyUser,(SELECT
  337. COUNT(1)
  338. FROM
  339. tede_analyze
  340. WHERE
  341. TypeValue = 2
  342. AND SourceId = a.MiddleId
  343. AND AnalyzeType = 1) AS PraiseCount,
  344. (SELECT
  345. COUNT(1)
  346. FROM
  347. tede_analyze
  348. WHERE
  349. UserId = {request.UserId} AND TypeValue = 2
  350. AND SourceId = a.MiddleId
  351. AND AnalyzeType = 1
  352. LIMIT 0 , 1) AS IsLaud,
  353. (SELECT
  354. COUNT(1)
  355. FROM
  356. tede_comment
  357. WHERE
  358. ArticleId = a.MiddleId and pid=0
  359. AND TypeValue = 2) AS CommentCount,
  360. (SELECT
  361. COUNT(1)
  362. FROM
  363. tede_analyze
  364. WHERE
  365. UserId = {request.UserId} AND TypeValue = 2
  366. AND SourceId = a.MiddleId
  367. AND AnalyzeType = 4) AS RetransmissionCount,
  368. (SELECT
  369. COUNT(1)
  370. FROM
  371. tede_analyze
  372. WHERE
  373. UserId = {request.UserId} AND TypeValue = 2
  374. AND SourceId = a.MiddleId
  375. AND AnalyzeType = 4
  376. LIMIT 0 , 1) AS IsRetransmission,
  377. (SELECT
  378. COUNT(1)
  379. FROM
  380. tede_analyze
  381. WHERE
  382. UserId = {request.UserId} AND TypeValue = 2
  383. AND SourceId = a.MiddleId
  384. AND AnalyzeType = 4
  385. LIMIT 0 , 1) AS IsCollect,
  386. (SELECT
  387. COUNT(1)
  388. FROM
  389. tede_analyze
  390. WHERE
  391. UserId = {request.UserId} AND TypeValue = 2
  392. AND SourceId = a.MiddleId
  393. AND AnalyzeType = 4) AS CollectCount,
  394. (SELECT
  395. COUNT(1)
  396. FROM
  397. tede_middle
  398. WHERE
  399. ParentId = a.Id and IsDelete=0 and NoticeAddresseeType<>2) as FileCount,(SELECT
  400. COUNT(1)
  401. FROM
  402. tede_addressee
  403. WHERE
  404. SourceId = a.MiddleId AND IsRead = 1) as ReadCount,(SELECT
  405. COUNT(1)
  406. FROM
  407. tede_addressee
  408. WHERE
  409. SourceId = a.MiddleId ) as AllCount,(SELECT
  410. COUNT(1)
  411. FROM
  412. tede_addressee
  413. WHERE
  414. SourceId = a.MiddleId AND IsRead = 1 and UserId={request.UserId} limit 0,1) as IsRead, b.*, c.Name, c.AvatarUrl, d.*
  415. FROM
  416. tede_middle a
  417. left JOIN
  418. tede_notice b ON a.MiddleId = b.Id
  419. left JOIN
  420. tede_user c ON b.UserId = c.Id
  421. left JOIN
  422. tede_addressee d ON d.Id = a.MiddleSonId
  423. WHERE
  424. a.UserId = {request.UserId} and a.FolderType=1
  425. {sb}
  426. ORDER BY a.IsTop desc,a.LastModifiedDate desc,a.AttributeValue desc
  427. LIMIT {(request.Page - 1) * request.PerPage},{request.PerPage}";
  428. var countSql = string.Format(@"SELECT
  429. count(1)
  430. FROM
  431. tede_middle a
  432. left JOIN
  433. tede_notice b ON a.MiddleId = b.Id
  434. left JOIN
  435. tede_user c ON b.UserId = c.Id
  436. left JOIN
  437. tede_addressee d ON d.Id = a.MiddleSonId
  438. WHERE
  439. a.UserId = {1} and a.FolderType=1
  440. {0}", sb, request.UserId);
  441. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  442. var database = new Database(databaseType, _connectionString);
  443. var connection = database.GetConnection();
  444. var items = await connection
  445. .QueryAsync<NoticeListPageResult, Notice, User, Addressee, NoticeListPageResult>(sql,
  446. (noticeListPageResult, notice, user, noticeAddressee) =>
  447. {
  448. noticeListPageResult.Title = notice != null ? notice.Title : "";
  449. noticeListPageResult.Content = notice != null ? notice.Content : "[]";
  450. noticeListPageResult.UserName = user != null ? user.Name : "";
  451. noticeListPageResult.SourceId = notice != null ? notice.SourceId : 0;
  452. noticeListPageResult.AvatarUrl = user != null ? StringUtils.AddDomainMin(user.AvatarUrl) : "";
  453. noticeListPageResult.NoticeAddresseeId = noticeAddressee?.Id ?? 0;
  454. noticeListPageResult.NoticeId = noticeAddressee?.SourceId ?? 0;
  455. return noticeListPageResult;
  456. },
  457. splitOn: "Id,Name,Id");
  458. foreach (var item in items)
  459. {
  460. if (item.AttributeValue == 3)
  461. item.UReadCount = await _adminVerifyRepository.CountAsync(Q.Where(nameof(Entity.AdminVerify.AdminId), request.UserId).Where(nameof(Entity.AdminVerify.DisposeType), AdminVerifyTypeConst.UDispose.GetHashCode()));
  462. }
  463. PagedList<NoticeListPageResult> result = new PagedList<NoticeListPageResult>
  464. {
  465. Total = await CountAsync(countSql),
  466. Items = items
  467. };
  468. return result;
  469. }
  470. public async Task<int> CountAsync(string sql)
  471. {
  472. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  473. var database = new Database(databaseType, _connectionString);
  474. var connection = database.GetConnection();
  475. return await connection.ExecuteScalarAsync<int>(sql);
  476. }
  477. public async Task<IEnumerable<Notice>> GetAllAsync()
  478. {
  479. return await _repository.GetAllAsync();
  480. }
  481. public async Task<bool> DeleteAsync(Query query)
  482. {
  483. return await _repository.DeleteAsync(query) > 0;
  484. }
  485. /// <summary>
  486. ///
  487. /// </summary>
  488. /// <returns></returns>
  489. public async Task<List<JobNoticeResult>> ElasticSearchNotice()
  490. {
  491. 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";
  492. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  493. var database = new Database(databaseType, _connectionString);
  494. var connection = database.GetConnection();
  495. var items = await connection
  496. .QueryAsync<JobNoticeResult, Notice, User, JobNoticeResult>(sql,
  497. (jobNoticeResult, notice, user) =>
  498. {
  499. jobNoticeResult.MiddleId = jobNoticeResult.Id;
  500. jobNoticeResult.Id = notice.Id;
  501. jobNoticeResult.Title = notice != null ? notice.Title : "";
  502. jobNoticeResult.Content = notice != null ? notice.Content : "";
  503. jobNoticeResult.AvatarUrl = user != null ? user.AvatarUrl : "";
  504. jobNoticeResult.Name = user != null ? user.Name : "";
  505. return jobNoticeResult;
  506. },
  507. splitOn: "Id,Id,Name");
  508. return items.ToList();
  509. }
  510. }
  511. }