GroupRepository.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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 != null ? groupUser.GroupUserRoleId : 0;
  237. groupDetailResult.IsUDisturb = groupUser != null ? groupUser.IsUDisturb : false;
  238. groupDetailResult.IsAdmin = groupUser != null ? groupUser.UserId == groupDetailResult.UserId : false;
  239. groupDetailResult.IsUser = groupUser != null ? groupUser.UserId == request.UserId : false;
  240. groupDetailResult.CreatedDate = groupDetail.CreatedDate;
  241. return groupDetailResult;
  242. }
  243. /// <summary>
  244. /// 搜索小组成员
  245. /// </summary>
  246. /// <param name="request"></param>
  247. /// <returns></returns>
  248. public async Task<IEnumerable<GroupUserListResult>> SearchGroupUserAsync(TopicDetailListRequest request)
  249. {
  250. string sql =
  251. $@"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
  252. tede_department c ON b.DepartmentId = c.Id
  253. WHERE a.GroupId = {request.GroupId} and b.Name like '%{request.Key}%'";
  254. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  255. var database = new Database(databaseType, _connectionString);
  256. var connection = database.GetConnection();
  257. var result =
  258. await connection
  259. .QueryAsync<GroupUserListResult, User, Department, GroupUserListResult>(sql,
  260. (groupUserListResult, user, department) =>
  261. {
  262. groupUserListResult.DepartmentName = department.Name;
  263. groupUserListResult.Name = user.Name;
  264. groupUserListResult.AvatarUrl = StringUtils.AddDomainMin(user.AvatarUrl);
  265. return groupUserListResult;
  266. }, splitOn: "Name");
  267. return result;
  268. }
  269. /// <summary>
  270. /// 获取小组详情
  271. /// </summary>
  272. /// <param name="guId"></param>
  273. /// <param name="userId"></param>
  274. /// <returns></returns>
  275. public async Task<GroupDetailResult> GroupDetailByGuIdAsync(string guId, int userId)
  276. {
  277. var groupDetail = await _repository.GetAsync(Q.Where(nameof(Entity.Group.Guid), guId));
  278. if (groupDetail == null)
  279. throw new BusinessException("小组不存在");
  280. if (!string.IsNullOrEmpty(groupDetail.AvatarUrl))
  281. groupDetail.AvatarUrl = StringUtils.AddDomainMin(groupDetail.AvatarUrl);
  282. if (!string.IsNullOrEmpty(groupDetail.QRCoder))
  283. groupDetail.QRCoder = StringUtils.AddDomain(groupDetail.QRCoder);
  284. var sql =
  285. "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";
  286. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  287. var database = new Database(databaseType, _connectionString);
  288. var connection = database.GetConnection();
  289. var result =
  290. await connection
  291. .QueryAsync<GroupUserListResult, User, Department, GroupUserListResult>(sql,
  292. (groupUserListResult, user, department) =>
  293. {
  294. groupUserListResult.DepartmentName = department.Name;
  295. groupUserListResult.Name = user.Name;
  296. groupUserListResult.AvatarUrl = StringUtils.AddDomainMin(user.AvatarUrl);
  297. return groupUserListResult;
  298. }, new { groupId = groupDetail.Id }, splitOn: "Name");
  299. var groupDetailResult = _mapper.Map<GroupDetailResult>(groupDetail);
  300. groupDetailResult.GroupUserListResult = result;
  301. var groupUser = await _groupUserRepository.GetAsync(Q.Where(nameof(GroupUser.UserId), userId)
  302. .Where(nameof(GroupUser.Guid), guId));
  303. groupDetailResult.GroupUserRoleId = groupUser?.GroupUserRoleId ?? GroupUserRoleTyeConst.General;
  304. //获取当前用户的权限
  305. return groupDetailResult;
  306. }
  307. /// <summary>
  308. /// 获取用户未读取话题数量
  309. /// </summary>
  310. /// <param name="userId"></param>
  311. /// <param name="groupId"></param>
  312. /// <returns></returns>
  313. public async Task<int> GetUReadCountAsync(int userId, int groupId)
  314. {
  315. string sql =
  316. @"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";
  317. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  318. var database = new Database(databaseType, _connectionString);
  319. var connection = database.GetConnection();
  320. var result = await connection.ExecuteScalarAsync<int>(sql, new { userId, groupId });
  321. return result;
  322. }
  323. /// <summary>
  324. /// 获取小组的共享话题数量
  325. /// </summary>
  326. /// <param name="groupId"></param>
  327. /// <returns></returns>
  328. public async Task<int> SharingCountAsync(int groupId)
  329. {
  330. var sql =
  331. $"select count(1) from tede_group_user where GroupId={groupId}";
  332. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  333. var database = new Database(databaseType, _connectionString);
  334. var connection = database.GetConnection();
  335. var result = await connection.ExecuteScalarAsync<int>(sql, new { GroupId = groupId });
  336. return result;
  337. }
  338. public async Task<Entity.Group> GetAsync(int id)
  339. {
  340. return await _repository.GetAsync(id);
  341. }
  342. /// <summary>
  343. /// 是开启管理员同意加入
  344. /// </summary>
  345. /// <param name="groupId"></param>
  346. /// <returns></returns>
  347. public async Task<bool> SetGroupIsAdminAsync(int groupId)
  348. {
  349. var group = await GetAsync(groupId);
  350. return await _repository.UpdateAsync(Q.Set(nameof(Entity.Group.IsAdmin), !group.IsAdmin)
  351. .Where(nameof(Entity.Group.Id), groupId)) > 0;
  352. }
  353. /// <summary>
  354. /// 是否禁言
  355. /// </summary>
  356. /// <param name="groupId"></param>
  357. /// <returns></returns>
  358. public async Task<bool> SetGroupIsWordsAsync(int groupId)
  359. {
  360. var group = await GetAsync(groupId);
  361. return await _repository.UpdateAsync(Q.Set(nameof(Entity.Group.IsWords), !group.IsWords)
  362. .Where(nameof(Entity.Group.Id), groupId)) > 0;
  363. }
  364. public async Task<List<JobGroupResult>> ElasticSearchGroup()
  365. {
  366. 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";
  367. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  368. var database = new Database(databaseType, _connectionString);
  369. var connection = database.GetConnection();
  370. var items = await connection
  371. .QueryAsync<JobGroupResult, Entity.Group, User, JobGroupResult>(sql,
  372. (jobGroupResult, group, user) =>
  373. {
  374. jobGroupResult.MiddleId = jobGroupResult.Id;
  375. jobGroupResult.Id = group.Id;
  376. jobGroupResult.Name = group != null ? group.Name : "";
  377. jobGroupResult.AvatarUrl = group != null ? group.AvatarUrl : "";
  378. return jobGroupResult;
  379. },
  380. splitOn: "Id,Id,Name");
  381. return items.ToList();
  382. }
  383. /// <summary>
  384. /// 根据广场类别查询小组
  385. /// </summary>
  386. /// <param name="categoryId"></param>
  387. /// <returns></returns>
  388. public async Task<IEnumerable<Entity.Group>> GetAllAsync(int categoryId)
  389. {
  390. var sql = $@"SELECT
  391. *,
  392. (SELECT
  393. COUNT(1)
  394. FROM
  395. tede_group_user
  396. WHERE
  397. GroupId = a.Id) AS UserCount,
  398. (SELECT
  399. COUNT(1)
  400. FROM
  401. tede_topic
  402. WHERE
  403. GroupId = a.Id) AS GroupArticleCount
  404. FROM
  405. tede_group a
  406. WHERE
  407. a.GroupCategroyId = {categoryId}";
  408. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  409. var database = new Database(databaseType, _connectionString);
  410. var connection = database.GetConnection();
  411. var result = await connection.QueryAsync<Entity.Group>(sql);
  412. //return await _repository.GetAllAsync(Q.Where(nameof(Entity.Group.GroupCategroyId), categoryId));
  413. return result;
  414. }
  415. /// <summary>
  416. /// 用户小组列表
  417. /// </summary>
  418. /// <param name="userId"></param>
  419. /// <returns></returns>
  420. public async Task<IEnumerable<UserGroupList>> GetAllByUserIdAsync(int userId)
  421. {
  422. string sql = $@"SELECT
  423. Id,
  424. Name,
  425. AvatarUrl,
  426. (SELECT
  427. COUNT(1)
  428. FROM
  429. tede_group_user
  430. WHERE
  431. GroupId = a.Id) AS UserCount
  432. FROM
  433. tede_group a
  434. WHERE
  435. a.id IN (SELECT
  436. GroupId
  437. FROM
  438. ccpph_tede.tede_group_user
  439. WHERE
  440. UserId = {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<UserGroupList>(sql);
  446. foreach (var item in items)
  447. {
  448. item.AvatarUrl = StringUtils.AddDomain(item.AvatarUrl);
  449. }
  450. return items;
  451. }
  452. }
  453. }