GroupRepository.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. };
  65. if (!string.IsNullOrEmpty(group.AvatarUrl))
  66. group.AvatarUrl = StringUtils.RemoveDomain(group.AvatarUrl);
  67. var id = await _repository.InsertAsync(group);
  68. //生成二维码
  69. var groupDto = await _repository.GetAsync(id);
  70. var qrCodeData = new { key = QRCodeTypeConst.GroupInfo, value = groupDto.Guid };
  71. var resultPath =
  72. FileHelper.SaveQRCodeFile(StringUtils.GetWebRootPath(_environment.WebRootPath),
  73. JsonConvert.SerializeObject(qrCodeData));
  74. groupDto.QRCoder = resultPath.RelativePath;
  75. await _repository.UpdateAsync(groupDto);
  76. return id;
  77. }
  78. public async Task<IEnumerable<GroupUser>> GetAllAsync(SqlKata.Query query)
  79. {
  80. return await _groupUserRepository.GetAllAsync(query);
  81. }
  82. /// <summary>
  83. /// 修改小组
  84. /// </summary>
  85. /// <param name="request"></param>
  86. /// <returns></returns>
  87. public async Task<bool> UpdateAsync(GroupUpRequest request)
  88. {
  89. var group = await _repository.GetAsync(request.Id);
  90. if (!string.IsNullOrEmpty(request.Name))
  91. group.Name = request.Name;
  92. if (!string.IsNullOrEmpty(request.AvatarUrl))
  93. group.AvatarUrl = StringUtils.RemoveDomain(request.AvatarUrl);
  94. if (!string.IsNullOrEmpty(request.Introduce))
  95. group.Introduce = request.Introduce;
  96. return await _repository.UpdateAsync(group);
  97. }
  98. /// <summary>
  99. /// 删除小组
  100. /// </summary>
  101. /// <param name="id"></param>
  102. /// <returns></returns>
  103. public async Task<bool> DeleteAsync(int id)
  104. {
  105. return await _repository.DeleteAsync(id);
  106. }
  107. public async Task<bool> DeleteAsync(Query query)
  108. {
  109. return await _repository.DeleteAsync(query) > 0;
  110. }
  111. /// <summary>
  112. /// 查询小组
  113. /// </summary>
  114. /// <param name="request"></param>
  115. /// <returns></returns>
  116. public async Task<PagedList<GroupUserFindResult>> FindGroupByGroupFolderId(GroupSearchRequest request)
  117. {
  118. var pagedList = new PagedList<GroupUserFindResult>();
  119. //根据文件夹ID查询成员
  120. var sqlValue = "";
  121. // if (!string.IsNullOrEmpty(request.Key))
  122. // sqlValue += $"and b.Name like '%{request.Key}%'";
  123. //共享数量
  124. var topicSharingCount = "(select count(1) from tede_group_user where GroupId=a.MiddleId) as TopicSharingCount";
  125. //总话题数量
  126. var topicAllCount = "(select count(1) from tede_topic where GroupId=a.MiddleId) as TopicAllCount";
  127. //未读话题数量
  128. 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";
  129. var categoryName = "(select FolderName from tede_middle where id=a.ParentId) as CategoryName";
  130. var sql =
  131. $@"SELECT a.*,{topicSharingCount},{topicAllCount},{uReadTopicCount},{categoryName},
  132. (SELECT
  133. COUNT(1)
  134. FROM
  135. tede_group
  136. WHERE
  137. id IN (SELECT
  138. MiddleId
  139. FROM
  140. tede_middle
  141. WHERE
  142. 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 ";
  143. if (request.GroupFolderId == 0 && string.IsNullOrEmpty(request.Key))
  144. sql += $"and a.ParentId = @groupFolderId ";
  145. else if (request.GroupFolderId > 0 && !string.IsNullOrEmpty(request.Key))
  146. sql += $"and a.ParentId = @groupFolderId and (a.FolderName like '%{request.Key}%' or b.Name like '%{request.Key}%')";
  147. else if (request.GroupFolderId > 0 && string.IsNullOrEmpty(request.Key))
  148. sql += $"and a.ParentId = @groupFolderId ";
  149. else
  150. sql += $" and (a.FolderName like '%{request.Key}%' or b.Name like '%{request.Key}%')";
  151. sql +=
  152. $@" 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";
  153. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  154. var database = new Database(databaseType, _connectionString);
  155. var connection = database.GetConnection();
  156. var result =
  157. await connection
  158. .QueryAsync<GroupUserFindResult, Entity.Group, GroupUserFindResult>(sql,
  159. (groupUserFindResult, group) =>
  160. {
  161. groupUserFindResult.GroupName = group == null ? "" : group.Name;
  162. groupUserFindResult.AvatarUrl = group == null ? "" : StringUtils.AddDomainMin(group.AvatarUrl);
  163. groupUserFindResult.GroupId = group?.Id ?? 0;
  164. return groupUserFindResult;
  165. },
  166. new
  167. {
  168. groupFolderId = request.GroupFolderId,
  169. userId = request.UserId,
  170. page = (request.Page - 1) * request.PerPage,
  171. pageSize = request.PerPage * request.Page
  172. }, splitOn: "Id");
  173. pagedList.Items = result;
  174. var sqlCount =
  175. @"SELECT count(1) FROM tede_Middle a LEFT JOIN tede_group b ON a.MiddleId = b.Id WHERE 1=1 ";
  176. if (request.GroupFolderId == 0 && string.IsNullOrEmpty(request.Key))
  177. sqlCount += $"and a.ParentId = {request.GroupFolderId} ";
  178. else if (request.GroupFolderId > 0 && !string.IsNullOrEmpty(request.Key))
  179. sqlCount += $"and a.ParentId = {request.GroupFolderId} and (a.FolderName like '%{request.Key}%' or b.Name like '%{request.Key}%')";
  180. else if (request.GroupFolderId > 0 && string.IsNullOrEmpty(request.Key))
  181. sqlCount += $"and a.ParentId = {request.GroupFolderId} ";
  182. else
  183. sql += $" and (a.FolderName like '%{request.Key}%' or b.Name like '%{request.Key}%')";
  184. sqlCount +=
  185. $" and a.UserId={request.UserId} and a.FolderType=7 and a.IsDelete=0 {sqlValue} and (b.id>0 or a.AttributeValue=2)";
  186. pagedList.Total = await FindGroupByGroupFolderIdCountAsync(sqlCount);
  187. return pagedList;
  188. }
  189. /// <summary>
  190. /// 条数
  191. /// </summary>
  192. /// <param name="sql"></param>
  193. /// <returns></returns>
  194. public async Task<int> FindGroupByGroupFolderIdCountAsync(string sql)
  195. {
  196. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  197. var database = new Database(databaseType, _connectionString);
  198. var connection = database.GetConnection();
  199. var result = await connection.ExecuteScalarAsync<int>(sql);
  200. return result;
  201. }
  202. /// <summary>
  203. /// 获取小组详情
  204. /// </summary>
  205. /// <param name="request"></param>
  206. /// <returns></returns>
  207. public async Task<GroupDetailResult> GroupDetailAsync(GroupDetailRequest request)
  208. {
  209. var groupDetail = await _repository.GetAsync(request.GroupId);
  210. if (groupDetail == null)
  211. throw new BusinessException("小组不存在");
  212. if (!string.IsNullOrEmpty(groupDetail.AvatarUrl))
  213. groupDetail.AvatarUrl = StringUtils.AddDomainMin(groupDetail.AvatarUrl);
  214. if (!string.IsNullOrEmpty(groupDetail.QRCoder))
  215. groupDetail.QRCoder = StringUtils.AddDomain(groupDetail.QRCoder);
  216. var sql =
  217. "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";
  218. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  219. var database = new Database(databaseType, _connectionString);
  220. var connection = database.GetConnection();
  221. var result =
  222. await connection
  223. .QueryAsync<GroupUserListResult, User, Department, GroupUserListResult>(sql,
  224. (groupUserListResult, user, department) =>
  225. {
  226. groupUserListResult.DepartmentName = department.Name;
  227. groupUserListResult.Name = user.Name;
  228. groupUserListResult.AvatarUrl = StringUtils.AddDomainMin(user.AvatarUrl);
  229. return groupUserListResult;
  230. }, new { groupId = request.GroupId }, splitOn: "Name");
  231. var groupDetailResult = _mapper.Map<GroupDetailResult>(groupDetail);
  232. groupDetailResult.GroupUserListResult = result;
  233. var groupUser = await _groupUserRepository.GetAsync(Q.Where(nameof(GroupUser.UserId), request.UserId)
  234. .Where(nameof(GroupUser.GroupId), request.GroupId));
  235. //获取当前用户的权限
  236. groupDetailResult.GroupUserRoleId = groupUser.GroupUserRoleId;
  237. groupDetailResult.IsUDisturb = groupUser.IsUDisturb;
  238. return groupDetailResult;
  239. }
  240. /// <summary>
  241. /// 搜索小组成员
  242. /// </summary>
  243. /// <param name="request"></param>
  244. /// <returns></returns>
  245. public async Task<IEnumerable<GroupUserListResult>> SearchGroupUserAsync(TopicDetailListRequest request)
  246. {
  247. string sql =
  248. $@"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
  249. tede_department c ON b.DepartmentId = c.Id
  250. WHERE a.GroupId = {request.GroupId} and b.Name like '%{request.Key}%'";
  251. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  252. var database = new Database(databaseType, _connectionString);
  253. var connection = database.GetConnection();
  254. var result =
  255. await connection
  256. .QueryAsync<GroupUserListResult, User, Department, GroupUserListResult>(sql,
  257. (groupUserListResult, user, department) =>
  258. {
  259. groupUserListResult.DepartmentName = department.Name;
  260. groupUserListResult.Name = user.Name;
  261. groupUserListResult.AvatarUrl = StringUtils.AddDomainMin(user.AvatarUrl);
  262. return groupUserListResult;
  263. }, splitOn: "Name");
  264. return result;
  265. }
  266. /// <summary>
  267. /// 获取小组详情
  268. /// </summary>
  269. /// <param name="guId"></param>
  270. /// <param name="userId"></param>
  271. /// <returns></returns>
  272. public async Task<GroupDetailResult> GroupDetailByGuIdAsync(string guId, int userId)
  273. {
  274. var groupDetail = await _repository.GetAsync(Q.Where(nameof(Entity.Group.Guid), guId));
  275. if (groupDetail == null)
  276. throw new BusinessException("小组不存在");
  277. if (!string.IsNullOrEmpty(groupDetail.AvatarUrl))
  278. groupDetail.AvatarUrl = StringUtils.AddDomainMin(groupDetail.AvatarUrl);
  279. if (!string.IsNullOrEmpty(groupDetail.QRCoder))
  280. groupDetail.QRCoder = StringUtils.AddDomain(groupDetail.QRCoder);
  281. var sql =
  282. "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";
  283. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  284. var database = new Database(databaseType, _connectionString);
  285. var connection = database.GetConnection();
  286. var result =
  287. await connection
  288. .QueryAsync<GroupUserListResult, User, Department, GroupUserListResult>(sql,
  289. (groupUserListResult, user, department) =>
  290. {
  291. groupUserListResult.DepartmentName = department.Name;
  292. groupUserListResult.Name = user.Name;
  293. groupUserListResult.AvatarUrl = StringUtils.AddDomainMin(user.AvatarUrl);
  294. return groupUserListResult;
  295. }, new { groupId = groupDetail.Id }, splitOn: "Name");
  296. var groupDetailResult = _mapper.Map<GroupDetailResult>(groupDetail);
  297. groupDetailResult.GroupUserListResult = result;
  298. var groupUser = await _groupUserRepository.GetAsync(Q.Where(nameof(GroupUser.UserId), userId)
  299. .Where(nameof(GroupUser.Guid), guId));
  300. groupDetailResult.GroupUserRoleId = groupUser?.GroupUserRoleId ?? GroupUserRoleTyeConst.General;
  301. //获取当前用户的权限
  302. return groupDetailResult;
  303. }
  304. /// <summary>
  305. /// 获取用户未读取话题数量
  306. /// </summary>
  307. /// <param name="userId"></param>
  308. /// <param name="groupId"></param>
  309. /// <returns></returns>
  310. public async Task<int> GetUReadCountAsync(int userId, int groupId)
  311. {
  312. string sql =
  313. @"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";
  314. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  315. var database = new Database(databaseType, _connectionString);
  316. var connection = database.GetConnection();
  317. var result = await connection.ExecuteScalarAsync<int>(sql, new { userId, groupId });
  318. return result;
  319. }
  320. /// <summary>
  321. /// 获取小组的共享话题数量
  322. /// </summary>
  323. /// <param name="groupId"></param>
  324. /// <returns></returns>
  325. public async Task<int> SharingCountAsync(int groupId)
  326. {
  327. var sql =
  328. $"select count(1) from tede_group_user where GroupId={groupId}";
  329. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  330. var database = new Database(databaseType, _connectionString);
  331. var connection = database.GetConnection();
  332. var result = await connection.ExecuteScalarAsync<int>(sql, new { GroupId = groupId });
  333. return result;
  334. }
  335. public async Task<Entity.Group> GetAsync(int id)
  336. {
  337. return await _repository.GetAsync(id);
  338. }
  339. /// <summary>
  340. /// 是开启管理员同意加入
  341. /// </summary>
  342. /// <param name="groupId"></param>
  343. /// <returns></returns>
  344. public async Task<bool> SetGroupIsAdminAsync(int groupId)
  345. {
  346. var group = await GetAsync(groupId);
  347. return await _repository.UpdateAsync(Q.Set(nameof(Entity.Group.IsAdmin), !group.IsAdmin)
  348. .Where(nameof(Entity.Group.Id), groupId)) > 0;
  349. }
  350. /// <summary>
  351. /// 是否禁言
  352. /// </summary>
  353. /// <param name="groupId"></param>
  354. /// <returns></returns>
  355. public async Task<bool> SetGroupIsWordsAsync(int groupId)
  356. {
  357. var group = await GetAsync(groupId);
  358. return await _repository.UpdateAsync(Q.Set(nameof(Entity.Group.IsWords), !group.IsWords)
  359. .Where(nameof(Entity.Group.Id), groupId)) > 0;
  360. }
  361. public async Task<List<JobGroupResult>> ElasticSearchGroup()
  362. {
  363. 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";
  364. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  365. var database = new Database(databaseType, _connectionString);
  366. var connection = database.GetConnection();
  367. var items = await connection
  368. .QueryAsync<JobGroupResult, Entity.Group, User, JobGroupResult>(sql,
  369. (jobGroupResult, group, user) =>
  370. {
  371. jobGroupResult.MiddleId = jobGroupResult.Id;
  372. jobGroupResult.Id = group.Id;
  373. jobGroupResult.Name = group != null ? group.Name : "";
  374. jobGroupResult.AvatarUrl = group != null ? group.AvatarUrl : "";
  375. return jobGroupResult;
  376. },
  377. splitOn: "Id,Id,Name");
  378. return items.ToList();
  379. }
  380. /// <summary>
  381. /// 根据广场类别查询小组
  382. /// </summary>
  383. /// <param name="categoryId"></param>
  384. /// <returns></returns>
  385. public async Task<IEnumerable<Entity.Group>> GetAllAsync(int categoryId)
  386. {
  387. return await _repository.GetAllAsync(Q.Where(nameof(Entity.Group.GroupCategroyId), categoryId));
  388. }
  389. /// <summary>
  390. /// 用户小组列表
  391. /// </summary>
  392. /// <param name="userId"></param>
  393. /// <returns></returns>
  394. public async Task<IEnumerable<UserGroupList>> GetAllByUserIdAsync(int userId)
  395. {
  396. string sql = $@"SELECT
  397. Id,
  398. Name,
  399. AvatarUrl,
  400. (SELECT
  401. COUNT(1)
  402. FROM
  403. tede_group_user
  404. WHERE
  405. GroupId = a.Id) AS UserCount
  406. FROM
  407. tede_group a
  408. WHERE
  409. a.id IN (SELECT
  410. GroupId
  411. FROM
  412. ccpph_tede.tede_group_user
  413. WHERE
  414. UserId = {userId})";
  415. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  416. var database = new Database(databaseType, _connectionString);
  417. var connection = database.GetConnection();
  418. var items = await connection
  419. .QueryAsync<UserGroupList>(sql);
  420. foreach (var item in items)
  421. {
  422. item.AvatarUrl = StringUtils.AddDomain(item.AvatarUrl);
  423. }
  424. return items;
  425. }
  426. }
  427. }