GroupRepository.cs 24 KB

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