GroupRepository.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. using System.Collections.Generic;
  2. using System.Threading.Tasks;
  3. using AutoMapper;
  4. using Dapper;
  5. using GxPress.Common.AppOptions;
  6. using GxPress.Common.Exceptions;
  7. using GxPress.Common.Page;
  8. using GxPress.Common.Tools;
  9. using GxPress.Entity;
  10. using GxPress.EnumConst;
  11. using GxPress.Repository.Interface;
  12. using GxPress.Request.App.Group;
  13. using GxPress.Result.App.Group;
  14. using GxPress.Result.App.GroupUser;
  15. using Microsoft.AspNetCore.Hosting;
  16. using Microsoft.Extensions.Options;
  17. using Newtonsoft.Json;
  18. using Datory;
  19. using GxPress.Request.App.Topic;
  20. using SqlKata;
  21. using GxPress.Result.Job;
  22. using System.Linq;
  23. namespace GxPress.Repository.Implement
  24. {
  25. public class GroupRepository : IGroupRepository
  26. {
  27. private readonly Repository<Entity.Group> _repository;
  28. private readonly IMapper _mapper;
  29. private readonly IWebHostEnvironment _environment;
  30. private readonly string _connectionString;
  31. private readonly string _databaseTypeStr;
  32. private readonly Repository<GroupUser> _groupUserRepository;
  33. public GroupRepository(IOptionsMonitor<DatabaseOptions> dbOptionsAccessor, IMapper mapper,
  34. IWebHostEnvironment environment)
  35. {
  36. _databaseTypeStr = dbOptionsAccessor.CurrentValue.DatabaseType;
  37. _connectionString = dbOptionsAccessor.CurrentValue.ConnectionString;
  38. var databaseType =
  39. StringUtils.ToEnum<DatabaseType>(dbOptionsAccessor.CurrentValue.DatabaseType, DatabaseType.MySql);
  40. var database = new Database(databaseType, dbOptionsAccessor.CurrentValue.ConnectionString);
  41. _repository = new Repository<Entity.Group>(database);
  42. _groupUserRepository = new Repository<GroupUser>(database);
  43. _environment = environment;
  44. _mapper = mapper;
  45. }
  46. public IDatabase Database => _repository.Database;
  47. public string TableName => _repository.TableName;
  48. public List<TableColumn> TableColumns => _repository.TableColumns;
  49. public async Task<int> InsertAsync(GroupInRequest request)
  50. {
  51. if (string.IsNullOrEmpty(request.Name))
  52. throw new BusinessException("小组名称不能为空");
  53. var group = new Entity.Group
  54. {
  55. Name = request.Name,
  56. AvatarUrl = request.AvatarUrl,
  57. Introduce = request.Introduce,
  58. IsAdmin = false,
  59. IsUDisturb = false,
  60. QRCoder = request.QRCoder,
  61. IsWords = false,
  62. UserId = request.UserId,
  63. GroupCategroyId = request.GroupCategroyId,
  64. LabelName = request.LabelName,
  65. IsShow = request.IsShow
  66. };
  67. if (!string.IsNullOrEmpty(group.AvatarUrl))
  68. group.AvatarUrl = StringUtils.RemoveDomain(group.AvatarUrl);
  69. var id = await _repository.InsertAsync(group);
  70. //生成二维码
  71. var groupDto = await _repository.GetAsync(id);
  72. var qrCodeData = new { key = QRCodeTypeConst.GroupInfo, value = groupDto.Guid };
  73. var resultPath =
  74. FileHelper.SaveQRCodeFile(StringUtils.GetWebRootPath(_environment.WebRootPath),
  75. JsonConvert.SerializeObject(qrCodeData));
  76. groupDto.QRCoder = resultPath.RelativePath;
  77. await _repository.UpdateAsync(groupDto);
  78. return id;
  79. }
  80. public async Task<IEnumerable<GroupUser>> GetAllAsync(SqlKata.Query query)
  81. {
  82. return await _groupUserRepository.GetAllAsync(query);
  83. }
  84. /// <summary>
  85. /// 修改小组
  86. /// </summary>
  87. /// <param name="request"></param>
  88. /// <returns></returns>
  89. public async Task<bool> UpdateAsync(GroupUpRequest request)
  90. {
  91. var group = await _repository.GetAsync(request.Id);
  92. if (!string.IsNullOrEmpty(request.Name))
  93. group.Name = request.Name;
  94. if (!string.IsNullOrEmpty(request.AvatarUrl))
  95. group.AvatarUrl = StringUtils.RemoveDomain(request.AvatarUrl);
  96. if (!string.IsNullOrEmpty(request.Introduce))
  97. group.Introduce = request.Introduce;
  98. if (!string.IsNullOrEmpty(request.LabelName))
  99. group.LabelName = request.LabelName;
  100. if (request.IsShow > 0)
  101. group.IsShow = request.IsShow == 1;
  102. return await _repository.UpdateAsync(group);
  103. }
  104. /// <summary>
  105. /// 删除小组
  106. /// </summary>
  107. /// <param name="id"></param>
  108. /// <returns></returns>
  109. public async Task<bool> DeleteAsync(int id)
  110. {
  111. return await _repository.DeleteAsync(id);
  112. }
  113. public async Task<bool> DeleteAsync(Query query)
  114. {
  115. return await _repository.DeleteAsync(query) > 0;
  116. }
  117. /// <summary>
  118. /// 查询小组
  119. /// </summary>
  120. /// <param name="request"></param>
  121. /// <returns></returns>
  122. public async Task<PagedList<GroupUserFindResult>> FindGroupByGroupFolderId(GroupSearchRequest request)
  123. {
  124. var pagedList = new PagedList<GroupUserFindResult>();
  125. //根据文件夹ID查询成员
  126. var sqlValue = "";
  127. // if (!string.IsNullOrEmpty(request.Key))
  128. // sqlValue += $"and b.Name like '%{request.Key}%'";
  129. //共享数量
  130. var topicSharingCount = "(select count(1) from tede_group_user where GroupId=a.MiddleId) as TopicSharingCount";
  131. //总话题数量
  132. var topicAllCount = "(select count(1) from tede_topic where GroupId=a.MiddleId) as TopicAllCount";
  133. //未读话题数量
  134. var uReadTopicCount = $"(select count(1) from tede_topic_addressee where TopicId in (select Id from tede_topic where GroupId=a.MiddleId) and UserId={request.UserId} and IsRead=0) as UReadTopicCount";
  135. var categoryName = "(select FolderName from tede_middle where id=a.ParentId) as CategoryName";
  136. var sql =
  137. $@"SELECT a.*,{topicSharingCount},{topicAllCount},{uReadTopicCount},{categoryName},
  138. (SELECT
  139. COUNT(1)
  140. FROM
  141. tede_group
  142. WHERE
  143. id IN (SELECT
  144. MiddleId
  145. FROM
  146. tede_middle
  147. WHERE
  148. ParentId = a.Id)) AS FileCount,b.Id, b.AvatarUrl, b.Name FROM tede_Middle a LEFT JOIN tede_group b ON a.MiddleId = b.Id WHERE 1=1 ";
  149. if (request.GroupFolderId == 0 && string.IsNullOrEmpty(request.Key))
  150. sql += $"and a.ParentId = @groupFolderId ";
  151. else if (request.GroupFolderId > 0 && !string.IsNullOrEmpty(request.Key))
  152. sql += $"and a.ParentId = @groupFolderId and (a.FolderName like '%{request.Key}%' or b.Name like '%{request.Key}%')";
  153. else if (request.GroupFolderId > 0 && string.IsNullOrEmpty(request.Key))
  154. sql += $"and a.ParentId = @groupFolderId ";
  155. else
  156. sql += $" and (a.FolderName like '%{request.Key}%' or b.Name like '%{request.Key}%')";
  157. sql +=
  158. $@" and a.UserId=@userId and a.FolderType=7 and a.IsDelete=0 {sqlValue} and (b.id>0 or a.AttributeValue=2) ORDER BY a.IsTop DESC, a.LastModifiedDate DESC ,a.AttributeValue DESC LIMIT @page , @pageSize";
  159. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  160. var database = new Database(databaseType, _connectionString);
  161. var connection = database.GetConnection();
  162. var result =
  163. await connection
  164. .QueryAsync<GroupUserFindResult, Entity.Group, GroupUserFindResult>(sql,
  165. (groupUserFindResult, group) =>
  166. {
  167. groupUserFindResult.GroupName = group == null ? "" : group.Name;
  168. groupUserFindResult.AvatarUrl = group == null ? "" : StringUtils.AddDomainMin(group.AvatarUrl);
  169. groupUserFindResult.GroupId = group?.Id ?? 0;
  170. return groupUserFindResult;
  171. },
  172. new
  173. {
  174. groupFolderId = request.GroupFolderId,
  175. userId = request.UserId,
  176. page = (request.Page - 1) * request.PerPage,
  177. pageSize = request.PerPage * request.Page
  178. }, splitOn: "Id");
  179. pagedList.Items = result;
  180. var sqlCount =
  181. @"SELECT count(1) FROM tede_Middle a LEFT JOIN tede_group b ON a.MiddleId = b.Id WHERE 1=1 ";
  182. if (request.GroupFolderId == 0 && string.IsNullOrEmpty(request.Key))
  183. sqlCount += $"and a.ParentId = {request.GroupFolderId} ";
  184. else if (request.GroupFolderId > 0 && !string.IsNullOrEmpty(request.Key))
  185. sqlCount += $"and a.ParentId = {request.GroupFolderId} and (a.FolderName like '%{request.Key}%' or b.Name like '%{request.Key}%')";
  186. else if (request.GroupFolderId > 0 && string.IsNullOrEmpty(request.Key))
  187. sqlCount += $"and a.ParentId = {request.GroupFolderId} ";
  188. else
  189. sql += $" and (a.FolderName like '%{request.Key}%' or b.Name like '%{request.Key}%')";
  190. sqlCount +=
  191. $" and a.UserId={request.UserId} and a.FolderType=7 and a.IsDelete=0 {sqlValue} and (b.id>0 or a.AttributeValue=2)";
  192. pagedList.Total = await FindGroupByGroupFolderIdCountAsync(sqlCount);
  193. return pagedList;
  194. }
  195. /// <summary>
  196. /// 条数
  197. /// </summary>
  198. /// <param name="sql"></param>
  199. /// <returns></returns>
  200. public async Task<int> FindGroupByGroupFolderIdCountAsync(string sql)
  201. {
  202. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  203. var database = new Database(databaseType, _connectionString);
  204. var connection = database.GetConnection();
  205. var result = await connection.ExecuteScalarAsync<int>(sql);
  206. return result;
  207. }
  208. /// <summary>
  209. /// 获取小组详情
  210. /// </summary>
  211. /// <param name="request"></param>
  212. /// <returns></returns>
  213. public async Task<GroupDetailResult> GroupDetailAsync(GroupDetailRequest request)
  214. {
  215. var groupDetail = await _repository.GetAsync(request.GroupId);
  216. if (groupDetail == null)
  217. throw new BusinessException("小组不存在");
  218. if (!string.IsNullOrEmpty(groupDetail.AvatarUrl))
  219. groupDetail.AvatarUrl = StringUtils.AddDomainMin(groupDetail.AvatarUrl);
  220. if (!string.IsNullOrEmpty(groupDetail.QRCoder))
  221. groupDetail.QRCoder = StringUtils.AddDomain(groupDetail.QRCoder);
  222. var sql =
  223. "SELECT a.*,b.Name,b.AvatarUrl,c.Name FROM tede_group_user a inner join tede_user b on a.UserId=b.Id inner join tede_department c on b.DepartmentId=c.Id where a.GroupId=@groupId order by a.GroupUserRoleId";
  224. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  225. var database = new Database(databaseType, _connectionString);
  226. var connection = database.GetConnection();
  227. var result =
  228. await connection
  229. .QueryAsync<GroupUserListResult, User, Department, GroupUserListResult>(sql,
  230. (groupUserListResult, user, department) =>
  231. {
  232. groupUserListResult.DepartmentName = department.Name;
  233. groupUserListResult.Name = user.Name;
  234. groupUserListResult.AvatarUrl = StringUtils.AddDomainMin(user.AvatarUrl);
  235. return groupUserListResult;
  236. }, new { groupId = request.GroupId }, splitOn: "Name");
  237. var groupDetailResult = _mapper.Map<GroupDetailResult>(groupDetail);
  238. groupDetailResult.GroupUserListResult = result;
  239. var groupUser = await _groupUserRepository.GetAsync(Q.Where(nameof(GroupUser.UserId), request.UserId)
  240. .Where(nameof(GroupUser.GroupId), request.GroupId));
  241. //获取当前用户的权限
  242. groupDetailResult.GroupUserRoleId = groupUser != null ? groupUser.GroupUserRoleId : 0;
  243. groupDetailResult.IsUDisturb = groupUser != null ? groupUser.IsUDisturb : false;
  244. groupDetailResult.IsAdmin = groupUser != null ? groupUser.UserId == groupDetailResult.UserId : false;
  245. groupDetailResult.IsUser = groupUser != null ? groupUser.UserId == request.UserId : false;
  246. groupDetailResult.CreatedDate = groupDetail.CreatedDate;
  247. return groupDetailResult;
  248. }
  249. /// <summary>
  250. /// 搜索小组成员
  251. /// </summary>
  252. /// <param name="request"></param>
  253. /// <returns></returns>
  254. public async Task<IEnumerable<GroupUserListResult>> SearchGroupUserAsync(TopicDetailListRequest request)
  255. {
  256. string sql =
  257. $@"SELECT a.*, b.Name, b.AvatarUrl, c.Name FROM tede_group_user a INNER JOIN tede_user b ON a.UserId = b.Id INNER JOIN
  258. tede_department c ON b.DepartmentId = c.Id
  259. WHERE a.GroupId = {request.GroupId} and b.Name like '%{request.Key}%'";
  260. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  261. var database = new Database(databaseType, _connectionString);
  262. var connection = database.GetConnection();
  263. var result =
  264. await connection
  265. .QueryAsync<GroupUserListResult, User, Department, GroupUserListResult>(sql,
  266. (groupUserListResult, user, department) =>
  267. {
  268. groupUserListResult.DepartmentName = department.Name;
  269. groupUserListResult.Name = user.Name;
  270. groupUserListResult.AvatarUrl = StringUtils.AddDomainMin(user.AvatarUrl);
  271. return groupUserListResult;
  272. }, splitOn: "Name");
  273. return result;
  274. }
  275. /// <summary>
  276. /// 获取小组详情
  277. /// </summary>
  278. /// <param name="guId"></param>
  279. /// <param name="userId"></param>
  280. /// <returns></returns>
  281. public async Task<GroupDetailResult> GroupDetailByGuIdAsync(string guId, int userId)
  282. {
  283. var groupDetail = await _repository.GetAsync(Q.Where(nameof(Entity.Group.Guid), guId));
  284. if (groupDetail == null)
  285. throw new BusinessException("小组不存在");
  286. if (!string.IsNullOrEmpty(groupDetail.AvatarUrl))
  287. groupDetail.AvatarUrl = StringUtils.AddDomainMin(groupDetail.AvatarUrl);
  288. if (!string.IsNullOrEmpty(groupDetail.QRCoder))
  289. groupDetail.QRCoder = StringUtils.AddDomain(groupDetail.QRCoder);
  290. var sql =
  291. "SELECT a.*,b.Name,b.AvatarUrl,c.Name FROM tede_group_user a inner join tede_user b on a.UserId=b.Id inner join tede_department c on b.DepartmentId=c.Id where a.GroupId=@groupId";
  292. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  293. var database = new Database(databaseType, _connectionString);
  294. var connection = database.GetConnection();
  295. var result =
  296. await connection
  297. .QueryAsync<GroupUserListResult, User, Department, GroupUserListResult>(sql,
  298. (groupUserListResult, user, department) =>
  299. {
  300. groupUserListResult.DepartmentName = department.Name;
  301. groupUserListResult.Name = user.Name;
  302. groupUserListResult.AvatarUrl = StringUtils.AddDomainMin(user.AvatarUrl);
  303. return groupUserListResult;
  304. }, new { groupId = groupDetail.Id }, splitOn: "Name");
  305. var groupDetailResult = _mapper.Map<GroupDetailResult>(groupDetail);
  306. groupDetailResult.GroupUserListResult = result;
  307. var groupUser = await _groupUserRepository.GetAsync(Q.Where(nameof(GroupUser.UserId), userId)
  308. .Where(nameof(GroupUser.Guid), guId));
  309. groupDetailResult.GroupUserRoleId = groupUser?.GroupUserRoleId ?? GroupUserRoleTyeConst.General;
  310. //获取当前用户的权限
  311. return groupDetailResult;
  312. }
  313. /// <summary>
  314. /// 获取用户未读取话题数量
  315. /// </summary>
  316. /// <param name="userId"></param>
  317. /// <param name="groupId"></param>
  318. /// <returns></returns>
  319. public async Task<int> GetUReadCountAsync(int userId, int groupId)
  320. {
  321. string sql =
  322. @"select count(1) from tede_topic a inner join tede_topic_addressee b on a.Id=b.TopicId where b.UserId=@userId and b.IsRead=0 and a.GroupId=@groupId";
  323. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  324. var database = new Database(databaseType, _connectionString);
  325. var connection = database.GetConnection();
  326. var result = await connection.ExecuteScalarAsync<int>(sql, new { userId, groupId });
  327. return result;
  328. }
  329. /// <summary>
  330. /// 获取小组的共享话题数量
  331. /// </summary>
  332. /// <param name="groupId"></param>
  333. /// <returns></returns>
  334. public async Task<int> SharingCountAsync(int groupId)
  335. {
  336. var sql =
  337. $"select count(1) from tede_group_user where GroupId={groupId}";
  338. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  339. var database = new Database(databaseType, _connectionString);
  340. var connection = database.GetConnection();
  341. var result = await connection.ExecuteScalarAsync<int>(sql, new { GroupId = groupId });
  342. return result;
  343. }
  344. public async Task<Entity.Group> GetAsync(int id)
  345. {
  346. return await _repository.GetAsync(id);
  347. }
  348. /// <summary>
  349. /// 是开启管理员同意加入
  350. /// </summary>
  351. /// <param name="groupId"></param>
  352. /// <returns></returns>
  353. public async Task<bool> SetGroupIsAdminAsync(int groupId)
  354. {
  355. var group = await GetAsync(groupId);
  356. return await _repository.UpdateAsync(Q.Set(nameof(Entity.Group.IsAdmin), !group.IsAdmin)
  357. .Where(nameof(Entity.Group.Id), groupId)) > 0;
  358. }
  359. /// <summary>
  360. /// 是否禁言
  361. /// </summary>
  362. /// <param name="groupId"></param>
  363. /// <returns></returns>
  364. public async Task<bool> SetGroupIsWordsAsync(int groupId)
  365. {
  366. var group = await GetAsync(groupId);
  367. return await _repository.UpdateAsync(Q.Set(nameof(Entity.Group.IsWords), !group.IsWords)
  368. .Where(nameof(Entity.Group.Id), groupId)) > 0;
  369. }
  370. public async Task<List<JobGroupResult>> ElasticSearchGroup()
  371. {
  372. var sql = "select a.Id,a.GuId,a.UserId,b.Id,b.Name,b.AvatarUrl,b.CreatedDate,c.Name from tede_middle a inner join tede_group b on a.MiddleId=b.Id inner join tede_user c on c.Id=b.UserId where a.FolderType=7 and a.IsUpload=0 order by a.CreatedDate desc limit 0,100";
  373. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  374. var database = new Database(databaseType, _connectionString);
  375. var connection = database.GetConnection();
  376. var items = await connection
  377. .QueryAsync<JobGroupResult, Entity.Group, User, JobGroupResult>(sql,
  378. (jobGroupResult, group, user) =>
  379. {
  380. jobGroupResult.MiddleId = jobGroupResult.Id;
  381. jobGroupResult.Id = group.Id;
  382. jobGroupResult.Name = group != null ? group.Name : "";
  383. jobGroupResult.AvatarUrl = group != null ? group.AvatarUrl : "";
  384. return jobGroupResult;
  385. },
  386. splitOn: "Id,Id,Name");
  387. return items.ToList();
  388. }
  389. /// <summary>
  390. /// 根据广场类别查询小组
  391. /// </summary>
  392. /// <param name="categoryId"></param>
  393. /// <returns></returns>
  394. public async Task<IEnumerable<Entity.Group>> GetAllAsync(int categoryId)
  395. {
  396. var sql = $@"SELECT
  397. *,
  398. (SELECT
  399. COUNT(1)
  400. FROM
  401. tede_group_user
  402. WHERE
  403. GroupId = a.Id) AS UserCount,
  404. (SELECT
  405. COUNT(1)
  406. FROM
  407. tede_topic
  408. WHERE
  409. GroupId = a.Id) AS GroupArticleCount
  410. FROM
  411. tede_group a
  412. WHERE
  413. a.GroupCategroyId = {categoryId} and a.IsShow=1";
  414. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  415. var database = new Database(databaseType, _connectionString);
  416. var connection = database.GetConnection();
  417. var result = await connection.QueryAsync<Entity.Group>(sql);
  418. //return await _repository.GetAllAsync(Q.Where(nameof(Entity.Group.GroupCategroyId), categoryId));
  419. return result;
  420. }
  421. /// <summary>
  422. /// 用户小组列表
  423. /// </summary>
  424. /// <param name="userId"></param>
  425. /// <returns></returns>
  426. public async Task<IEnumerable<UserGroupList>> GetAllByUserIdAsync(int userId)
  427. {
  428. string sql = $@"SELECT
  429. Id,
  430. Name,
  431. AvatarUrl,
  432. (SELECT
  433. COUNT(1)
  434. FROM
  435. tede_group_user
  436. WHERE
  437. GroupId = a.Id) AS UserCount
  438. FROM
  439. tede_group a
  440. WHERE
  441. a.id IN (SELECT
  442. GroupId
  443. FROM
  444. ccpph_tede.tede_group_user
  445. WHERE
  446. UserId = {userId})";
  447. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  448. var database = new Database(databaseType, _connectionString);
  449. var connection = database.GetConnection();
  450. var items = await connection
  451. .QueryAsync<UserGroupList>(sql);
  452. foreach (var item in items)
  453. {
  454. item.AvatarUrl = StringUtils.AddDomain(item.AvatarUrl);
  455. }
  456. return items;
  457. }
  458. }
  459. }