GroupListController.cs 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184
  1. using Azure.Cosmos;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.Extensions.Options;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.IdentityModel.Tokens.Jwt;
  8. using System.Linq;
  9. using System.Text.Json;
  10. using System.Threading.Tasks;
  11. using TEAMModelOS.Models;
  12. using TEAMModelOS.SDK.Models;
  13. using TEAMModelOS.SDK;
  14. using TEAMModelOS.SDK.DI;
  15. using TEAMModelOS.SDK.Extension;
  16. using Azure;
  17. using TEAMModelOS.SDK.Models.Cosmos.Common;
  18. using Azure.Messaging.ServiceBus;
  19. using Microsoft.Extensions.Configuration;
  20. using TEAMModelOS.Filter;
  21. using HTEXLib.COMM.Helpers;
  22. using System.Text;
  23. using Microsoft.AspNetCore.Authorization;
  24. using Microsoft.Extensions.Hosting;
  25. using OpenXmlPowerTools;
  26. using TEAMModelOS.SDK.Models.Dtos;
  27. using Microsoft.AspNetCore.Hosting;
  28. using Azure.Core;
  29. using static TEAMModelOS.SDK.Services.ActivityStudentService;
  30. using static TEAMModelOS.SDK.GroupListService;
  31. using DocumentFormat.OpenXml.Bibliography;
  32. namespace TEAMModelOS.Controllers
  33. {
  34. [ProducesResponseType(StatusCodes.Status200OK)]
  35. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  36. [Route("grouplist")]
  37. [ApiController]
  38. public class GroupListController : ControllerBase
  39. {
  40. private AzureCosmosFactory _azureCosmos;
  41. private readonly DingDing _dingDing;
  42. private readonly Option _option;
  43. private readonly AzureServiceBusFactory _serviceBus;
  44. private readonly AzureRedisFactory _azureRedis;
  45. private readonly AzureStorageFactory _azureStorage;
  46. private readonly CoreAPIHttpService _coreAPIHttpService;
  47. private readonly IWebHostEnvironment _environment;
  48. private const string SummarySql = " c.id,c.code,c.name,c.no,c.periodId,c.scope,c.school,c.creatorId,c.type,c.year,c.tcount,c.scount,c.leader ,c.froms ,c.joinLock ,c.review,c.limitCount ,c.expire,c.qrcodeExpire,c.qrcodeDays ,c.grades ";
  49. public IConfiguration _configuration { get; set; }
  50. public GroupListController(IWebHostEnvironment environment, CoreAPIHttpService coreAPIHttpService, AzureCosmosFactory azureCosmos, DingDing dingDing, IOptionsSnapshot<Option> option,
  51. AzureServiceBusFactory serviceBus, AzureStorageFactory azureStorage, IConfiguration configuration, AzureRedisFactory azureRedis)
  52. {
  53. _azureCosmos = azureCosmos;
  54. _dingDing = dingDing;
  55. _option = option?.Value;
  56. _serviceBus = serviceBus;
  57. _configuration = configuration;
  58. _azureStorage = azureStorage;
  59. _coreAPIHttpService = coreAPIHttpService;
  60. _environment = environment;
  61. _azureRedis=azureRedis;
  62. }
  63. //学生获取自己已经加入的名单。
  64. [ProducesDefaultResponseType]
  65. [HttpPost("get-student-joined-grouplist")]
  66. [Authorize(Roles = "IES")]
  67. [AuthToken(Roles = "admin,teacher,student")]
  68. public async Task<IActionResult> GetMyCourseAndGroupList(JsonElement json)
  69. {
  70. var (userid, _name, _picture, school) = HttpContext.GetAuthTokenInfo();
  71. var client = _azureCosmos.GetCosmosClient();
  72. object scope = null;
  73. HttpContext?.Items.TryGetValue("Scope", out scope);
  74. int memberType = 2;
  75. if ($"{scope}".Equals(Constant.ScopeStudent))
  76. {
  77. memberType = 2;
  78. // Student student = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<Student>(userid, new PartitionKey($"Base-{school}"));
  79. }
  80. if ($"{scope}".Equals(Constant.ScopeTmdUser))
  81. {
  82. memberType = 1;
  83. }
  84. if ($"{scope}".Equals(Constant.ScopeTeacher))
  85. {
  86. memberType = 1;
  87. }
  88. List<GroupListGrp> groups = await GroupListService.GetMemberInGroupList(_coreAPIHttpService, client, _dingDing, userid, memberType, school, new List<string> { "class", "teach" });
  89. return Ok(new { groups = groups });
  90. }
  91. /// <summary>
  92. /// 扫码加入名单
  93. /// </summary>
  94. /// <param name="json"></param>
  95. /// <returns></returns>
  96. [ProducesDefaultResponseType]
  97. [HttpPost("scan-code-join-list")]
  98. public async Task<IActionResult> ScanCodeJoinList(JsonElement json)
  99. {
  100. if (!json.TryGetProperty("stuListNo", out JsonElement _stuListNo)) return BadRequest();
  101. json.TryGetProperty("school", out JsonElement school);
  102. var client = _azureCosmos.GetCosmosClient();
  103. json.TryGetProperty("id_token", out JsonElement id_token);
  104. var jwt = new JwtSecurityToken(id_token.GetString());
  105. var id = jwt.Payload.Sub;
  106. jwt.Payload.TryGetValue("name", out object name);
  107. jwt.Payload.TryGetValue("lang", out object lang);
  108. jwt.Payload.TryGetValue("picture", out object picture);
  109. try
  110. {
  111. TmdUser tmduser = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<TmdUser>(id, new PartitionKey("Base"));
  112. }
  113. catch (CosmosException ex)
  114. {
  115. if (ex.Status == 404)
  116. {
  117. //如果沒有,則初始化Teacher基本資料到Cosmos
  118. TmdUser tmduser = new TmdUser
  119. {
  120. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  121. id = id,
  122. pk = "Base",
  123. code = "Base",
  124. name = name?.ToString(),
  125. picture = picture?.ToString(),
  126. //创建账号并第一次登录IES5则默认赠送1G
  127. defaultSchool = null,
  128. schools = new List<TmdUser.School>(),
  129. lang= lang?.ToString(),
  130. };
  131. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync<TmdUser>(tmduser, new PartitionKey("Base"));
  132. }
  133. }
  134. int year = DateTimeOffset.UtcNow.Year;
  135. (int status, GroupList stuList, Member member) data = await GroupListService.CodeJoinList(client, _azureRedis, $"{_stuListNo}", id, type: 1, $"{school}", year, $"{name}", $"{picture}", $"{lang}");
  136. //没有TmdUser时
  137. if (data.status == 0)
  138. {
  139. await GroupListService.UpsertList(data.stuList, _azureCosmos, _configuration, _serviceBus);
  140. List<string> ids = new List<string>();
  141. if (data.stuList.scope.Equals("private") && !string.IsNullOrEmpty(data.stuList.creatorId))
  142. {
  143. ids.Add(data.stuList.creatorId);
  144. }
  145. else if (data.stuList.scope.Equals("school") && !string.IsNullOrEmpty(data.stuList.school))
  146. {
  147. //通知管理员
  148. string sql = "select distinct value(c.id) from c where array_contains(c.roles,'admin')";
  149. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<string>(queryText: sql,
  150. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Teacher-{school}") }))
  151. {
  152. ids.Add(item);
  153. }
  154. }
  155. if (ids.IsNotEmpty())
  156. {
  157. string bizcode = "scan-join";
  158. string sql = $"select c.id, c.name ,c.lang as code from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))})";
  159. List<IdNameCode> idNameCodes = new List<IdNameCode>();
  160. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  161. .GetItemQueryIterator<IdNameCode>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  162. {
  163. idNameCodes.Add(item);
  164. }
  165. // _coreAPIHttpService.PushNotify(idNameCodes, $"scan-join_groupList", Constant.NotifyType_IES5_Course, new Dictionary<string, object> { { "tmdid", id }, { "tmdname", name }, { "groupListName", data.stuList.name }, { "groupListId", data.stuList.id } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
  166. }
  167. return Ok(new { data.stuList, data.status });
  168. }
  169. else
  170. {
  171. return Ok(new { data.status });
  172. }
  173. }
  174. /// <summary>
  175. /// 根据邀请码加入名单
  176. /// </summary>
  177. /// <param name="json"></param>
  178. /// <returns></returns>
  179. [ProducesDefaultResponseType]
  180. [AuthToken(Roles = "admin,teacher,student")]
  181. [HttpPost("input-code-join-list")]
  182. [Authorize(Roles = "IES")]
  183. public async Task<IActionResult> InputCodeJoinList(JsonElement json)
  184. {
  185. string head_lang = _option.Location.Contains("China") ? "zh-cn" : "zh-tw";
  186. if (HttpContext.Request.Headers.TryGetValue("lang", out var _lang))
  187. {
  188. head_lang = $"{_lang}";
  189. }
  190. if (!json.TryGetProperty("stuListNo", out JsonElement _stuListNo)) return BadRequest();
  191. var (userid, _name, _picture, school) = HttpContext.GetAuthTokenInfo();
  192. object scope = null;
  193. int type = 0;
  194. string no = null;
  195. var client = _azureCosmos.GetCosmosClient();
  196. HttpContext?.Items.TryGetValue("Scope", out scope);
  197. int year = DateTimeOffset.UtcNow.Year;
  198. if ($"{scope}".Equals(Constant.ScopeStudent))
  199. {
  200. type = 2;
  201. Student student = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<Student>(userid, new PartitionKey($"Base-{school}"));
  202. no = student.no;
  203. year = student.year;
  204. }
  205. if ($"{scope}".Equals(Constant.ScopeTmdUser))
  206. {
  207. type = 1;
  208. }
  209. if ($"{scope}".Equals(Constant.ScopeTeacher))
  210. {
  211. type = 1;
  212. }
  213. (int status, GroupList stuList, Member member) data = await GroupListService.CodeJoinList(client, _azureRedis, $"{_stuListNo}", userid, type, school, year, _name, _picture, head_lang);
  214. if (data.status == 0)
  215. {
  216. await GroupListService.UpsertList(data.stuList, _azureCosmos, _configuration, _serviceBus);
  217. List<string> ids = new List<string>();
  218. if (data.stuList.scope.Equals("private") && !string.IsNullOrEmpty(data.stuList.creatorId))
  219. {
  220. ids.Add(data.stuList.creatorId);
  221. }
  222. else if (data.stuList.scope.Equals("school") && !string.IsNullOrEmpty(data.stuList.school))
  223. {
  224. //通知管理员
  225. string sql = "select distinct value(c.id) from c where array_contains(c.roles,'admin')";
  226. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<string>(queryText: sql,
  227. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Teacher-{school}") }))
  228. {
  229. ids.Add(item);
  230. }
  231. }
  232. if (ids.IsNotEmpty())
  233. {
  234. string bizcode = "scan-join";
  235. string sql = $"select c.id, c.name ,c.lang as code from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))})";
  236. List<IdNameCode> idNameCodes = new List<IdNameCode>();
  237. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  238. .GetItemQueryIterator<IdNameCode>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  239. {
  240. idNameCodes.Add(item);
  241. }
  242. _coreAPIHttpService.PushNotify(idNameCodes, $"{bizcode}_school", Constant.NotifyType_IES5_Course,
  243. new Dictionary<string, object> { { "tmdid", userid }, { "tmdname", _name }, { "groupListName", data.stuList.name }, { "groupListId", data.stuList.id } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
  244. }
  245. return Ok(new { data.stuList, data.status });
  246. }
  247. else
  248. {
  249. return Ok(new { data.status });
  250. }
  251. }
  252. /// <summary>
  253. /// 获取名单的tags
  254. /// </summary>
  255. /// <param name="json"></param>
  256. /// <returns></returns>
  257. [ProducesDefaultResponseType]
  258. [AuthToken(Roles = "admin,teacher,student")]
  259. [HttpPost("get-grouplist-tags")]
  260. [Authorize(Roles = "IES")]
  261. public async Task<IActionResult> GetGrouplistTags(JsonElement json)
  262. {
  263. var client = _azureCosmos.GetCosmosClient();
  264. var (id, _, _, school) = HttpContext.GetAuthTokenInfo();
  265. object scope = null;
  266. StringBuilder sql = new StringBuilder($"SELECT {SummarySql} ,A1.tag FROM c " +
  267. $" join A1 in c. members where A1.id='{id}' and A1.tag<>null ");
  268. HttpContext?.Items.TryGetValue("Scope", out scope);
  269. if (!string.IsNullOrEmpty(school) && $"{scope}".Equals(Constant.ScopeStudent))
  270. {
  271. sql.Append($" and A1.code='{school}'");
  272. }
  273. List<dynamic> groupLists = new List<dynamic>();
  274. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  275. GetItemQueryIterator<dynamic>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
  276. {
  277. groupLists.Add(item);
  278. }
  279. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").
  280. GetItemQueryIterator<dynamic>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList") }))
  281. {
  282. groupLists.Add(item);
  283. }
  284. return Ok(new { groupLists });
  285. }
  286. /// <summary>
  287. /// 获取发布活动的名单
  288. /// </summary>
  289. /// <param name="json"></param>
  290. /// <returns></returns>
  291. [ProducesDefaultResponseType]
  292. [HttpPost("get-activity-grouplist")]
  293. #if !DEBUG
  294. [AuthToken(Roles = "teacher,admin,student")]
  295. [Authorize(Roles = "IES")]
  296. #endif
  297. public async Task<IActionResult> GetActivityGrouplist(JsonElement json)
  298. {
  299. var client = _azureCosmos.GetCosmosClient();
  300. json.TryGetProperty("tmdid", out JsonElement tmdid);
  301. json.TryGetProperty("schoolId", out JsonElement schoolId);
  302. if (!json.TryGetProperty("opt", out JsonElement opt)) { return BadRequest(); }
  303. json.TryGetProperty("periodId", out JsonElement periodId);
  304. long nowtime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  305. List<GroupListGrp> groupLists = new List<GroupListGrp>();
  306. switch (true)
  307. {
  308. //我管理的
  309. case bool when $"{opt}".Equals("manage", StringComparison.OrdinalIgnoreCase):
  310. //包含,学校的行政班,教学班
  311. json.TryGetProperty("type", out JsonElement _type);
  312. List<string> types = null;
  313. if (_type.ValueKind.Equals(JsonValueKind.Array))
  314. {
  315. types = _type.ToObject<List<string>>();
  316. }
  317. else if (_type.ValueKind.Equals(JsonValueKind.String))
  318. {
  319. types = new List<string> { $"{_type}" };
  320. }
  321. if (types.IsEmpty() || types.Contains("class"))
  322. {
  323. StringBuilder classsql = new StringBuilder($"SELECT c.id,c.name,c.periodId ,c.year,c.no FROM c where ( c.graduate = 0 or IS_DEFINED(c.graduate) = false )");
  324. if (!string.IsNullOrEmpty($"{periodId}"))
  325. {
  326. classsql.Append($" and c.periodId='{periodId}' ");
  327. }
  328. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ClassInfo>(queryText: classsql.ToString(),
  329. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  330. {
  331. int scount = 0;
  332. HashSet<string> groupNames = new HashSet<string>();
  333. string gpsql = $"SELECT distinct c.id, c.groupId,c.groupName FROM c where c.classId='{item.id}' ";
  334. await foreach (var gp in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: gpsql,
  335. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{schoolId}") }))
  336. {
  337. if (!string.IsNullOrWhiteSpace(gp.groupName))
  338. {
  339. groupNames.Add(gp.groupName);
  340. }
  341. scount += 1;
  342. }
  343. ///行政班(学生搜寻classId动态返回)class
  344. GroupListGrp group = new GroupListGrp
  345. {
  346. id = item.id,
  347. code = $"GroupList-{schoolId}",
  348. name = item.name,
  349. periodId = item.periodId,
  350. scope = "school",
  351. school = $"{schoolId}",
  352. type = "class",
  353. year = item.year,
  354. expire=0,
  355. groupName = groupNames,
  356. scount= scount
  357. };
  358. groupLists.Add(group);
  359. }
  360. }
  361. if (types.IsEmpty() || types.Contains("teach"))
  362. {
  363. //教学班
  364. StringBuilder teachsql = new StringBuilder($" SELECT distinct value(c) FROM c where c.type='teach' and ( c.expire = 0 or IS_DEFINED(c.expire) = false or c.expire >={nowtime} ) ");
  365. if (!string.IsNullOrEmpty($"{periodId}"))
  366. {
  367. teachsql.Append($" and c.periodId='{periodId}'");
  368. }
  369. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  370. GetItemQueryIterator<GroupList>(queryText: teachsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{schoolId}") }))
  371. {
  372. HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  373. groupLists.Add(new GroupListGrp(item, groupName));
  374. }
  375. }
  376. if (types.IsEmpty() || types.Contains("research"))
  377. {
  378. //教研组
  379. StringBuilder researchsql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='research'");
  380. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  381. GetItemQueryIterator<GroupList>(queryText: researchsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{schoolId}") }))
  382. {
  383. HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  384. groupLists.Add(new GroupListGrp(item, groupName));
  385. }
  386. }
  387. if (types.IsEmpty() || types.Contains("yxtrain"))
  388. {
  389. //研修名单
  390. StringBuilder yxtrainsql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='yxtrain'");
  391. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  392. GetItemQueryIterator<GroupList>(queryText: yxtrainsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{schoolId}") }))
  393. {
  394. HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  395. groupLists.Add(new GroupListGrp(item, groupName));
  396. }
  397. }
  398. return Ok(new { groupLists });
  399. case bool when $"{opt}".Equals("teach", StringComparison.OrdinalIgnoreCase):
  400. //我执教的
  401. //从学校的课程和个人课程搜寻与我相关的课程对应的名单。
  402. List<TeachCourse> teachCourses = new List<TeachCourse>();
  403. if (!string.IsNullOrEmpty($"{schoolId}"))
  404. {
  405. var schoolQuery = new StringBuilder($"select distinct c.name,c.id, c.scope,c.subject,c.period,A0 schedule from c join A0 in c.schedule where A0.teacherId = '{tmdid}'");
  406. if (!string.IsNullOrEmpty($"{periodId}"))
  407. {
  408. schoolQuery.Append($" and c.period.id='{periodId}' ");
  409. }
  410. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  411. GetItemQueryIterator<TeachCourse>(queryText: schoolQuery.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{schoolId}") }))
  412. {
  413. teachCourses.Add(item);
  414. }
  415. }
  416. var query = new StringBuilder($"select distinct c.name,c.id, c.scope,c.subject,c.period,A0 schedule from c join A0 in c.schedule where A0.teacherId = '{tmdid}'");
  417. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").
  418. GetItemQueryIterator<TeachCourse>(queryText: query.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{tmdid}") }))
  419. {
  420. teachCourses.Add(item);
  421. }
  422. var classIds = teachCourses.Select(x => x.schedule).Where(y => !string.IsNullOrEmpty(y.classId)).Select(x => x.classId).Distinct().ToList();
  423. var schedule = teachCourses.Where(y => !string.IsNullOrEmpty(y.schedule.stulist)).Distinct().ToList();
  424. //var schedule = teachCourses.Select(x => new { schedule = x.schedule.Where(mm=>!string.IsNullOrEmpty(mm.stulist)), scope = x.scope }).ToList();
  425. if (classIds.IsNotEmpty())
  426. {
  427. string insql = string.Join(",", classIds.Select(x => $"'{x}'"));
  428. query = new StringBuilder($"SELECT c.id,c.name,c.periodId ,c.year FROM c where c.id in ({insql}) and ( c.graduate = 0 or IS_DEFINED(c.graduate) = false) ");
  429. ///行政班(学生搜寻classId动态返回)class
  430. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ClassInfo>(queryText: query.ToString(),
  431. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{schoolId}") }))
  432. {
  433. HashSet<string> groupNames = new HashSet<string>();
  434. string gpsql = $"SELECT distinct c.groupId,c.groupName FROM c where c.classId='{item.id}'and c.groupName <>null";
  435. await foreach (var gp in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: gpsql,
  436. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{schoolId}") }))
  437. {
  438. groupNames.Add(gp.groupName);
  439. }
  440. GroupListGrp group = new GroupListGrp
  441. {
  442. id = item.id,
  443. code = $"GroupList-{schoolId}",
  444. name = item.name,
  445. periodId = item.periodId,
  446. scope = "school",
  447. school = $"{schoolId}",
  448. type = "class",
  449. expire=0,
  450. year = item.year,
  451. groupName = groupNames
  452. };
  453. groupLists.Add(group);
  454. }
  455. }
  456. if (schedule.IsNotEmpty())
  457. {
  458. var privateList = schedule.Where(x => x.scope.Equals("private")).Select(x => x.schedule.stulist).Distinct();
  459. if (privateList.Count() > 0)
  460. {
  461. string insql = string.Join(",", privateList.Select(x => $"'{x}'"));
  462. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<GroupList>(queryText: $"select distinct {SummarySql} from c where c.id in ({insql})",
  463. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  464. {
  465. HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  466. groupLists.Add(new GroupListGrp(item, groupName));
  467. }
  468. }
  469. var schoolList = schedule.Where(x => x.scope.Equals("school")).Select(x => x.schedule.stulist).Distinct();
  470. if (schoolList.Count() > 0)
  471. {
  472. List<GroupListDto> groups = new List<GroupListDto>();
  473. string insql = string.Join(",", schoolList.Select(x => $"'{x}'"));
  474. //我教的学校教学班,如果有过期的教学班则不返回
  475. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupList>(queryText: $"select distinct {SummarySql} from c where c.id in ({insql}) and ( c.expire = 0 or IS_DEFINED(c.expire) = false or c.expire >={nowtime} ) ",
  476. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{schoolId}") }))
  477. {
  478. HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  479. groupLists.Add(new GroupListGrp(item, groupName));
  480. }
  481. }
  482. }
  483. List<CourseGroupList> courseGroups = new List<CourseGroupList>();
  484. teachCourses.GroupBy(y => (y.id, y.name, y.scope, y.period.name, y.period.id, y.subject.name, y.subject.id)).ToList().ForEach(x =>
  485. {
  486. List<GroupListGrp> classIds = groupLists.Where(n => x.Where(m => !string.IsNullOrEmpty(m.schedule.classId)).Select(b => b.schedule.classId).Contains(n.id)).ToList();
  487. List<GroupListGrp> stulists = groupLists.Where(n => x.Where(m => !string.IsNullOrEmpty(m.schedule.stulist)).Select(b => b.schedule.stulist).Contains(n.id)).ToList();
  488. if (classIds == null)
  489. {
  490. classIds = new List<GroupListGrp>();
  491. }
  492. if (stulists != null)
  493. {
  494. classIds.AddRange(stulists);
  495. }
  496. CourseGroupList groupList = new CourseGroupList()
  497. {
  498. scope = x.Key.Item3,
  499. subject = x.Key.Item6,
  500. subjectId = x.Key.Item7,
  501. period = x.Key.Item4,
  502. periodId = x.Key.Item5,
  503. id = x.Key.Item1,
  504. name = x.Key.Item2,
  505. groups = classIds
  506. };
  507. courseGroups.Add(groupList);
  508. });
  509. return Ok(new { groupLists = courseGroups });
  510. case bool when $"{opt}".Equals("private", StringComparison.OrdinalIgnoreCase):
  511. //我个人的
  512. break;
  513. default:
  514. break;
  515. }
  516. return Ok(new { error = 1, msg = "参数异常" });
  517. }
  518. /// <summary>
  519. /// 根据任意名单id获取成员信息。
  520. /// </summary>
  521. /// <param name="json"></param>
  522. /// <returns></returns>
  523. [ProducesDefaultResponseType]
  524. [HttpPost("get-members-listids")]
  525. #if !DEBUG
  526. [AuthToken(Roles = "teacher,admin,student")]
  527. [Authorize(Roles = "IES")]
  528. #endif
  529. public async Task<IActionResult> GetMembersListids(JsonElement json)
  530. {
  531. var client = _azureCosmos.GetCosmosClient();
  532. if (!json.TryGetProperty("ids", out JsonElement ids)) return BadRequest();
  533. json.TryGetProperty("schoolId", out JsonElement schoolId);
  534. json.TryGetProperty("groupNames", out JsonElement groupNames);
  535. List<Dictionary<string, List<string>>> groupLists = new List<Dictionary<string, List<string>>>();
  536. if (groupNames.ValueKind.Equals(JsonValueKind.Array))
  537. {
  538. groupLists = groupNames.ToObject<List<Dictionary<string, List<string>>>>();
  539. }
  540. List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
  541. if (groupLists.Count > 0)
  542. {
  543. foreach (var gp in groupLists)
  544. {
  545. foreach (KeyValuePair<string, List<string>> pp in gp)
  546. {
  547. ps.Add((pp.Key, pp.Value));
  548. }
  549. }
  550. }
  551. List<string> listids = ids.ToObject<List<string>>();
  552. (List<RMember> members, List<RGroupList> groups) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, listids, $"{schoolId}", ps);
  553. return Ok(new { groups, members });
  554. }
  555. /// <summary>
  556. /// 根据任意名单id获取名单摘要信息。
  557. /// </summary>
  558. /// <param name="json"></param>
  559. /// <returns></returns>
  560. [ProducesDefaultResponseType]
  561. [HttpPost("get-grouplist-listids")]
  562. #if !DEBUG
  563. [AuthToken(Roles = "teacher,admin,student")]
  564. [Authorize(Roles = "IES")]
  565. #endif
  566. public async Task<IActionResult> GetGroupListListids(JsonElement json)
  567. {
  568. var client = _azureCosmos.GetCosmosClient();
  569. if (!json.TryGetProperty("ids", out JsonElement ids)) return BadRequest();
  570. json.TryGetProperty("schoolId", out JsonElement schoolId);
  571. List<string> listids = ids.ToObject<List<string>>();
  572. List<GroupListDto> groups = await GroupListService.GetGroupListByListids(client, _dingDing, listids, $"{schoolId}", SummarySql);
  573. return Ok(new { groups });
  574. }
  575. /// <summary>
  576. /// 获取名单和成员信息。
  577. /// </summary>
  578. /// <param name="json"></param>
  579. /// <returns></returns>
  580. [ProducesDefaultResponseType]
  581. [AuthToken(Roles = "teacher,admin,student")]
  582. [HttpPost("get-grouplists-members")]
  583. [Authorize(Roles = "IES")]
  584. public async Task<IActionResult> GetGrouplistsMembers(JsonElement json)
  585. {
  586. try
  587. {
  588. var client = _azureCosmos.GetCosmosClient();
  589. json.TryGetProperty("tmdid", out JsonElement _tmdid);
  590. json.TryGetProperty("schoolId", out JsonElement _schoolId);
  591. if (!json.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  592. if (!json.TryGetProperty("type", out JsonElement type)) return BadRequest();
  593. json.TryGetProperty("periodId", out JsonElement periodId);
  594. json.TryGetProperty("no", out JsonElement no);
  595. StringBuilder sql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='{type}'");
  596. List<RGroupList> groups = new List<RGroupList>();
  597. string tbname = "Teacher";
  598. string code = $"GroupList";
  599. if ($"{scope}".Equals("school", StringComparison.OrdinalIgnoreCase))
  600. {
  601. tbname = "School";
  602. code = $"GroupList-{_schoolId}";
  603. if (!string.IsNullOrEmpty($"{periodId}"))
  604. {
  605. sql.Append($" and c.periodId='{periodId}'");
  606. }
  607. if (!string.IsNullOrEmpty($"{no}"))
  608. {
  609. sql.Append($" and c.no='{no}'");
  610. }
  611. }
  612. else
  613. {
  614. sql.Append($" and c.creatorId='{_tmdid}'");
  615. }
  616. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, tbname).GetItemQueryIterator<RGroupList>(queryText: sql.ToString(),
  617. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
  618. {
  619. groups.Add(item);
  620. }
  621. (List<RGroupList> groupsData, List<RMember> members) = await GroupListService.GetGroupListMemberInfo(_coreAPIHttpService, client, $"{type}", groups, tbname, _dingDing, $"{_schoolId}");
  622. return Ok(new { groups = groupsData, members });
  623. }
  624. catch (CosmosException ex)
  625. {
  626. await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplists-members()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  627. }
  628. catch (Exception ex)
  629. {
  630. await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplists-members()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  631. }
  632. return Ok();
  633. }
  634. /// <summary>
  635. /// 获取名单列表
  636. /// </summary>
  637. /// <param name="json"></param>
  638. /// <returns></returns>
  639. [ProducesDefaultResponseType]
  640. [AuthToken(Roles = "teacher,admin,student")]
  641. [HttpPost("get-grouplists")]
  642. [Authorize(Roles = "IES")]
  643. public async Task<IActionResult> GetGrouplists(JsonElement json)
  644. {
  645. try
  646. {
  647. var client = _azureCosmos.GetCosmosClient();
  648. json.TryGetProperty("tmdid", out JsonElement _tmdid);
  649. json.TryGetProperty("schoolId", out JsonElement _schoolId);
  650. if (!json.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  651. if (!json.TryGetProperty("type", out JsonElement type)) return BadRequest();
  652. json.TryGetProperty("periodId", out JsonElement periodId);
  653. json.TryGetProperty("no", out JsonElement no);
  654. StringBuilder sql = new StringBuilder($"SELECT distinct {SummarySql} FROM c where c.type='{type}'");
  655. List<GroupListDto> groups = new List<GroupListDto>();
  656. string tbname = "Teacher";
  657. string code = $"GroupList";
  658. if ($"{scope}".Equals("school", StringComparison.OrdinalIgnoreCase))
  659. {
  660. tbname = "School";
  661. code = $"GroupList-{_schoolId}";
  662. if (!string.IsNullOrEmpty($"{periodId}"))
  663. {
  664. sql.Append($" and c.periodId='{periodId}'");
  665. }
  666. if (!string.IsNullOrEmpty($"{no}"))
  667. {
  668. sql.Append($" and c.no='{no}'");
  669. }
  670. }
  671. else
  672. {
  673. sql.Append($" and c.creatorId='{_tmdid}'");
  674. }
  675. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, tbname).GetItemQueryIterator<GroupListDto>(queryText: sql.ToString(),
  676. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
  677. {
  678. groups.Add(item);
  679. }
  680. return Ok(new { groups });
  681. }
  682. catch (CosmosException ex)
  683. {
  684. await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplists()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  685. }
  686. catch (Exception ex)
  687. {
  688. await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplists()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  689. }
  690. return Ok();
  691. }
  692. /// <summary>
  693. /// 根据id,code获取学校行政班信息和学生信息。用于维护学生基本信息。
  694. /// </summary>
  695. /// <param name="json"></param>
  696. /// <returns></returns>
  697. [ProducesDefaultResponseType]
  698. [AuthToken(Roles = "teacher,admin")]
  699. [HttpPost("get-classstudents-idcode")]
  700. [Authorize(Roles = "IES")]
  701. public async Task<IActionResult> GetClassStudentsIdcode(JsonElement json)
  702. {
  703. if (!json.TryGetProperty("id", out JsonElement id)) return BadRequest();
  704. if (!json.TryGetProperty("code", out JsonElement _code)) return BadRequest();
  705. try
  706. {
  707. var client = _azureCosmos.GetCosmosClient();
  708. Class clazz = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<Class>($"{id}", new PartitionKey($"Class-{_code}"));
  709. List<Student> students = new List<Student>();
  710. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: $"select value(c) from c where c.classId = '{clazz.id}'",
  711. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{_code}") }))
  712. {
  713. item.salt = null;
  714. item.pw = null;
  715. students.Add(item);
  716. }
  717. return Ok(new { classInfo = clazz, students = students });
  718. }
  719. catch (Exception ex)
  720. {
  721. return Ok(new { error = 404, msg = "班级不存在!" });
  722. }
  723. }
  724. //处理通用名单
  725. [ProducesDefaultResponseType]
  726. [AuthToken(Roles = "teacher,admin,student")]
  727. [HttpPost("get-grouplist-idcode")]
  728. [Authorize(Roles = "IES")]
  729. public async Task<IActionResult> GetGrouplistIdcode(JsonElement json)
  730. {
  731. RGroupList groupList = null;
  732. try
  733. {
  734. var client = _azureCosmos.GetCosmosClient();
  735. json.TryGetProperty("type", out JsonElement _type);
  736. json.TryGetProperty("code", out JsonElement _code);
  737. if (!json.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  738. if (!json.TryGetProperty("id", out JsonElement id)) return BadRequest();
  739. string tbname = $"{scope}".Equals("private") ? "Teacher" : "School";
  740. string code = "";
  741. if (string.IsNullOrEmpty($"{_type}") || !$"{_type}".Equals("class"))
  742. {
  743. if ($"{scope}".Equals("private"))
  744. {
  745. //私人名单
  746. code = "GroupList";
  747. }
  748. else
  749. {
  750. //学校自定义名单
  751. code = !code.StartsWith("GroupList-") ? $"GroupList-{_code}" : code;
  752. }
  753. groupList = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<RGroupList>($"{id}", new PartitionKey($"{code}"));
  754. }
  755. else if ($"{_type}".Equals("class"))
  756. {
  757. try
  758. {
  759. code = $"Class-{_code}";
  760. Class clazz = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<Class>($"{id}", new PartitionKey($"{code}"));
  761. if (clazz != null)
  762. {
  763. List<Student> students = new List<Student>();
  764. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: $"select value(c) from c where c.classId = '{clazz.id}'",
  765. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{_code}") }))
  766. {
  767. students.Add(item);
  768. }
  769. ///行政班(学生搜寻classId动态返回)class
  770. List<RMember> smembers = students.Where(x => x.classId.Equals(clazz.id)).Select(y => new RMember { id = y.id, code = $"{_code}", name = y.name, type = 2, picture = y.picture, no = y.no, classId = y.classId, groupId = y.groupId, groupName = y.groupName }).ToList();
  771. groupList = new RGroupList
  772. {
  773. id = clazz.id,
  774. code = $"GroupList-{clazz.school}",
  775. name = clazz.name,
  776. periodId = clazz.periodId,
  777. pk = "GroupList",
  778. year = clazz.year,
  779. expire = 0,
  780. school = clazz.school,
  781. scope = "school",
  782. type = "class",
  783. scount = smembers.Count,
  784. no = clazz.no,
  785. leader = clazz.teacher?.id,
  786. members = smembers,
  787. };
  788. }
  789. }
  790. catch (CosmosException ex)
  791. {
  792. await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplist-idcode()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  793. return Ok(new { groupList });
  794. }
  795. }
  796. (List<RGroupList> groupsData, List<RMember> members) = await GroupListService.GetGroupListMemberInfo(_coreAPIHttpService, client, $"{groupList.type}", new List<RGroupList> { groupList }, tbname, _dingDing, $"{_code}");
  797. groupList = groupsData.FirstOrDefault();
  798. }
  799. catch (CosmosException ex)
  800. {
  801. await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplist-idcode()\n{ex.Message}\n{ex.StackTrace}\n {json}", GroupNames.醍摩豆服務運維群組);
  802. return Ok(new { groupList });
  803. }
  804. catch (Exception ex)
  805. {
  806. await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplist-idcode()\n{ex.Message}\n{ex.StackTrace}\n{json}", GroupNames.醍摩豆服務運維群組);
  807. }
  808. return Ok(new { groupList });
  809. }
  810. /// <summary>
  811. /// 保存或更新通用名单
  812. /// </summary>
  813. /// <param name="json"></param>
  814. /// <returns></returns>
  815. [ProducesDefaultResponseType]
  816. [AuthToken(Roles = "teacher,admin")]
  817. [HttpPost("upsert-grouplist")]
  818. #if !DEBUG
  819. [Authorize(Roles = "IES")]
  820. #endif
  821. public async Task<IActionResult> UpsertGroupList(JsonElement json)
  822. {
  823. GroupList list = json.ToObject<GroupList>();
  824. try
  825. {
  826. var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
  827. if (string.IsNullOrEmpty(list.type))
  828. {
  829. return BadRequest();
  830. }
  831. list.year = list.year > 0 ? list.year : DateTimeOffset.UtcNow.Year;
  832. list.ttl = -1;
  833. list.creatorId = userid;
  834. list.school = string.IsNullOrEmpty(list.school) ? school : list.school;
  835. list.pk = "GroupList";
  836. if (list.scope.Equals("private"))
  837. {
  838. //私人名单
  839. list.code = "GroupList";
  840. list.school = null;
  841. //只有开启审核,且设置天数大于零,且之前没有设置过期时间的时候才会重新设置过期时间。
  842. GroupList dblist = null;
  843. if (!string.IsNullOrWhiteSpace(list.id))
  844. {
  845. var response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemStreamAsync(list.id, new PartitionKey(list.code));
  846. if (response.Status==200)
  847. {
  848. dblist = JsonDocument.Parse(response.Content).RootElement.ToObject<GroupList>();
  849. }
  850. }
  851. if (list.review==1)
  852. {
  853. if (list.qrcodeDays>0)
  854. {
  855. if (dblist!=null)
  856. {
  857. //更新过期时间
  858. if (dblist.qrcodeDays!=list.qrcodeDays)
  859. {
  860. list.qrcodeExpire= DateTimeOffset.UtcNow.AddDays(list.qrcodeDays).ToUnixTimeMilliseconds();
  861. string key = $"GroupList:GroupWaitingList:{list.scope}:{list.id}";
  862. await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, expiry: DateTimeOffset.FromUnixTimeMilliseconds(list.qrcodeExpire).UtcDateTime);
  863. }
  864. else
  865. {
  866. //相同
  867. if (dblist.review==0 && list.review==1)
  868. {
  869. list.qrcodeExpire= DateTimeOffset.UtcNow.AddDays(list.qrcodeDays).ToUnixTimeMilliseconds();
  870. string key = $"GroupList:GroupWaitingList:{list.scope}:{list.id}";
  871. await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, expiry: DateTimeOffset.FromUnixTimeMilliseconds(list.qrcodeExpire).UtcDateTime);
  872. }
  873. else
  874. {
  875. list.qrcodeExpire=dblist.qrcodeExpire;
  876. }
  877. }
  878. }
  879. else
  880. {
  881. if (list.qrcodeExpire<=0)
  882. {
  883. list.qrcodeExpire= DateTimeOffset.UtcNow.AddDays(list.qrcodeDays).ToUnixTimeMilliseconds();
  884. }
  885. }
  886. }
  887. else
  888. {
  889. return Ok(new { error = 400, msg = "必须设置二维码过期天数!" });
  890. }
  891. }
  892. else
  893. {
  894. if (dblist!=null && dblist.review==1) {
  895. list.qrcodeDays = 1;
  896. list.qrcodeExpire = 0;
  897. string key = $"GroupList:GroupWaitingList:{list.scope}:{list.id}";
  898. var datas = await _azureRedis.GetRedisClient(8).HashGetAllAsync(key);
  899. List<GroupWaitingList> groupWaitingLists = new List<GroupWaitingList>();
  900. foreach (var rcd in datas)
  901. {
  902. var value = rcd.Value.ToString().ToObject<GroupWaitingList>();
  903. if (value!=null) { groupWaitingLists.Add(value); }
  904. }
  905. if (groupWaitingLists.IsNotEmpty()) {
  906. var takeCount = list.limitCount-dblist.members.Count;
  907. if (takeCount>0)
  908. {
  909. var takes = groupWaitingLists.OrderBy(x => x.applyTime).Take(takeCount);
  910. if (takes!=null && takes.Count()>0)
  911. {
  912. foreach (var t in takes)
  913. {
  914. GroupListService.JoinList(list, t.userid, t.type, t.school, t.year);
  915. string stuKey = !string.IsNullOrWhiteSpace(school) ? $"GroupList:StudentWaitinglist:{school}_{t.userid}" : $"GroupList:StudentWaitinglist:{t.userid}";
  916. string sutFiled = $"{list.scope}:{list.id}";
  917. var data = await _azureRedis.GetRedisClient(8).HashGetAsync(stuKey, sutFiled);
  918. if (data != default && !data.IsNullOrEmpty)
  919. {
  920. var value = data.ToString().ToObject<GroupWaitingList>();
  921. value.status=0;
  922. await _azureRedis.GetRedisClient(8).HashSetAsync(stuKey, sutFiled, value.ToJsonString());
  923. }
  924. }
  925. //未自动加入的,直接拒绝
  926. var untakes = groupWaitingLists.Except(takes);
  927. if (untakes!=null && untakes.Count()>0)
  928. {
  929. foreach (var t in takes)
  930. {
  931. string stuKey = !string.IsNullOrWhiteSpace(school) ? $"GroupList:StudentWaitinglist:{school}_{t.userid}" : $"GroupList:StudentWaitinglist:{t.userid}";
  932. string sutFiled = $"{list.scope}:{list.id}";
  933. var data = await _azureRedis.GetRedisClient(8).HashGetAsync(stuKey, sutFiled);
  934. if (data != default && !data.IsNullOrEmpty)
  935. {
  936. var value = data.ToString().ToObject<GroupWaitingList>();
  937. value.status=1;
  938. await _azureRedis.GetRedisClient(8).HashSetAsync(stuKey, sutFiled, value.ToJsonString());
  939. }
  940. }
  941. }
  942. }
  943. }
  944. else
  945. {
  946. //已经加满,删除候选
  947. foreach (var t in groupWaitingLists)
  948. {
  949. string stuKey = !string.IsNullOrWhiteSpace(school) ? $"GroupList:StudentWaitinglist:{school}_{t.userid}" : $"GroupList:StudentWaitinglist:{t.userid}";
  950. string sutFiled = $"{list.scope}:{list.id}";
  951. var data = await _azureRedis.GetRedisClient(8).HashGetAsync(stuKey, sutFiled);
  952. if (data != default && !data.IsNullOrEmpty)
  953. {
  954. var value = data.ToString().ToObject<GroupWaitingList>();
  955. value.status=1;
  956. await _azureRedis.GetRedisClient(8).HashSetAsync(stuKey, sutFiled, value.ToJsonString());
  957. }
  958. }
  959. }
  960. }
  961. await _azureRedis.GetRedisClient(8).KeyDeleteAsync(key);
  962. }
  963. }
  964. }
  965. else
  966. {
  967. //学校自定义名单
  968. list.code = !list.code.StartsWith("GroupList-") ? $"GroupList-{list.code}" : list.code;
  969. }
  970. switch (true)
  971. {
  972. //普通学生名单(包含学校教学班名单,个人课程名单),其中学生成员账号类型可以是学校学生账号和醍摩豆ID,分区键为GroupList-hbcn
  973. case bool when $"{list.type}".Equals("teach", StringComparison.OrdinalIgnoreCase):
  974. list.type = "teach";
  975. list = await GroupListService.CheckListNo(list, _azureCosmos, _dingDing, _option);
  976. list = await GroupListService.UpsertList(list, _azureCosmos, _configuration, _serviceBus);
  977. break;
  978. //教研组名单,只有加入学校的老师名单 成员账号类型是醍摩豆ID,保存在学校表,分区键为GroupList-hbcn
  979. case bool when $"{list.type}".Equals("research", StringComparison.OrdinalIgnoreCase):
  980. list.type = "research";
  981. list.scope = "school";
  982. list = await GroupListService.UpsertList(list, _azureCosmos, _configuration, _serviceBus);
  983. break;
  984. //个人好友名单,成员账号类型可以是学校学生账号和醍摩豆ID,分区键为GroupList
  985. case bool when $"{list.type}".Equals("friend", StringComparison.OrdinalIgnoreCase):
  986. list.type = "friend";
  987. list.scope = "private";
  988. list = await GroupListService.UpsertList(list, _azureCosmos, _configuration, _serviceBus);
  989. break;
  990. //社交群组类型(包含学校交流群组,个人交流群组),成员账号类型可以是学校学生账号和醍摩豆ID,,分区键为GroupList-hbcn
  991. case bool when $"{list.type}".Equals("group", StringComparison.OrdinalIgnoreCase):
  992. list.type = "group";
  993. list = await GroupListService.CheckListNo(list, _azureCosmos, _dingDing, _option);
  994. list = await GroupListService.UpsertList(list, _azureCosmos, _configuration, _serviceBus);
  995. break;
  996. //研修类型成员账号类型可以是学校学生账号和醍摩豆ID,,分区键为GroupList-hbcn
  997. case bool when $"{list.type}".Equals("yxtrain", StringComparison.OrdinalIgnoreCase):
  998. list.type = "yxtrain";
  999. list.scope = "school";
  1000. list = await GroupListService.UpsertList(list, _azureCosmos, _configuration, _serviceBus);
  1001. break;
  1002. default:
  1003. return Ok(new { error = 400, msg = "参数错误!" });
  1004. }
  1005. return Ok(new { list });
  1006. }
  1007. catch (Exception ex)
  1008. {
  1009. await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/upsert-grouplist()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1010. return BadRequest();
  1011. }
  1012. }
  1013. //删除名单
  1014. [ProducesDefaultResponseType]
  1015. [AuthToken(Roles = "teacher,admin")]
  1016. [HttpPost("delete-grouplist")]
  1017. [Authorize(Roles = "IES")]
  1018. public async Task<IActionResult> DeleteGroupList(JsonElement json)
  1019. {
  1020. try
  1021. {
  1022. if (!json.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1023. if (!json.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  1024. if (!json.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1025. var client = _azureCosmos.GetCosmosClient();
  1026. string tbname = "";
  1027. string datacode = "";
  1028. if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
  1029. {
  1030. tbname = "School";
  1031. datacode = $"GroupList-{code}";
  1032. }
  1033. else
  1034. {
  1035. tbname = "Teacher";
  1036. datacode = $"GroupList";
  1037. }
  1038. try
  1039. {
  1040. await GroupListService.DeleteGrouplistEvent($"{id}", datacode, tbname, client, _configuration, _serviceBus);
  1041. }
  1042. catch (Exception ex) { }
  1043. return Ok(new { id });
  1044. }
  1045. catch (Exception ex)
  1046. {
  1047. await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/delete-grouplist()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1048. return Ok(new { error = 400 });
  1049. }
  1050. }
  1051. /// <summary>
  1052. /// 保存或更新通用名单
  1053. /// </summary>
  1054. /// <param name="json"></param>
  1055. /// <returns></returns>
  1056. [ProducesDefaultResponseType]
  1057. [AuthToken(Roles = "teacher,admin,student")]
  1058. [HttpPost("upsert-group-member")]
  1059. [Authorize(Roles = "IES")]
  1060. public async Task<IActionResult> UpsertGroupMember(JsonElement json)
  1061. {
  1062. if (!json.TryGetProperty("opt", out JsonElement _opt)) { return BadRequest(); }
  1063. if (!json.TryGetProperty("scope", out JsonElement _scope)) { return BadRequest(); }
  1064. if (!json.TryGetProperty("id", out JsonElement _id)) { return BadRequest(); }
  1065. if (!json.TryGetProperty("code", out JsonElement _code)) { return BadRequest(); }
  1066. if (!json.TryGetProperty("type", out JsonElement _type)) { return BadRequest(); }
  1067. try
  1068. {
  1069. GroupList groupList = null;
  1070. string tbname = $"{_scope}".Equals("private") ? "Teacher" : "School";
  1071. string code = "";
  1072. if (string.IsNullOrEmpty($"{_type}") || !$"{_type}".Equals("class"))
  1073. {
  1074. if ($"{_scope}".Equals("private"))
  1075. {
  1076. //私人名单
  1077. code = "GroupList";
  1078. }
  1079. else
  1080. {
  1081. //学校自定义名单
  1082. code = !code.StartsWith("GroupList-") ? $"GroupList-{_code}" : code;
  1083. }
  1084. groupList = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<GroupList>($"{_id}", new PartitionKey($"{code}"));
  1085. }
  1086. switch (true)
  1087. {
  1088. case bool when $"{_opt}".Equals("up-nickname", StringComparison.OrdinalIgnoreCase) && json.TryGetProperty("members", out JsonElement _members):
  1089. var members = _members.ToObject<List<Member>>();
  1090. List<Member> updateSuccess = new List<Member>();
  1091. List<Member> updateFailed = new List<Member>();
  1092. members.ForEach(x =>
  1093. {
  1094. var member = groupList.members.Find(z => z.type == x.type && z.id.Equals(x.id));
  1095. if (member != null)
  1096. {
  1097. member.nickname = x.nickname;
  1098. updateSuccess.Add(member);
  1099. }
  1100. else
  1101. {
  1102. updateFailed.Add(x);
  1103. }
  1104. });
  1105. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<GroupList>(groupList, $"{_id}", new PartitionKey(code));
  1106. return Ok(new { updateSuccess, updateFailed });
  1107. }
  1108. }
  1109. catch (Exception ex)
  1110. {
  1111. await _dingDing.SendBotMsg($"{_option.Location},更新名单成员信息异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.成都开发測試群組);
  1112. return BadRequest();
  1113. }
  1114. return Ok();
  1115. }
  1116. /// <
  1117. /// summary>
  1118. /// 处理名单审核
  1119. /// </summary>
  1120. /// <param name="json"></param>
  1121. /// <returns></returns>
  1122. [ProducesDefaultResponseType]
  1123. [AuthToken(Roles = "teacher,admin")]
  1124. [HttpPost("review")]
  1125. #if DEBUG
  1126. [Authorize(Roles = "IES")]
  1127. #endif
  1128. public async Task<IActionResult> review(JsonElement request)
  1129. {
  1130. (string tmdid, _, _, string school) = HttpContext.GetAuthTokenInfo();
  1131. if (!request.TryGetProperty("grant_type", out JsonElement grant_type)) return BadRequest();
  1132. var client = _azureCosmos.GetCosmosClient();
  1133. switch (true)
  1134. {
  1135. //待加入列表
  1136. case bool when $"{grant_type}".Equals("waitlist", StringComparison.OrdinalIgnoreCase):
  1137. break;
  1138. //处理审核
  1139. case bool when $"{grant_type}".Equals("process", StringComparison.OrdinalIgnoreCase):
  1140. await _azureRedis.GetRedisClient(8).KeyExpireTimeAsync("");
  1141. break;
  1142. //审核结果,学生端获取到被拒绝的,或者过期的自动删除,未被审核的保存
  1143. case bool when $"{grant_type}".Equals("result", StringComparison.OrdinalIgnoreCase):
  1144. break;
  1145. }
  1146. return Ok();
  1147. }
  1148. }
  1149. }