GroupListController.cs 144 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375
  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 Microsoft.Extensions.Configuration;
  18. using TEAMModelOS.Filter;
  19. using HTEXLib.COMM.Helpers;
  20. using System.Text;
  21. using Microsoft.AspNetCore.Authorization;
  22. using Microsoft.AspNetCore.Hosting;
  23. using static TEAMModelOS.SDK.GroupListService;
  24. using TEAMModelOS.Controllers.Both;
  25. using CourseDto = TEAMModelOS.Controllers.Both.CourseDto;
  26. namespace TEAMModelOS.Controllers
  27. {
  28. [ProducesResponseType(StatusCodes.Status200OK)]
  29. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  30. [Route("grouplist")]
  31. [ApiController]
  32. public class GroupListController : ControllerBase
  33. {
  34. private AzureCosmosFactory _azureCosmos;
  35. private readonly DingDing _dingDing;
  36. private readonly Option _option;
  37. private readonly AzureServiceBusFactory _serviceBus;
  38. private readonly AzureRedisFactory _azureRedis;
  39. private readonly AzureStorageFactory _azureStorage;
  40. private readonly CoreAPIHttpService _coreAPIHttpService;
  41. private readonly IWebHostEnvironment _environment;
  42. 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.optNo ,c.expire,c.qrcodeExpire,c.qrcodeDays ,c.grades ";
  43. public IConfiguration _configuration { get; set; }
  44. public GroupListController(IWebHostEnvironment environment, CoreAPIHttpService coreAPIHttpService, AzureCosmosFactory azureCosmos, DingDing dingDing, IOptionsSnapshot<Option> option,
  45. AzureServiceBusFactory serviceBus, AzureStorageFactory azureStorage, IConfiguration configuration, AzureRedisFactory azureRedis)
  46. {
  47. _azureCosmos = azureCosmos;
  48. _dingDing = dingDing;
  49. _option = option?.Value;
  50. _serviceBus = serviceBus;
  51. _configuration = configuration;
  52. _azureStorage = azureStorage;
  53. _coreAPIHttpService = coreAPIHttpService;
  54. _environment = environment;
  55. _azureRedis=azureRedis;
  56. }
  57. //学生获取自己已经加入的名单。
  58. [ProducesDefaultResponseType]
  59. [HttpPost("get-student-joined-grouplist")]
  60. [Authorize(Roles = "IES")]
  61. [AuthToken(Roles = "admin,teacher,student")]
  62. public async Task<IActionResult> GetMyCourseAndGroupList(JsonElement json)
  63. {
  64. var (userid, _name, _picture, school) = HttpContext.GetAuthTokenInfo();
  65. var client = _azureCosmos.GetCosmosClient();
  66. object scope = null;
  67. HttpContext?.Items.TryGetValue("Scope", out scope);
  68. int memberType = 2;
  69. if ($"{scope}".Equals(Constant.ScopeStudent))
  70. {
  71. memberType = 2;
  72. // Student student = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<Student>(userid, new PartitionKey($"Base-{school}"));
  73. }
  74. if ($"{scope}".Equals(Constant.ScopeTmdUser))
  75. {
  76. memberType = 1;
  77. }
  78. if ($"{scope}".Equals(Constant.ScopeTeacher))
  79. {
  80. memberType = 1;
  81. }
  82. List<GroupListGrp> groups = null;
  83. if (json.TryGetProperty("time", out JsonElement _time) && long.TryParse($"{_time}", out long time) && time>0)
  84. {
  85. groups = await GroupListService.GetMemberInGroupList(_coreAPIHttpService, client, _dingDing, userid, memberType, school, new List<string> { "class", "teach" },time:time);
  86. }
  87. else {
  88. groups = await GroupListService.GetMemberInGroupList(_coreAPIHttpService, client, _dingDing, userid, memberType, school, new List<string> { "class", "teach" });
  89. }
  90. return Ok(new { groups = groups });
  91. }
  92. [ProducesDefaultResponseType]
  93. [HttpPost("get-grouplist-nos")]
  94. public async Task<IActionResult> GetGroupListNos(JsonElement json)
  95. {
  96. GroupList groupList = null;
  97. var client = _azureCosmos.GetCosmosClient();
  98. if (!json.TryGetProperty("stuListNo", out JsonElement _stuListNo)) return BadRequest();
  99. json.TryGetProperty("school", out JsonElement school);
  100. var queryNo = $"SELECT value(c) FROM c where c.no ='{_stuListNo}'";
  101. if (!string.IsNullOrEmpty($"{school}"))
  102. {
  103. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupList>(queryText: queryNo,
  104. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
  105. {
  106. groupList=item;
  107. break;
  108. }
  109. }
  110. if (groupList==null) {
  111. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<GroupList>(queryText: queryNo,
  112. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  113. {
  114. groupList=item;
  115. break;
  116. }
  117. }
  118. if (groupList!=null)
  119. {
  120. return Ok(new {code=200, nos = groupList.members.Select(x => x.irs),optNo= groupList.optNo , limitCount=groupList.limitCount});
  121. }
  122. else {
  123. return Ok(new {code=404, nos =new List<string>() , optNo =0, limitCount =0});
  124. }
  125. }
  126. /// <summary>
  127. /// 扫码加入名单
  128. /// </summary>
  129. /// <param name="json"></param>
  130. /// <returns></returns>
  131. [ProducesDefaultResponseType]
  132. [HttpPost("scan-code-join-list")]
  133. public async Task<IActionResult> ScanCodeJoinList(JsonElement json)
  134. {
  135. if (!json.TryGetProperty("stuListNo", out JsonElement _stuListNo)) return BadRequest();
  136. json.TryGetProperty("school", out JsonElement school);
  137. json.TryGetProperty("courseId", out JsonElement _courseId);
  138. int seatNo = 0;
  139. if (json.TryGetProperty("seatNo", out JsonElement _seatNo) ) {
  140. if (int.TryParse($"{_seatNo}", out int __seatNo)) {
  141. seatNo=__seatNo;
  142. }
  143. }
  144. var client = _azureCosmos.GetCosmosClient();
  145. json.TryGetProperty("id_token", out JsonElement id_token);
  146. var jwt = new JwtSecurityToken(id_token.GetString());
  147. var id = jwt.Payload.Sub;
  148. jwt.Payload.TryGetValue("name", out object name);
  149. jwt.Payload.TryGetValue("lang", out object lang);
  150. jwt.Payload.TryGetValue("picture", out object picture);
  151. try
  152. {
  153. TmdUser tmduser = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<TmdUser>(id, new PartitionKey("Base"));
  154. }
  155. catch (CosmosException ex)
  156. {
  157. if (ex.Status == 404)
  158. {
  159. //如果沒有,則初始化Teacher基本資料到Cosmos
  160. TmdUser tmduser = new TmdUser
  161. {
  162. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  163. id = id,
  164. pk = "Base",
  165. code = "Base",
  166. name = name?.ToString(),
  167. picture = picture?.ToString(),
  168. //创建账号并第一次登录IES5则默认赠送1G
  169. defaultSchool = null,
  170. schools = new List<TmdUser.School>(),
  171. lang= lang?.ToString(),
  172. };
  173. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync<TmdUser>(tmduser, new PartitionKey("Base"));
  174. }
  175. }
  176. int year = DateTimeOffset.UtcNow.Year;
  177. (int status, GroupList stuList, Member member) data = await GroupListService.CodeJoinList(client, _azureRedis, $"{_stuListNo}", id, type: 1, $"{school}", year, $"{name}", $"{picture}", $"{lang}", seatNo, $"{_courseId}");
  178. //没有TmdUser时
  179. if (data.status == 0)
  180. {
  181. await GroupListService.UpsertList(data.stuList, _azureCosmos, _configuration, _serviceBus);
  182. List<string> ids = new List<string>();
  183. if (data.stuList.scope.Equals("private") && !string.IsNullOrEmpty(data.stuList.creatorId))
  184. {
  185. ids.Add(data.stuList.creatorId);
  186. }
  187. else if (data.stuList.scope.Equals("school") && !string.IsNullOrEmpty(data.stuList.school))
  188. {
  189. //通知管理员
  190. string sql = "select distinct value(c.id) from c where array_contains(c.roles,'admin')";
  191. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<string>(queryText: sql,
  192. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Teacher-{school}") }))
  193. {
  194. ids.Add(item);
  195. }
  196. }
  197. if (ids.IsNotEmpty())
  198. {
  199. string bizcode = "scan-join";
  200. string sql = $"select c.id, c.name ,c.lang as code from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))})";
  201. List<IdNameCode> idNameCodes = new List<IdNameCode>();
  202. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  203. .GetItemQueryIterator<IdNameCode>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  204. {
  205. idNameCodes.Add(item);
  206. }
  207. // _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);
  208. }
  209. return Ok(new { data.stuList, data.status });
  210. }
  211. else
  212. {
  213. return Ok(new { data.status });
  214. }
  215. }
  216. /// <summary>
  217. /// 根据邀请码加入名单
  218. /// </summary>
  219. /// <param name="json"></param>
  220. /// <returns></returns>
  221. [ProducesDefaultResponseType]
  222. [AuthToken(Roles = "admin,teacher,student")]
  223. [HttpPost("input-code-join-list")]
  224. [Authorize(Roles = "IES")]
  225. public async Task<IActionResult> InputCodeJoinList(JsonElement json)
  226. {
  227. string head_lang = _option.Location.Contains("China") ? "zh-cn" : "zh-tw";
  228. if (HttpContext.Request.Headers.TryGetValue("lang", out var _lang))
  229. {
  230. head_lang = $"{_lang}";
  231. }
  232. if (!json.TryGetProperty("stuListNo", out JsonElement _stuListNo)) return BadRequest();
  233. var (userid, _name, _picture, school) = HttpContext.GetAuthTokenInfo();
  234. int type = 0;
  235. string no = null;
  236. var client = _azureCosmos.GetCosmosClient();
  237. int year = DateTimeOffset.UtcNow.Year;
  238. object scope = null;
  239. HttpContext?.Items.TryGetValue("Scope", out scope);
  240. if ($"{scope}".Equals(Constant.ScopeStudent))
  241. {
  242. type = 2;
  243. Student student = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<Student>(userid, new PartitionKey($"Base-{school}"));
  244. no = student.no;
  245. year = student.year;
  246. }
  247. if ($"{scope}".Equals(Constant.ScopeTmdUser))
  248. {
  249. type = 1;
  250. }
  251. if ($"{scope}".Equals(Constant.ScopeTeacher))
  252. {
  253. type = 1;
  254. }
  255. int seatNo =0;
  256. (int status, GroupList stuList, Member member) data = await GroupListService.CodeJoinList(client, _azureRedis, $"{_stuListNo}", userid, type, school, year, _name, _picture, head_lang,seatNo);
  257. if (data.status == 0)
  258. {
  259. await GroupListService.UpsertList(data.stuList, _azureCosmos, _configuration, _serviceBus);
  260. List<string> ids = new List<string>();
  261. if (data.stuList.scope.Equals("private") && !string.IsNullOrEmpty(data.stuList.creatorId))
  262. {
  263. ids.Add(data.stuList.creatorId);
  264. }
  265. else if (data.stuList.scope.Equals("school") && !string.IsNullOrEmpty(data.stuList.school))
  266. {
  267. //通知管理员
  268. string sql = "select distinct value(c.id) from c where array_contains(c.roles,'admin')";
  269. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<string>(queryText: sql,
  270. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Teacher-{school}") }))
  271. {
  272. ids.Add(item);
  273. }
  274. }
  275. if (ids.IsNotEmpty())
  276. {
  277. string bizcode = "scan-join";
  278. string sql = $"select c.id, c.name ,c.lang as code from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))})";
  279. List<IdNameCode> idNameCodes = new List<IdNameCode>();
  280. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  281. .GetItemQueryIterator<IdNameCode>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  282. {
  283. idNameCodes.Add(item);
  284. }
  285. _coreAPIHttpService.PushNotify(idNameCodes, $"{bizcode}_groupList", Constant.NotifyType_IES5_Course,
  286. new Dictionary<string, object> { { "tmdid", userid }, { "tmdname", _name }, { "groupListName", data.stuList.name }, { "groupListId", data.stuList.id } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
  287. }
  288. return Ok(new { data.stuList, data.status });
  289. }
  290. else
  291. {
  292. return Ok(new { data.status });
  293. }
  294. }
  295. /// <summary>
  296. /// 获取名单的tags
  297. /// </summary>
  298. /// <param name="json"></param>
  299. /// <returns></returns>
  300. [ProducesDefaultResponseType]
  301. [AuthToken(Roles = "admin,teacher,student")]
  302. [HttpPost("get-grouplist-tags")]
  303. [Authorize(Roles = "IES")]
  304. public async Task<IActionResult> GetGrouplistTags(JsonElement json)
  305. {
  306. var client = _azureCosmos.GetCosmosClient();
  307. var (id, _, _, school) = HttpContext.GetAuthTokenInfo();
  308. object scope = null;
  309. StringBuilder sql = new StringBuilder($"SELECT {SummarySql} ,A1.tag FROM c " +
  310. $" join A1 in c. members where A1.id='{id}' and A1.tag<>null ");
  311. HttpContext?.Items.TryGetValue("Scope", out scope);
  312. if (!string.IsNullOrEmpty(school) && $"{scope}".Equals(Constant.ScopeStudent))
  313. {
  314. sql.Append($" and A1.code='{school}'");
  315. }
  316. List<dynamic> groupLists = new List<dynamic>();
  317. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  318. GetItemQueryIterator<dynamic>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
  319. {
  320. groupLists.Add(item);
  321. }
  322. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").
  323. GetItemQueryIterator<dynamic>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList") }))
  324. {
  325. groupLists.Add(item);
  326. }
  327. return Ok(new { groupLists });
  328. }
  329. /// <summary>
  330. /// 获取发布活动的名单(弃用)
  331. /// </summary>
  332. /// <param name="json"></param>
  333. /// <returns></returns>
  334. [ProducesDefaultResponseType]
  335. [HttpPost("activity-grouplist")]
  336. #if !DEBUG
  337. [AuthToken(Roles = "teacher,admin,student")]
  338. [Authorize(Roles = "IES")]
  339. #endif
  340. public async Task<IActionResult> GetActivityGrouplist(JsonElement json)
  341. {
  342. var client = _azureCosmos.GetCosmosClient();
  343. json.TryGetProperty("tmdid", out JsonElement tmdid);
  344. json.TryGetProperty("schoolId", out JsonElement schoolId);
  345. if (!json.TryGetProperty("opt", out JsonElement opt)) { return BadRequest(); }
  346. json.TryGetProperty("periodId", out JsonElement periodId);
  347. long nowtime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  348. List<GroupListGrp> groupLists = new List<GroupListGrp>();
  349. switch (true)
  350. {
  351. //我管理的
  352. case bool when $"{opt}".Equals("manage", StringComparison.OrdinalIgnoreCase):
  353. //包含,学校的行政班,教学班
  354. json.TryGetProperty("type", out JsonElement _type);
  355. List<string> types = null;
  356. if (_type.ValueKind.Equals(JsonValueKind.Array))
  357. {
  358. types = _type.ToObject<List<string>>();
  359. }
  360. else if (_type.ValueKind.Equals(JsonValueKind.String))
  361. {
  362. types = new List<string> { $"{_type}" };
  363. }
  364. if (types.IsEmpty() || types.Contains("class"))
  365. {
  366. 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 )");
  367. if (!string.IsNullOrEmpty($"{periodId}"))
  368. {
  369. classsql.Append($" and c.periodId='{periodId}' ");
  370. }
  371. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ClassInfo>(queryText: classsql.ToString(),
  372. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  373. {
  374. int scount = 0;
  375. HashSet<string> groupNames = new HashSet<string>();
  376. string gpsql = $"SELECT distinct c.id, c.groupId,c.groupName FROM c where c.classId='{item.id}' ";
  377. await foreach (var gp in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: gpsql,
  378. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{schoolId}") }))
  379. {
  380. if (!string.IsNullOrWhiteSpace(gp.groupName))
  381. {
  382. groupNames.Add(gp.groupName);
  383. }
  384. scount += 1;
  385. }
  386. ///行政班(学生搜寻classId动态返回)class
  387. GroupListGrp group = new GroupListGrp
  388. {
  389. id = item.id,
  390. code = $"GroupList-{schoolId}",
  391. name = item.name,
  392. periodId = item.periodId,
  393. scope = "school",
  394. school = $"{schoolId}",
  395. type = "class",
  396. year = item.year,
  397. expire=0,
  398. groupName = groupNames,
  399. scount= scount
  400. };
  401. groupLists.Add(group);
  402. }
  403. }
  404. if (types.IsEmpty() || types.Contains("teach"))
  405. {
  406. //教学班
  407. 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} ) ");
  408. if (!string.IsNullOrEmpty($"{periodId}"))
  409. {
  410. teachsql.Append($" and c.periodId='{periodId}'");
  411. }
  412. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  413. GetItemQueryIterator<GroupList>(queryText: teachsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{schoolId}") }))
  414. {
  415. HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  416. groupLists.Add(new GroupListGrp(item, groupName));
  417. }
  418. }
  419. if (types.IsEmpty() || types.Contains("research"))
  420. {
  421. //教研组
  422. StringBuilder researchsql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='research'");
  423. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  424. GetItemQueryIterator<GroupList>(queryText: researchsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{schoolId}") }))
  425. {
  426. HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  427. groupLists.Add(new GroupListGrp(item, groupName));
  428. }
  429. }
  430. if (types.IsEmpty() || types.Contains("yxtrain"))
  431. {
  432. //研修名单
  433. StringBuilder yxtrainsql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='yxtrain'");
  434. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  435. GetItemQueryIterator<GroupList>(queryText: yxtrainsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{schoolId}") }))
  436. {
  437. HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  438. groupLists.Add(new GroupListGrp(item, groupName));
  439. }
  440. }
  441. return Ok(new { groupLists });
  442. //弃用
  443. case bool when $"{opt}".Equals("teach", StringComparison.OrdinalIgnoreCase):
  444. //我执教的
  445. //从学校的课程和个人课程搜寻与我相关的课程对应的名单。
  446. List<TeachCourse> teachCourses = new List<TeachCourse>();
  447. if (!string.IsNullOrEmpty($"{schoolId}"))
  448. {
  449. 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}'");
  450. if (!string.IsNullOrEmpty($"{periodId}"))
  451. {
  452. schoolQuery.Append($" and c.period.id='{periodId}' ");
  453. }
  454. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  455. GetItemQueryIterator<TeachCourse>(queryText: schoolQuery.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{schoolId}") }))
  456. {
  457. teachCourses.Add(item);
  458. }
  459. }
  460. 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}'");
  461. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").
  462. GetItemQueryIterator<TeachCourse>(queryText: query.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{tmdid}") }))
  463. {
  464. teachCourses.Add(item);
  465. }
  466. var classIds = teachCourses.Select(x => x.schedule).Where(y => !string.IsNullOrEmpty(y.classId)).Select(x => x.classId).Distinct().ToList();
  467. var schedule = teachCourses.Where(y => !string.IsNullOrEmpty(y.schedule.stulist)).Distinct().ToList();
  468. //var schedule = teachCourses.Select(x => new { schedule = x.schedule.Where(mm=>!string.IsNullOrEmpty(mm.stulist)), scope = x.scope }).ToList();
  469. if (classIds.IsNotEmpty())
  470. {
  471. string insql = string.Join(",", classIds.Select(x => $"'{x}'"));
  472. 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) ");
  473. ///行政班(学生搜寻classId动态返回)class
  474. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ClassInfo>(queryText: query.ToString(),
  475. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{schoolId}") }))
  476. {
  477. HashSet<string> groupNames = new HashSet<string>();
  478. string gpsql = $"SELECT distinct c.groupId,c.groupName FROM c where c.classId='{item.id}'and c.groupName <>null";
  479. await foreach (var gp in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: gpsql,
  480. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{schoolId}") }))
  481. {
  482. groupNames.Add(gp.groupName);
  483. }
  484. GroupListGrp group = new GroupListGrp
  485. {
  486. id = item.id,
  487. code = $"GroupList-{schoolId}",
  488. name = item.name,
  489. periodId = item.periodId,
  490. scope = "school",
  491. school = $"{schoolId}",
  492. type = "class",
  493. expire=0,
  494. year = item.year,
  495. groupName = groupNames
  496. };
  497. groupLists.Add(group);
  498. }
  499. }
  500. if (schedule.IsNotEmpty())
  501. {
  502. var privateList = schedule.Where(x => x.scope.Equals("private")).Select(x => x.schedule.stulist).Distinct();
  503. if (privateList.Count() > 0)
  504. {
  505. string insql = string.Join(",", privateList.Select(x => $"'{x}'"));
  506. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<GroupList>(queryText: $"select distinct {SummarySql} from c where c.id in ({insql})",
  507. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
  508. {
  509. HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  510. groupLists.Add(new GroupListGrp(item, groupName));
  511. }
  512. }
  513. var schoolList = schedule.Where(x => x.scope.Equals("school")).Select(x => x.schedule.stulist).Distinct();
  514. if (schoolList.Count() > 0)
  515. {
  516. List<GroupListDto> groups = new List<GroupListDto>();
  517. string insql = string.Join(",", schoolList.Select(x => $"'{x}'"));
  518. //我教的学校教学班,如果有过期的教学班则不返回
  519. 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} ) ",
  520. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{schoolId}") }))
  521. {
  522. HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  523. groupLists.Add(new GroupListGrp(item, groupName));
  524. }
  525. }
  526. }
  527. List<CourseGroupList> courseGroups = new List<CourseGroupList>();
  528. teachCourses.GroupBy(y => (y.id, y.name, y.scope, y.period.name, y.period.id, y.subject.name, y.subject.id)).ToList().ForEach(x =>
  529. {
  530. List<GroupListGrp> classIds = groupLists.Where(n => x.Where(m => !string.IsNullOrEmpty(m.schedule.classId)).Select(b => b.schedule.classId).Contains(n.id)).ToList();
  531. List<GroupListGrp> stulists = groupLists.Where(n => x.Where(m => !string.IsNullOrEmpty(m.schedule.stulist)).Select(b => b.schedule.stulist).Contains(n.id)).ToList();
  532. if (classIds == null)
  533. {
  534. classIds = new List<GroupListGrp>();
  535. }
  536. if (stulists != null)
  537. {
  538. classIds.AddRange(stulists);
  539. }
  540. CourseGroupList groupList = new CourseGroupList()
  541. {
  542. scope = x.Key.Item3,
  543. subject = x.Key.Item6,
  544. subjectId = x.Key.Item7,
  545. period = x.Key.Item4,
  546. periodId = x.Key.Item5,
  547. id = x.Key.Item1,
  548. name = x.Key.Item2,
  549. groups = classIds
  550. };
  551. courseGroups.Add(groupList);
  552. });
  553. return Ok(new { groupLists = courseGroups });
  554. case bool when $"{opt}".Equals("private", StringComparison.OrdinalIgnoreCase):
  555. //我个人的
  556. break;
  557. default:
  558. break;
  559. }
  560. return Ok(new { error = 1, msg = "参数异常" });
  561. }
  562. /// <summary>
  563. ///
  564. /// </summary>
  565. /// <param name="request"></param>
  566. /// <returns></returns>
  567. [ProducesDefaultResponseType]
  568. [AuthToken(Roles = "teacher,admin")]
  569. [HttpPost("get-activity-grouplist")]
  570. #if !DEBUG
  571. [Authorize(Roles = "IES")]
  572. #endif
  573. public async Task<IActionResult> ActivityGrouplist(JsonElement json)
  574. {
  575. (string tmdid, _, _, string school) = HttpContext.GetAuthTokenInfo();
  576. var client = _azureCosmos.GetCosmosClient();
  577. if (!json.TryGetProperty("opt", out JsonElement opt)) { return BadRequest(); }
  578. json.TryGetProperty("periodId", out JsonElement periodId);
  579. long nowtime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  580. json.TryGetProperty("time", out JsonElement _time);
  581. switch (true)
  582. {
  583. //我管理的
  584. case bool when $"{opt}".Equals("manage", StringComparison.OrdinalIgnoreCase):
  585. {
  586. List<GroupListGrp> groupLists = new List<GroupListGrp>();
  587. //包含,学校的行政班,教学班
  588. json.TryGetProperty("type", out JsonElement _type);
  589. List<string> types = null;
  590. if (_type.ValueKind.Equals(JsonValueKind.Array))
  591. {
  592. types = _type.ToObject<List<string>>();
  593. }
  594. else if (_type.ValueKind.Equals(JsonValueKind.String))
  595. {
  596. types = new List<string> { $"{_type}" };
  597. }
  598. if (types.IsEmpty() || types.Contains("class"))
  599. {
  600. 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 )");
  601. if (!string.IsNullOrEmpty($"{periodId}"))
  602. {
  603. classsql.Append($" and c.periodId='{periodId}' ");
  604. }
  605. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ClassInfo>(queryText: classsql.ToString(),
  606. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{school}") }))
  607. {
  608. int scount = 0;
  609. HashSet<string> groupNames = new HashSet<string>();
  610. string gpsql = $"SELECT distinct c.id, c.groupId,c.groupName FROM c where c.classId='{item.id}' ";
  611. await foreach (var gp in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: gpsql,
  612. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{school}") }))
  613. {
  614. if (!string.IsNullOrWhiteSpace(gp.groupName))
  615. {
  616. groupNames.Add(gp.groupName);
  617. }
  618. scount += 1;
  619. }
  620. ///行政班(学生搜寻classId动态返回)class
  621. GroupListGrp group = new GroupListGrp
  622. {
  623. id = item.id,
  624. code = $"GroupList-{school}",
  625. name = item.name,
  626. periodId = item.periodId,
  627. scope = "school",
  628. school = $"{school}",
  629. type = "class",
  630. year = item.year,
  631. expire=0,
  632. no=item.no,
  633. groupName = groupNames,
  634. scount= scount
  635. };
  636. groupLists.Add(group);
  637. }
  638. }
  639. if (types.IsEmpty() || types.Contains("teach"))
  640. {
  641. //教学班
  642. 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} ) ");
  643. if (!string.IsNullOrEmpty($"{periodId}"))
  644. {
  645. teachsql.Append($" and c.periodId='{periodId}'");
  646. }
  647. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  648. GetItemQueryIterator<GroupList>(queryText: teachsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
  649. {
  650. HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  651. groupLists.Add(new GroupListGrp(item, groupName));
  652. }
  653. }
  654. if (types.IsEmpty() || types.Contains("research"))
  655. {
  656. //教研组
  657. StringBuilder researchsql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='research'");
  658. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  659. GetItemQueryIterator<GroupList>(queryText: researchsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
  660. {
  661. HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  662. groupLists.Add(new GroupListGrp(item, groupName));
  663. }
  664. }
  665. if (types.IsEmpty() || types.Contains("yxtrain"))
  666. {
  667. //研修名单
  668. StringBuilder yxtrainsql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='yxtrain'");
  669. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  670. GetItemQueryIterator<GroupList>(queryText: yxtrainsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
  671. {
  672. HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  673. groupLists.Add(new GroupListGrp(item, groupName));
  674. }
  675. }
  676. //long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  677. return Ok(new { groupLists });
  678. }
  679. case bool when $"{opt}".Equals("teach", StringComparison.OrdinalIgnoreCase):
  680. {
  681. string sql = $"SELECT distinct value c FROM c join b in c.schedules where c.pk='CourseTask' and (ARRAY_CONTAINS(b.assistants,'{tmdid}')or b.teacherId ='{tmdid}' )";
  682. List<KeyValuePair<string,CourseTask >> schoolTeacherTask = new List<KeyValuePair<string, CourseTask>>();
  683. List<KeyValuePair<string,CourseTask >> schoolAssistantTask = new List<KeyValuePair<string,CourseTask >>();
  684. List<KeyValuePair<string,CourseTask >> privateTeacherTask = new List<KeyValuePair<string,CourseTask >>();
  685. List<KeyValuePair<string,CourseTask >> privateAssistantTask = new List<KeyValuePair<string,CourseTask >>();
  686. List<CourseDto> schoolCourses = new List<CourseDto>();
  687. List<CourseDto> teahcerCourses = new List<CourseDto>();
  688. List<string> groupIds = new List<string>();
  689. if (!string.IsNullOrWhiteSpace(school))
  690. {
  691. School schoolBase = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(school, new PartitionKey("Base"));
  692. JsonElement _year = default, _semesterId = default, _periodId = default;
  693. if (!json.TryGetProperty("periodId", out _periodId)) return BadRequest();
  694. if (!json.TryGetProperty("year", out _year))
  695. {
  696. return BadRequest();
  697. }
  698. if (!json.TryGetProperty("semesterId", out _semesterId))
  699. {
  700. return BadRequest();
  701. }
  702. var period = schoolBase.period.Find(x => x.id.Equals($"{_periodId}"));
  703. //string date = SchoolService.GetOpensByStudyYearAndSemester(period.semesters, int.Parse($"{_year}"), $"{_semesterId}");
  704. sql = $"{sql} and c.year={_year} and c.semesterId='{_semesterId}'";
  705. HashSet<string> courseIds = new HashSet<string>();
  706. var resultSchool= await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<CourseTask>(sql, $"CourseTask-{school}");
  707. if (resultSchool.list.IsNotEmpty()) {
  708. resultSchool.list.ForEach(x => {
  709. var schedulesTeacher = x.schedules.Where(z =>!string.IsNullOrWhiteSpace(z.teacherId) && z.teacherId.Equals(tmdid));
  710. if (schedulesTeacher.Any())
  711. {
  712. courseIds.Add(x.courseId);
  713. CourseTask courseTask = x.ToJsonString().ToObject<CourseTask>();
  714. courseTask.schedules=schedulesTeacher.ToList();
  715. schoolTeacherTask.Add(new KeyValuePair<string,CourseTask >(x.courseId, courseTask));
  716. groupIds.AddRange(schedulesTeacher.Where(z => !string.IsNullOrWhiteSpace(z.groupId)).Select(x => x.groupId));
  717. }
  718. var schedulesAssistant = x.schedules.Where(z => z.assistants.Contains(tmdid) );
  719. if (schedulesAssistant.Any())
  720. {
  721. courseIds.Add(x.courseId);
  722. CourseTask courseTask = x.ToJsonString().ToObject<CourseTask>();
  723. courseTask.schedules=schedulesAssistant.ToList();
  724. schoolAssistantTask.Add(new KeyValuePair<string, CourseTask>(x.courseId, courseTask));
  725. groupIds.AddRange(schedulesAssistant.Where(z => !string.IsNullOrWhiteSpace(z.groupId)).Select(x => x.groupId));
  726. }
  727. });
  728. }
  729. if (courseIds.Any()) {
  730. string sqlCourse = $"select value c from c where c.id in ({string.Join(",",courseIds.Select(b=>$"'{b}'"))})";
  731. var result = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<CourseBase>(sqlCourse, $"CourseBase-{school}");
  732. if (result.list.IsNotEmpty())
  733. {
  734. foreach (var item in result.list)
  735. {
  736. List<CourseTaskDto> courseTaskDtos = new List<CourseTaskDto>();
  737. var teacher = schoolTeacherTask.Where(x => x.Key.Equals(item.id)).Select(z => new CourseTaskDto { courseTask=z.Value, type="teacher" });
  738. if (teacher.Any()) {
  739. courseTaskDtos.AddRange(teacher.ToList());
  740. }
  741. var assistant= schoolAssistantTask.Where(x => x.Key.Equals(item.id)).Select(z => new CourseTaskDto { courseTask=z.Value, type="assistant" });
  742. if (assistant.Any()) {
  743. courseTaskDtos.AddRange(assistant.ToList());
  744. }
  745. schoolCourses.Add(new CourseDto { courseBase=item, courseTasks=courseTaskDtos });
  746. }
  747. }
  748. }
  749. }
  750. {
  751. HashSet<string> courseIds = new HashSet<string>();
  752. string sqlCoursePrivate = $"select value c.id from c where c.creatorId='{tmdid}'";
  753. var resultCourseBasePrivate = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetList<string>(sqlCoursePrivate, $"CourseBase");
  754. if (resultCourseBasePrivate.list.IsNotEmpty())
  755. {
  756. courseIds=new HashSet<string>(resultCourseBasePrivate.list);
  757. }
  758. string sqlprivate = $"SELECT distinct value c FROM c join b in c.schedules where c.pk='CourseTask' and (ARRAY_CONTAINS(b.assistants,'{tmdid}')or b.teacherId ='{tmdid}' )";
  759. var resultTeacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetList<CourseTask>(sqlprivate, $"CourseTask");
  760. if (resultTeacher.list.IsNotEmpty())
  761. {
  762. resultTeacher.list.ForEach(x => {
  763. var schedulesTeacher = x.schedules.Where(z => !string.IsNullOrWhiteSpace(z.teacherId) && z.teacherId.Equals(tmdid));
  764. if (schedulesTeacher.Any())
  765. {
  766. courseIds.Add(x.courseId);
  767. CourseTask courseTask = x.ToJsonString().ToObject<CourseTask>();
  768. courseTask.schedules=schedulesTeacher.ToList();
  769. privateTeacherTask.Add(new KeyValuePair<string, CourseTask>(x.courseId, courseTask));
  770. groupIds.AddRange(schedulesTeacher.Where(z => !string.IsNullOrWhiteSpace(z.groupId)).Select(x => x.groupId));
  771. }
  772. var schedulesAssistant = x.schedules.Where(z => z.assistants.Contains(tmdid));
  773. if (schedulesAssistant.Any())
  774. {
  775. courseIds.Add(x.courseId);
  776. CourseTask courseTask = x.ToJsonString().ToObject<CourseTask>();
  777. courseTask.schedules=schedulesAssistant.ToList();
  778. privateAssistantTask.Add(new KeyValuePair<string, CourseTask>(x.courseId, courseTask));
  779. groupIds.AddRange(schedulesAssistant.Where(z=>!string.IsNullOrWhiteSpace(z.groupId)).Select(x => x.groupId));
  780. }
  781. });
  782. }
  783. if (courseIds.Any())
  784. {
  785. string sqlCourse = $"select value c from c where c.creatorId='{tmdid}' and c.id in ({string.Join(",", courseIds.Select(b => $"'{b}'"))})";
  786. var result = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetList<CourseBase>(sqlCourse, $"CourseBase");
  787. if (result.list.IsNotEmpty())
  788. {
  789. foreach (var item in result.list)
  790. {
  791. List<CourseTaskDto> courseTaskDtos = new List<CourseTaskDto>();
  792. var teacher = privateTeacherTask.Where(x => x.Key.Equals(item.id)).Select(z => new CourseTaskDto { courseTask=z.Value, type="teacher" });
  793. if (teacher.Any())
  794. {
  795. courseTaskDtos.AddRange(teacher.ToList());
  796. }
  797. var assistant = privateAssistantTask.Where(x => x.Key.Equals(item.id)).Select(z => new CourseTaskDto { courseTask=z.Value, type="assistant" });
  798. if (assistant.Any())
  799. {
  800. courseTaskDtos.AddRange(assistant.ToList());
  801. }
  802. teahcerCourses.Add(new CourseDto { courseBase=item, courseTasks=courseTaskDtos });
  803. }
  804. }
  805. }
  806. List<CourseGroupList> courseGroupLists = new List<CourseGroupList>();
  807. _coreAPIHttpService.check=false;
  808. var groupListDatas = await GroupListService.GetMemberByListids(_coreAPIHttpService, _azureCosmos.GetCosmosClient(), _dingDing, groupIds.ToHashSet().ToList(), school);
  809. foreach (var z in teahcerCourses)
  810. {
  811. CourseGroupList courseGroupList= new CourseGroupList
  812. {
  813. scope="private",
  814. id=z.courseBase.id,
  815. name=z.courseBase.name,
  816. periodId=z.courseBase.period?.id,
  817. period=z.courseBase.period?.name,
  818. subject=z.courseBase.subject?.name,
  819. subjectId= z.courseBase.subject?.id
  820. };
  821. foreach (var x in z.courseTasks)
  822. {
  823. foreach (var y in x.courseTask.schedules)
  824. {
  825. var data = groupListDatas.groups.Find(m => m.id.Equals(y.groupId));
  826. if (data!= null)
  827. {
  828. HashSet<string> groupName = data.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  829. GroupListGrp groupListGrp = new GroupListGrp(data, groupName);
  830. groupListGrp.teachType=x.type;
  831. courseGroupList.groups.Add(groupListGrp);
  832. }
  833. }
  834. }
  835. courseGroupLists.Add(courseGroupList);
  836. }
  837. foreach (var z in schoolCourses)
  838. {
  839. CourseGroupList courseGroupList = new CourseGroupList
  840. {
  841. scope="school",
  842. id=z.courseBase.id,
  843. name=z.courseBase.name,
  844. periodId=z.courseBase.period?.id,
  845. period=z.courseBase.period?.name,
  846. subject=z.courseBase.subject?.name,
  847. subjectId= z.courseBase.subject?.id
  848. };
  849. foreach (var x in z.courseTasks)
  850. {
  851. foreach (var y in x.courseTask.schedules)
  852. {
  853. var data = groupListDatas.groups.Find(m => m.id.Equals(y.groupId));
  854. if (data!= null) {
  855. HashSet<string> groupName = data.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  856. GroupListGrp groupListGrp = new GroupListGrp(data, groupName);
  857. groupListGrp.teachType=x.type;
  858. courseGroupList.groups.Add(groupListGrp);
  859. }
  860. }
  861. }
  862. courseGroupLists.Add(courseGroupList);
  863. }
  864. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  865. foreach (var groups in courseGroupLists) {
  866. groups.groups.RemoveAll(z => z.expire>0 && z.expire<now);
  867. }
  868. return Ok(new { groupLists = courseGroupLists });
  869. }
  870. }
  871. }
  872. return Ok();
  873. }
  874. /// <summary>
  875. /// 根据任意名单id获取成员信息。
  876. /// </summary>
  877. /// <param name="json"></param>
  878. /// <returns></returns>
  879. [ProducesDefaultResponseType]
  880. [HttpPost("get-members-listids")]
  881. #if !DEBUG
  882. [AuthToken(Roles = "teacher,admin,student")]
  883. [Authorize(Roles = "IES")]
  884. #endif
  885. public async Task<IActionResult> GetMembersListids(JsonElement json)
  886. {
  887. var client = _azureCosmos.GetCosmosClient();
  888. if (!json.TryGetProperty("ids", out JsonElement ids)) return BadRequest();
  889. json.TryGetProperty("schoolId", out JsonElement schoolId);
  890. json.TryGetProperty("groupNames", out JsonElement groupNames);
  891. List<Dictionary<string, List<string>>> groupLists = new List<Dictionary<string, List<string>>>();
  892. if (groupNames.ValueKind.Equals(JsonValueKind.Array))
  893. {
  894. groupLists = groupNames.ToObject<List<Dictionary<string, List<string>>>>();
  895. }
  896. List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
  897. if (groupLists.Count > 0)
  898. {
  899. foreach (var gp in groupLists)
  900. {
  901. foreach (KeyValuePair<string, List<string>> pp in gp)
  902. {
  903. ps.Add((pp.Key, pp.Value));
  904. }
  905. }
  906. }
  907. List<string> listids = ids.ToObject<List<string>>();
  908. if (json.TryGetProperty("time", out JsonElement _time) && long.TryParse($"{_time}", out long time) && time>0)
  909. {
  910. (List<RMember> members, List<RGroupList> groups) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, listids, $"{schoolId}", ps,time:time);
  911. return Ok(new { groups, members });
  912. }
  913. else
  914. {
  915. (List<RMember> members, List<RGroupList> groups) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, listids, $"{schoolId}", ps);
  916. return Ok(new { groups, members });
  917. }
  918. }
  919. /// <summary>
  920. /// 根据任意名单id获取名单摘要信息。
  921. /// </summary>
  922. /// <param name="json"></param>
  923. /// <returns></returns>
  924. [ProducesDefaultResponseType]
  925. [HttpPost("get-grouplist-listids")]
  926. #if !DEBUG
  927. [AuthToken(Roles = "teacher,admin,student")]
  928. [Authorize(Roles = "IES")]
  929. #endif
  930. public async Task<IActionResult> GetGroupListListids(JsonElement json)
  931. {
  932. var client = _azureCosmos.GetCosmosClient();
  933. if (!json.TryGetProperty("ids", out JsonElement ids)) return BadRequest();
  934. json.TryGetProperty("schoolId", out JsonElement schoolId);
  935. List<string> listids = ids.ToObject<HashSet<string>>().ToList() ;
  936. List<GroupListDto> groups = null;
  937. if (json.TryGetProperty("time", out JsonElement _time) && long.TryParse($"{_time}", out long time) && time>0)
  938. {
  939. groups = await GroupListService.GetGroupListByListids(client, _dingDing, listids, $"{schoolId}", SummarySql, time: time);
  940. }
  941. else
  942. {
  943. groups = await GroupListService.GetGroupListByListids(client, _dingDing, listids, $"{schoolId}", SummarySql);
  944. }
  945. return Ok(new { groups });
  946. }
  947. /// <summary>
  948. /// 获取名单和成员信息。
  949. /// </summary>
  950. /// <param name="json"></param>
  951. /// <returns></returns>
  952. [ProducesDefaultResponseType]
  953. [AuthToken(Roles = "teacher,admin,student")]
  954. [HttpPost("get-grouplists-members")]
  955. [Authorize(Roles = "IES")]
  956. public async Task<IActionResult> GetGrouplistsMembers(JsonElement json)
  957. {
  958. try
  959. {
  960. var client = _azureCosmos.GetCosmosClient();
  961. json.TryGetProperty("tmdid", out JsonElement _tmdid);
  962. json.TryGetProperty("schoolId", out JsonElement _schoolId);
  963. if (!json.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  964. if (!json.TryGetProperty("type", out JsonElement type)) return BadRequest();
  965. json.TryGetProperty("periodId", out JsonElement periodId);
  966. json.TryGetProperty("no", out JsonElement no);
  967. List<RGroupList> groups = new List<RGroupList>();
  968. string sqlSemester = "";
  969. if (json.TryGetProperty("time", out JsonElement _time) && long.TryParse($"{_time}", out long time) && time>0)
  970. {
  971. var groupListSemester = await GetGroupListSemester(client, null, $"{_schoolId}", $"{type}", $"{periodId}", $"{no}", time);
  972. if (groupListSemester.groupListDtos.IsNotEmpty())
  973. {
  974. groups.AddRange(groupListSemester.rgroupList);
  975. //排除掉已有的数据
  976. sqlSemester =$" and c.id not in ({string.Join(",", groupListSemester.groupListDtos.Select(z => $"'{z.id}'"))})";
  977. }
  978. }
  979. StringBuilder sql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='{type}'");
  980. string tbname = "Teacher";
  981. string code = $"GroupList";
  982. if ($"{scope}".Equals("school", StringComparison.OrdinalIgnoreCase))
  983. {
  984. tbname = "School";
  985. code = $"GroupList-{_schoolId}";
  986. if (!string.IsNullOrEmpty($"{periodId}"))
  987. {
  988. sql.Append($" and c.periodId='{periodId}'");
  989. }
  990. if (!string.IsNullOrEmpty($"{no}"))
  991. {
  992. sql.Append($" and c.no='{no}'");
  993. }
  994. }
  995. else
  996. {
  997. sql.Append($" and c.creatorId='{_tmdid}'");
  998. }
  999. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, tbname).GetItemQueryIterator<RGroupList>(queryText: sql.ToString(),
  1000. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
  1001. {
  1002. groups.Add(item);
  1003. }
  1004. (List<RGroupList> groupsData, List<RMember> members) = await GroupListService.GetGroupListMemberInfo(_coreAPIHttpService, client, $"{type}", groups, tbname, _dingDing, $"{_schoolId}");
  1005. return Ok(new { groups = groupsData, members });
  1006. }
  1007. catch (CosmosException ex)
  1008. {
  1009. await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplists-members()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1010. }
  1011. catch (Exception ex)
  1012. {
  1013. await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplists-members()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1014. }
  1015. return Ok();
  1016. }
  1017. /// <summary>
  1018. /// 获取名单列表
  1019. /// </summary>
  1020. /// <param name="json"></param>
  1021. /// <returns></returns>
  1022. [ProducesDefaultResponseType]
  1023. [AuthToken(Roles = "teacher,admin,student")]
  1024. [HttpPost("get-grouplists")]
  1025. [Authorize(Roles = "IES")]
  1026. public async Task<IActionResult> GetGrouplists(JsonElement json)
  1027. {
  1028. try
  1029. {
  1030. var client = _azureCosmos.GetCosmosClient();
  1031. json.TryGetProperty("tmdid", out JsonElement _tmdid);
  1032. json.TryGetProperty("schoolId", out JsonElement _schoolId);
  1033. if (!json.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  1034. if (!json.TryGetProperty("type", out JsonElement type)) return BadRequest();
  1035. json.TryGetProperty("periodId", out JsonElement periodId);
  1036. json.TryGetProperty("no", out JsonElement no);
  1037. List<GroupListDto> groups = new List<GroupListDto>();
  1038. string sqlSemester = "";
  1039. if (json.TryGetProperty("time", out JsonElement _time) && long.TryParse($"{_time}", out long time) && time>0) {
  1040. var groupListSemester = await GetGroupListSemester(client, null, $"{_schoolId}", $"{type}", $"{periodId}", $"{no}", time);
  1041. if (groupListSemester.groupListDtos.IsNotEmpty()) {
  1042. groups.AddRange(groupListSemester.groupListDtos);
  1043. //排除掉已有的数据
  1044. sqlSemester =$" and c.id not in ({string.Join(",",groupListSemester.groupListDtos.Select(z=>$"'{z.id}'"))})";
  1045. }
  1046. }
  1047. StringBuilder sql = new StringBuilder($"SELECT distinct {SummarySql} FROM c where c.type='{type}' {sqlSemester}");
  1048. string tbname = "Teacher";
  1049. string code = $"GroupList";
  1050. if ($"{scope}".Equals("school", StringComparison.OrdinalIgnoreCase))
  1051. {
  1052. tbname = "School";
  1053. code = $"GroupList-{_schoolId}";
  1054. if (!string.IsNullOrEmpty($"{periodId}"))
  1055. {
  1056. sql.Append($" and c.periodId='{periodId}'");
  1057. }
  1058. if (!string.IsNullOrEmpty($"{no}"))
  1059. {
  1060. sql.Append($" and c.no='{no}'");
  1061. }
  1062. }
  1063. else
  1064. {
  1065. sql.Append($" and c.creatorId='{_tmdid}'");
  1066. }
  1067. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, tbname).GetItemQueryIterator<GroupListDto>(queryText: sql.ToString(),
  1068. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
  1069. {
  1070. groups.Add(item);
  1071. }
  1072. return Ok(new { groups });
  1073. }
  1074. catch (CosmosException ex)
  1075. {
  1076. await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplists()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1077. }
  1078. catch (Exception ex)
  1079. {
  1080. await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplists()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1081. }
  1082. return Ok();
  1083. }
  1084. /// <summary>
  1085. /// 根据id,code获取学校行政班信息和学生信息。用于维护学生基本信息。
  1086. /// </summary>
  1087. /// <param name="json"></param>
  1088. /// <returns></returns>
  1089. [ProducesDefaultResponseType]
  1090. [AuthToken(Roles = "teacher,admin")]
  1091. [HttpPost("get-classstudents-idcode")]
  1092. [Authorize(Roles = "IES")]
  1093. public async Task<IActionResult> GetClassStudentsIdcode(JsonElement json)
  1094. {
  1095. var client = _azureCosmos.GetCosmosClient();
  1096. if (!json.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1097. if (!json.TryGetProperty("code", out JsonElement _code)) return BadRequest();
  1098. List<Student> students = new List<Student>();
  1099. Class clazz = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<Class>($"{id}", new PartitionKey($"Class-{_code}"));
  1100. if (json.TryGetProperty("time", out JsonElement _time) && long.TryParse($"{_time}", out long time) && time>0)
  1101. {
  1102. var groupListSemester = await GetGroupListSemester(client, new List<string> { id.GetString()}, $"{_code}",type:null, periodId:null,no:null, time);
  1103. if (groupListSemester.rmembers.IsNotEmpty())
  1104. {
  1105. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: $"select value(c) from c where c.id in ({string.Join(",",groupListSemester.rmembers.Select(z=>$"'{z.id}'"))}) ",
  1106. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{_code}") }))
  1107. {
  1108. item.salt = null;
  1109. item.pw = null;
  1110. item.classId=clazz.id;
  1111. students.Add(item);
  1112. }
  1113. }
  1114. }
  1115. if (!students.IsNotEmpty()) {
  1116. try
  1117. {
  1118. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: $"select value(c) from c where c.classId = '{clazz.id}'",
  1119. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{_code}") }))
  1120. {
  1121. item.salt = null;
  1122. item.pw = null;
  1123. students.Add(item);
  1124. }
  1125. }
  1126. catch (Exception ex)
  1127. {
  1128. return Ok(new { error = 404, msg = "班级不存在!" });
  1129. }
  1130. }
  1131. return Ok(new { classInfo = clazz, students = students });
  1132. }
  1133. //处理通用名单
  1134. [ProducesDefaultResponseType]
  1135. [AuthToken(Roles = "teacher,admin,student")]
  1136. [HttpPost("get-grouplist-idcode")]
  1137. [Authorize(Roles = "IES")]
  1138. public async Task<IActionResult> GetGrouplistIdcode(JsonElement json)
  1139. {
  1140. RGroupList groupList = null;
  1141. try
  1142. {
  1143. var client = _azureCosmos.GetCosmosClient();
  1144. json.TryGetProperty("type", out JsonElement _type);
  1145. json.TryGetProperty("code", out JsonElement _code);
  1146. if (!json.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  1147. if (!json.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1148. string tbname = $"{scope}".Equals("private") ? "Teacher" : "School";
  1149. string code = "";
  1150. //根据时间获取历史名单
  1151. if (json.TryGetProperty("time", out JsonElement _time) && long.TryParse($"{_time}",out long time) && time>0 && !string.IsNullOrWhiteSpace($"{_code}")){
  1152. var semesterGroupList = await GetGroupListSemester(client, new List<string> { id.GetString()}, _code.GetString(),type:null,periodId:null,no:null, time);
  1153. if (semesterGroupList.rgroupList.IsNotEmpty()) {
  1154. groupList=semesterGroupList.rgroupList.First();
  1155. }
  1156. }
  1157. if (groupList==null) {
  1158. if (string.IsNullOrEmpty($"{_type}") || !$"{_type}".Equals("class"))
  1159. {
  1160. if ($"{scope}".Equals("private"))
  1161. {
  1162. //私人名单
  1163. code = "GroupList";
  1164. }
  1165. else
  1166. {
  1167. //学校自定义名单
  1168. code = !code.StartsWith("GroupList-") ? $"GroupList-{_code}" : code;
  1169. }
  1170. groupList = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<RGroupList>($"{id}", new PartitionKey($"{code}"));
  1171. }
  1172. else if ($"{_type}".Equals("class"))
  1173. {
  1174. try
  1175. {
  1176. code = $"Class-{_code}";
  1177. Class clazz = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<Class>($"{id}", new PartitionKey($"{code}"));
  1178. if (clazz != null)
  1179. {
  1180. List<Student> students = new List<Student>();
  1181. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: $"select value(c) from c where c.classId = '{clazz.id}'",
  1182. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{_code}") }))
  1183. {
  1184. students.Add(item);
  1185. }
  1186. ///行政班(学生搜寻classId动态返回)class
  1187. 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();
  1188. groupList = new RGroupList
  1189. {
  1190. id = clazz.id,
  1191. code = $"GroupList-{clazz.school}",
  1192. name = clazz.name,
  1193. periodId = clazz.periodId,
  1194. pk = "GroupList",
  1195. year = clazz.year,
  1196. expire = 0,
  1197. school = clazz.school,
  1198. scope = "school",
  1199. type = "class",
  1200. scount = smembers.Count,
  1201. no = clazz.no,
  1202. leader = clazz.teacher?.id,
  1203. members = smembers,
  1204. };
  1205. }
  1206. }
  1207. catch (CosmosException ex)
  1208. {
  1209. await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplist-idcode()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1210. return Ok(new { groupList });
  1211. }
  1212. }
  1213. }
  1214. (List<RGroupList> groupsData, List<RMember> members) = await GroupListService.GetGroupListMemberInfo(_coreAPIHttpService, client, $"{groupList.type}", new List<RGroupList> { groupList }, tbname, _dingDing, $"{_code}");
  1215. groupList = groupsData.FirstOrDefault();
  1216. }
  1217. catch (CosmosException ex)
  1218. {
  1219. await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplist-idcode()\n{ex.Message}\n{ex.StackTrace}\n {json}", GroupNames.醍摩豆服務運維群組);
  1220. return Ok(new { groupList });
  1221. }
  1222. catch (Exception ex)
  1223. {
  1224. await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplist-idcode()\n{ex.Message}\n{ex.StackTrace}\n{json}", GroupNames.醍摩豆服務運維群組);
  1225. }
  1226. return Ok(new { groupList });
  1227. }
  1228. /// <summary>
  1229. /// 保存或更新通用名单
  1230. /// </summary>
  1231. /// <param name="json"></param>
  1232. /// <returns></returns>
  1233. [ProducesDefaultResponseType]
  1234. [AuthToken(Roles = "teacher,admin")]
  1235. [HttpPost("upsert-grouplist")]
  1236. #if !DEBUG
  1237. [Authorize(Roles = "IES")]
  1238. #endif
  1239. public async Task<IActionResult> UpsertGroupList(JsonElement json)
  1240. {
  1241. GroupList list = json.ToObject<GroupList>();
  1242. try
  1243. {
  1244. var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
  1245. if (string.IsNullOrEmpty(list.type))
  1246. {
  1247. return BadRequest();
  1248. }
  1249. list.year = list.year > 0 ? list.year : DateTimeOffset.UtcNow.Year;
  1250. list.ttl = -1;
  1251. list.creatorId = userid;
  1252. list.school = string.IsNullOrEmpty(list.school) ? school : list.school;
  1253. list.pk = "GroupList";
  1254. if (list.scope.Equals("private"))
  1255. {
  1256. //私人名单
  1257. list.code = "GroupList";
  1258. list.school = null;
  1259. //只有开启审核,且设置天数大于零,且之前没有设置过期时间的时候才会重新设置过期时间。
  1260. GroupList dblist = null;
  1261. if (!string.IsNullOrWhiteSpace(list.id))
  1262. {
  1263. var response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemStreamAsync(list.id, new PartitionKey(list.code));
  1264. if (response.Status==200)
  1265. {
  1266. dblist = JsonDocument.Parse(response.Content).RootElement.ToObject<GroupList>();
  1267. }
  1268. }
  1269. if (list.review==1)
  1270. {
  1271. if (list.qrcodeDays>0)
  1272. {
  1273. if (dblist!=null)
  1274. {
  1275. //更新过期时间
  1276. if (dblist.qrcodeDays!=list.qrcodeDays)
  1277. {
  1278. list.qrcodeExpire= DateTimeOffset.UtcNow.AddDays(list.qrcodeDays).ToUnixTimeMilliseconds();
  1279. string key = $"GroupList:GroupWaitingList:{list.scope}:{list.id}";
  1280. await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, expiry: DateTimeOffset.FromUnixTimeMilliseconds(list.qrcodeExpire).UtcDateTime);
  1281. }
  1282. else
  1283. {
  1284. //相同
  1285. if (dblist.review==0 && list.review==1)
  1286. {
  1287. list.qrcodeExpire= DateTimeOffset.UtcNow.AddDays(list.qrcodeDays).ToUnixTimeMilliseconds();
  1288. string key = $"GroupList:GroupWaitingList:{list.scope}:{list.id}";
  1289. await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, expiry: DateTimeOffset.FromUnixTimeMilliseconds(list.qrcodeExpire).UtcDateTime);
  1290. }
  1291. else
  1292. {
  1293. list.qrcodeExpire=dblist.qrcodeExpire;
  1294. }
  1295. }
  1296. }
  1297. else
  1298. {
  1299. if (list.qrcodeExpire<=0)
  1300. {
  1301. list.qrcodeExpire= DateTimeOffset.UtcNow.AddDays(list.qrcodeDays).ToUnixTimeMilliseconds();
  1302. }
  1303. }
  1304. }
  1305. else
  1306. {
  1307. return Ok(new { error = 400, msg = "必须设置二维码过期天数!" });
  1308. }
  1309. }
  1310. else
  1311. {
  1312. if (dblist!=null && dblist.review==1) {
  1313. list.qrcodeDays = 1;
  1314. list.qrcodeExpire = 0;
  1315. string key = $"GroupList:GroupWaitingList:{list.scope}:{list.id}";
  1316. var datas = await _azureRedis.GetRedisClient(8).HashGetAllAsync(key);
  1317. List<GroupWaitingList> groupWaitingLists = new List<GroupWaitingList>();
  1318. foreach (var rcd in datas)
  1319. {
  1320. var value = rcd.Value.ToString().ToObject<GroupWaitingList>();
  1321. if (value!=null) { groupWaitingLists.Add(value); }
  1322. }
  1323. if (groupWaitingLists.IsNotEmpty()) {
  1324. var takeCount = list.limitCount-dblist.members.Count;
  1325. if (takeCount>0)
  1326. {
  1327. var takes = groupWaitingLists.OrderBy(x => x.applyTime).Take(takeCount);
  1328. if (takes!=null && takes.Count()>0)
  1329. {
  1330. foreach (var t in takes)
  1331. {
  1332. GroupListService.JoinList(list, t.userid, t.type, t.school, t.year,t.seatNo);
  1333. string stuKey = !string.IsNullOrWhiteSpace(school) ? $"GroupList:StudentWaitinglist:{school}_{t.userid}" : $"GroupList:StudentWaitinglist:{t.userid}";
  1334. string stuFiled = $"{list.scope}:{list.id}";
  1335. var data = await _azureRedis.GetRedisClient(8).HashGetAsync(stuKey, stuFiled);
  1336. if (data != default && !data.IsNullOrEmpty)
  1337. {
  1338. var value = data.ToString().ToObject<GroupWaitingList>();
  1339. value.status=0;
  1340. await _azureRedis.GetRedisClient(8).HashSetAsync(stuKey, stuFiled, value.ToJsonString());
  1341. }
  1342. }
  1343. //未自动加入的,直接拒绝
  1344. var untakes = groupWaitingLists.Except(takes);
  1345. if (untakes!=null && untakes.Count()>0)
  1346. {
  1347. foreach (var t in takes)
  1348. {
  1349. string stuKey = !string.IsNullOrWhiteSpace(school) ? $"GroupList:StudentWaitinglist:{school}_{t.userid}" : $"GroupList:StudentWaitinglist:{t.userid}";
  1350. string stuFiled = $"{list.scope}:{list.id}";
  1351. var data = await _azureRedis.GetRedisClient(8).HashGetAsync(stuKey, stuFiled);
  1352. if (data != default && !data.IsNullOrEmpty)
  1353. {
  1354. var value = data.ToString().ToObject<GroupWaitingList>();
  1355. value.status=1;
  1356. await _azureRedis.GetRedisClient(8).HashSetAsync(stuKey, stuFiled, value.ToJsonString());
  1357. }
  1358. }
  1359. }
  1360. }
  1361. }
  1362. else
  1363. {
  1364. //已经加满,删除候选
  1365. foreach (var t in groupWaitingLists)
  1366. {
  1367. string stuKey = !string.IsNullOrWhiteSpace(school) ? $"GroupList:StudentWaitinglist:{school}_{t.userid}" : $"GroupList:StudentWaitinglist:{t.userid}";
  1368. string stuFiled = $"{list.scope}:{list.id}";
  1369. var data = await _azureRedis.GetRedisClient(8).HashGetAsync(stuKey, stuFiled);
  1370. if (data != default && !data.IsNullOrEmpty)
  1371. {
  1372. var value = data.ToString().ToObject<GroupWaitingList>();
  1373. value.status=1;
  1374. await _azureRedis.GetRedisClient(8).HashSetAsync(stuKey, stuFiled, value.ToJsonString());
  1375. }
  1376. }
  1377. }
  1378. }
  1379. await _azureRedis.GetRedisClient(8).KeyDeleteAsync(key);
  1380. }
  1381. }
  1382. }
  1383. else
  1384. {
  1385. //学校自定义名单
  1386. list.code = !list.code.StartsWith("GroupList-") ? $"GroupList-{list.code}" : list.code;
  1387. }
  1388. switch (true)
  1389. {
  1390. //普通学生名单(包含学校教学班名单,个人课程名单),其中学生成员账号类型可以是学校学生账号和醍摩豆ID,分区键为GroupList-hbcn
  1391. case bool when $"{list.type}".Equals("teach", StringComparison.OrdinalIgnoreCase):
  1392. list.type = "teach";
  1393. list = await GroupListService.CheckListNo(list, _azureCosmos, _dingDing, _option);
  1394. list = await GroupListService.UpsertList(list, _azureCosmos, _configuration, _serviceBus);
  1395. break;
  1396. //教研组名单,只有加入学校的老师名单 成员账号类型是醍摩豆ID,保存在学校表,分区键为GroupList-hbcn
  1397. case bool when $"{list.type}".Equals("research", StringComparison.OrdinalIgnoreCase):
  1398. list.type = "research";
  1399. list.scope = "school";
  1400. list = await GroupListService.UpsertList(list, _azureCosmos, _configuration, _serviceBus);
  1401. break;
  1402. //个人好友名单,成员账号类型可以是学校学生账号和醍摩豆ID,分区键为GroupList
  1403. case bool when $"{list.type}".Equals("friend", StringComparison.OrdinalIgnoreCase):
  1404. list.type = "friend";
  1405. list.scope = "private";
  1406. list = await GroupListService.UpsertList(list, _azureCosmos, _configuration, _serviceBus);
  1407. break;
  1408. //社交群组类型(包含学校交流群组,个人交流群组),成员账号类型可以是学校学生账号和醍摩豆ID,,分区键为GroupList-hbcn
  1409. case bool when $"{list.type}".Equals("group", StringComparison.OrdinalIgnoreCase):
  1410. list.type = "group";
  1411. list = await GroupListService.CheckListNo(list, _azureCosmos, _dingDing, _option);
  1412. list = await GroupListService.UpsertList(list, _azureCosmos, _configuration, _serviceBus);
  1413. break;
  1414. //研修类型成员账号类型可以是学校学生账号和醍摩豆ID,,分区键为GroupList-hbcn
  1415. case bool when $"{list.type}".Equals("yxtrain", StringComparison.OrdinalIgnoreCase):
  1416. list.type = "yxtrain";
  1417. list.scope = "school";
  1418. list = await GroupListService.UpsertList(list, _azureCosmos, _configuration, _serviceBus);
  1419. break;
  1420. default:
  1421. return Ok(new { error = 400, msg = "参数错误!" });
  1422. }
  1423. return Ok(new { list });
  1424. }
  1425. catch (Exception ex)
  1426. {
  1427. await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/upsert-grouplist()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1428. return BadRequest();
  1429. }
  1430. }
  1431. //删除名单
  1432. [ProducesDefaultResponseType]
  1433. [AuthToken(Roles = "teacher,admin")]
  1434. [HttpPost("delete-grouplist")]
  1435. [Authorize(Roles = "IES")]
  1436. public async Task<IActionResult> DeleteGroupList(JsonElement json)
  1437. {
  1438. try
  1439. {
  1440. if (!json.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1441. if (!json.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  1442. if (!json.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1443. var client = _azureCosmos.GetCosmosClient();
  1444. string tbname = "";
  1445. string datacode = "";
  1446. if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
  1447. {
  1448. tbname = "School";
  1449. datacode = $"GroupList-{code}";
  1450. }
  1451. else
  1452. {
  1453. tbname = "Teacher";
  1454. datacode = $"GroupList";
  1455. }
  1456. try
  1457. {
  1458. await GroupListService.DeleteGrouplistEvent($"{id}", datacode, tbname, client, _configuration, _serviceBus);
  1459. }
  1460. catch (Exception ex) { }
  1461. return Ok(new { id });
  1462. }
  1463. catch (Exception ex)
  1464. {
  1465. await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/delete-grouplist()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1466. return Ok(new { error = 400 });
  1467. }
  1468. }
  1469. /// <summary>
  1470. /// 保存或更新通用名单
  1471. /// </summary>
  1472. /// <param name="json"></param>
  1473. /// <returns></returns>
  1474. [ProducesDefaultResponseType]
  1475. [AuthToken(Roles = "teacher,admin,student")]
  1476. [HttpPost("upsert-group-member")]
  1477. [Authorize(Roles = "IES")]
  1478. public async Task<IActionResult> UpsertGroupMember(JsonElement json)
  1479. {
  1480. if (!json.TryGetProperty("opt", out JsonElement _opt)) { return BadRequest(); }
  1481. if (!json.TryGetProperty("scope", out JsonElement _scope)) { return BadRequest(); }
  1482. if (!json.TryGetProperty("id", out JsonElement _id)) { return BadRequest(); }
  1483. if (!json.TryGetProperty("code", out JsonElement _code)) { return BadRequest(); }
  1484. if (!json.TryGetProperty("type", out JsonElement _type)) { return BadRequest(); }
  1485. try
  1486. {
  1487. GroupList groupList = null;
  1488. string tbname = $"{_scope}".Equals("private") ? "Teacher" : "School";
  1489. string code = "";
  1490. if (string.IsNullOrEmpty($"{_type}") || !$"{_type}".Equals("class"))
  1491. {
  1492. if ($"{_scope}".Equals("private"))
  1493. {
  1494. //私人名单
  1495. code = "GroupList";
  1496. }
  1497. else
  1498. {
  1499. //学校自定义名单
  1500. code = !code.StartsWith("GroupList-") ? $"GroupList-{_code}" : code;
  1501. }
  1502. groupList = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<GroupList>($"{_id}", new PartitionKey($"{code}"));
  1503. }
  1504. switch (true)
  1505. {
  1506. case bool when $"{_opt}".Equals("up-nickname", StringComparison.OrdinalIgnoreCase) && json.TryGetProperty("members", out JsonElement _members):
  1507. var members = _members.ToObject<List<Member>>();
  1508. List<Member> updateSuccess = new List<Member>();
  1509. List<Member> updateFailed = new List<Member>();
  1510. members.ForEach(x =>
  1511. {
  1512. var member = groupList.members.Find(z => z.type == x.type && z.id.Equals(x.id));
  1513. if (member != null)
  1514. {
  1515. member.nickname = x.nickname;
  1516. updateSuccess.Add(member);
  1517. }
  1518. else
  1519. {
  1520. updateFailed.Add(x);
  1521. }
  1522. });
  1523. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<GroupList>(groupList, $"{_id}", new PartitionKey(code));
  1524. return Ok(new { updateSuccess, updateFailed });
  1525. }
  1526. }
  1527. catch (Exception ex)
  1528. {
  1529. await _dingDing.SendBotMsg($"{_option.Location},更新名单成员信息异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.成都开发測試群組);
  1530. return BadRequest();
  1531. }
  1532. return Ok();
  1533. }
  1534. /// <
  1535. /// summary>
  1536. /// 处理名单审核
  1537. /// </summary>
  1538. /// <param name="json"></param>
  1539. /// <returns></returns>
  1540. [ProducesDefaultResponseType]
  1541. [AuthToken(Roles = "teacher,admin,student")]
  1542. [HttpPost("review")]
  1543. #if !DEBUG
  1544. [Authorize(Roles = "IES")]
  1545. #endif
  1546. public async Task<IActionResult> review(JsonElement request)
  1547. {
  1548. (string userId, _, _, string school) = HttpContext.GetAuthTokenInfo();
  1549. if (!request.TryGetProperty("grant_type", out JsonElement grant_type)) return BadRequest();
  1550. var client = _azureCosmos.GetCosmosClient();
  1551. switch (true)
  1552. {
  1553. //待加入列表
  1554. case bool when $"{grant_type}".Equals("waitlist", StringComparison.OrdinalIgnoreCase):
  1555. {
  1556. if (!request.TryGetProperty("id", out JsonElement _id)) return BadRequest();
  1557. if (!request.TryGetProperty("scope", out JsonElement _scope)) return BadRequest();
  1558. //string tbname = ($"{_scope}".Equals("school")) ? Constant.School : Constant.Teacher;
  1559. //string code = $"";
  1560. string key = $"GroupList:GroupWaitingList:{_scope}:{_id}";
  1561. var datas = await _azureRedis.GetRedisClient(8).HashGetAllAsync(key);
  1562. List<GroupWaitingList> waitingLists = new List<GroupWaitingList>();
  1563. if (datas!=null && datas.Length>0)
  1564. {
  1565. foreach (var data in datas)
  1566. {
  1567. var group = data.Value.ToString().ToObject<GroupWaitingList>();
  1568. if (group!=null)
  1569. {
  1570. waitingLists.Add(group);
  1571. }
  1572. }
  1573. }
  1574. return Ok(new { waitingLists });
  1575. }
  1576. //处理审核
  1577. case bool when $"{grant_type}".Equals("process", StringComparison.OrdinalIgnoreCase):
  1578. {
  1579. if (!request.TryGetProperty("id", out JsonElement _id)) return BadRequest();
  1580. if (!request.TryGetProperty("scope", out JsonElement _scope)) return BadRequest();
  1581. if (!request.TryGetProperty("pass", out JsonElement _pass)) return BadRequest();
  1582. if (!request.TryGetProperty("members", out JsonElement _members)) return BadRequest();
  1583. var members = _members.ToObject<List<Member>>();
  1584. string tbname = $"{_scope}".Equals("school") ? Constant.School : Constant.Teacher;
  1585. string code = $"{_scope}".Equals("school") ?$"GroupList-{school}" : "GroupList";
  1586. string key = $"GroupList:GroupWaitingList:{_scope}:{_id}";
  1587. List<GroupWaitingList> waitingLists = new List<GroupWaitingList>();
  1588. if (members.IsNotEmpty()) {
  1589. Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(_id.ToString(), new PartitionKey(code));
  1590. if (response.Status==200)
  1591. {
  1592. GroupList groupList = JsonDocument.Parse(response.Content).RootElement.ToObject<GroupList>();
  1593. bool add=false;
  1594. foreach (var member in members)
  1595. {
  1596. string filed = $"{member.type}".Equals("2") ? $"{school}_{member.id}" : member.id;
  1597. var data = await _azureRedis.GetRedisClient(8).HashGetAsync(key, filed);
  1598. if (data != default && !data.IsNullOrEmpty)
  1599. {
  1600. var value = data.ToString().ToObject<GroupWaitingList>();
  1601. string stuKey = !string.IsNullOrWhiteSpace(school) ? $"GroupList:StudentWaitinglist:{school}_{member.id}" : $"GroupList:StudentWaitinglist:{member.id}";
  1602. string sutFiled = $"{_scope}:{_id}";
  1603. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  1604. if ($"{_pass}".Equals("0"))
  1605. {
  1606. //通过
  1607. if (now>value.qrcodeExpire)
  1608. {
  1609. value.status=2;
  1610. }
  1611. else
  1612. {
  1613. if (groupList!=null)
  1614. {
  1615. var mb = groupList.members.Find(x => x.type==value.type && x.id.Equals(value.userid));
  1616. if (mb== null)
  1617. {
  1618. var joindata = GroupListService.JoinList(groupList, value.userid, value.type, value.school, value.year);
  1619. if (joindata.status==0) {
  1620. add=true;
  1621. }
  1622. }
  1623. }
  1624. value.status=0;
  1625. }
  1626. await _azureRedis.GetRedisClient(8).HashDeleteAsync(key, filed);
  1627. await _azureRedis.GetRedisClient(8).HashSetAsync(stuKey, sutFiled, value.ToJsonString());
  1628. waitingLists.Add(value);
  1629. }
  1630. else if ($"{_pass}".Equals("1"))
  1631. {
  1632. //拒绝
  1633. value.status=1;
  1634. await _azureRedis.GetRedisClient(8).HashDeleteAsync(key, filed);
  1635. await _azureRedis.GetRedisClient(8).HashSetAsync(stuKey, sutFiled, value.ToJsonString());
  1636. waitingLists.Add(value);
  1637. }
  1638. else
  1639. {
  1640. return BadRequest(new { code = 1, msg = "参数错误" });
  1641. }
  1642. }
  1643. }
  1644. if (add)
  1645. {
  1646. await GroupListService.UpsertList(groupList, _azureCosmos, _configuration, _serviceBus);
  1647. }
  1648. }
  1649. }
  1650. return Ok(new { waitingLists });
  1651. }
  1652. //审核结果,学生端获取到被拒绝的,或者过期的自动删除,未被审核的保存
  1653. case bool when $"{grant_type}".Equals("result", StringComparison.OrdinalIgnoreCase):
  1654. {
  1655. string stuKey = !string.IsNullOrWhiteSpace(school) ? $"GroupList:StudentWaitinglist:{school}_{userId}" : $"GroupList:StudentWaitinglist:{userId}";
  1656. var datas = await _azureRedis.GetRedisClient(8).HashGetAllAsync(stuKey);
  1657. List<GroupWaitingList> waitingLists = new List<GroupWaitingList>();
  1658. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  1659. if (datas!=null && datas.Length>0)
  1660. {
  1661. foreach (var data in datas)
  1662. {
  1663. var group = data.Value.ToString().ToObject<GroupWaitingList>();
  1664. if (group!=null)
  1665. {
  1666. waitingLists.Add(group);
  1667. if (group.status!=-1)
  1668. {
  1669. await _azureRedis.GetRedisClient(8).HashDeleteAsync(stuKey, $"{group.groupScope}:{group.groupId}");
  1670. }
  1671. else
  1672. {
  1673. if (now>group.qrcodeExpire)
  1674. {
  1675. group.status=2;
  1676. await _azureRedis.GetRedisClient(8).HashDeleteAsync(stuKey, $"{group.groupScope}:{group.groupId}");
  1677. }
  1678. }
  1679. }
  1680. }
  1681. }
  1682. return Ok(new { waitingLists });
  1683. }
  1684. }
  1685. return BadRequest();
  1686. }
  1687. /// <
  1688. /// summary>
  1689. ///
  1690. /// </summary>
  1691. /// <param name="json"></param>
  1692. /// <returns></returns>
  1693. [ProducesDefaultResponseType]
  1694. [HttpPost("backups-all")]
  1695. #if !DEBUG
  1696. [AuthToken(Roles = "teacher,admin")]
  1697. [Authorize(Roles = "IES")]
  1698. #endif
  1699. public async Task<IActionResult> BackupsAll(JsonElement json) {
  1700. string sqlschool = "select value c from c ";
  1701. var resultSchool = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<School>(sqlschool, "Base");
  1702. List<School> schools = resultSchool.list;
  1703. List<GroupListSemester> listSemesters= new List<GroupListSemester>();
  1704. foreach (var school in schools) {
  1705. string sqlclass = $"select value c from c where c.year<2023 ";
  1706. var resultClass = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<School>(sqlclass, $"Class-{school.id}");
  1707. if (resultClass.list.IsNotEmpty()) {
  1708. var data = await GroupListService.GetMemberByListids(_coreAPIHttpService, _azureCosmos.GetCosmosClient(), _dingDing, resultClass.list.Select(z=>z.id).ToList(), school.id);
  1709. if (data.groups.IsNotEmpty()) {
  1710. foreach(var group in data.groups)
  1711. {
  1712. if(group.members.IsNotEmpty())
  1713. {
  1714. var period = school.period.Find(z => z.id.Equals(group.periodId));
  1715. if (period != null)
  1716. {
  1717. {
  1718. //2023-06-01
  1719. var dataSemester = SchoolService.GetSemester(period, 1688140800000);
  1720. string id = $"{dataSemester.studyYear}-{dataSemester.currSemester.id}-{group.id}";
  1721. string code = $"GroupListSemester-{school.id}";
  1722. GroupListSemester groupListSemester = group.ToJsonString().ToObject<GroupListSemester>();
  1723. groupListSemester.id = id;
  1724. groupListSemester.code = code;
  1725. groupListSemester.pk="GroupListSemester";
  1726. groupListSemester.semesterId=dataSemester.currSemester.id;
  1727. groupListSemester.groupListId=group.id;
  1728. groupListSemester.studyYear=dataSemester.studyYear;
  1729. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync<GroupListSemester>(groupListSemester, new PartitionKey(groupListSemester.code));
  1730. listSemesters.Add(groupListSemester);
  1731. }
  1732. {
  1733. //2022-11-01
  1734. var dataSemester = SchoolService.GetSemester(period, 1667232000000);
  1735. string id = $"{dataSemester.studyYear}-{dataSemester.currSemester.id}-{group.id}";
  1736. string code = $"GroupListSemester-{school.id}";
  1737. GroupListSemester groupListSemester = group.ToJsonString().ToObject<GroupListSemester>();
  1738. groupListSemester.id = id;
  1739. groupListSemester.code = code;
  1740. groupListSemester.pk="GroupListSemester";
  1741. groupListSemester.semesterId=dataSemester.currSemester.id;
  1742. groupListSemester.groupListId=group.id;
  1743. groupListSemester.studyYear=dataSemester.studyYear;
  1744. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync<GroupListSemester>(groupListSemester, new PartitionKey(groupListSemester.code));
  1745. listSemesters.Add(groupListSemester);
  1746. }
  1747. //{
  1748. // //2022-06-01
  1749. // var dataSemester = SchoolService.GetSemester(period, 1654012800000);
  1750. // string id = $"{dataSemester.studyYear}-{dataSemester.currSemester.id}-{group.id}";
  1751. // string code = $"GroupListSemester-{school.id}";
  1752. // GroupListSemester groupListSemester = group.ToJsonString().ToObject<GroupListSemester>();
  1753. // groupListSemester.id = id;
  1754. // groupListSemester.code = code;
  1755. // groupListSemester.pk="GroupListSemester";
  1756. // groupListSemester.semesterId=dataSemester.currSemester.id;
  1757. // groupListSemester.groupListId=group.id;
  1758. // groupListSemester.studyYear=dataSemester.studyYear;
  1759. // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync<GroupListSemester>(groupListSemester, new PartitionKey(groupListSemester.code));
  1760. // listSemesters.Add(groupListSemester);
  1761. //}
  1762. //{
  1763. // //2021-11-01
  1764. // var dataSemester = SchoolService.GetSemester(period, 1635696000000);
  1765. // string id = $"{dataSemester.studyYear}-{dataSemester.currSemester.id}-{group.id}";
  1766. // string code = $"GroupListSemester-{school.id}";
  1767. // GroupListSemester groupListSemester = group.ToJsonString().ToObject<GroupListSemester>();
  1768. // groupListSemester.id = id;
  1769. // groupListSemester.code = code;
  1770. // groupListSemester.pk="GroupListSemester";
  1771. // groupListSemester.semesterId=dataSemester.currSemester.id;
  1772. // groupListSemester.groupListId=group.id;
  1773. // groupListSemester.studyYear=dataSemester.studyYear;
  1774. // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync<GroupListSemester>(groupListSemester, new PartitionKey(groupListSemester.code));
  1775. // listSemesters.Add(groupListSemester);
  1776. //}
  1777. }
  1778. }
  1779. }
  1780. }
  1781. }
  1782. }
  1783. return Ok(listSemesters.Count);
  1784. }
  1785. /// <
  1786. /// summary>
  1787. ///
  1788. /// </summary>
  1789. /// <param name="json"></param>
  1790. /// <returns></returns>
  1791. [ProducesDefaultResponseType]
  1792. [HttpPost("process-grouplist-backups")]
  1793. #if !DEBUG
  1794. [AuthToken(Roles = "teacher,admin")]
  1795. [Authorize(Roles = "IES")]
  1796. #endif
  1797. public async Task<IActionResult> Backups(JsonElement json) {
  1798. if (!json.TryGetProperty("grant_type", out JsonElement _grant_type)) return BadRequest();
  1799. switch (true) {
  1800. case bool when $"{_grant_type}".Equals("ignore", StringComparison.OrdinalIgnoreCase):
  1801. {
  1802. json.TryGetProperty("keys", out JsonElement _keys);
  1803. List<string> keys = _keys.ToObject<List<string>>();
  1804. foreach (var key in keys) {
  1805. var data = await _azureRedis.GetRedisClient(8).StringGetAsync(key);
  1806. if (data.HasValue)
  1807. {
  1808. SemesterStudyYearNotify notify = data.ToString().ToObject<SemesterStudyYearNotify>();
  1809. notify.ignore=1;
  1810. await _azureRedis.GetRedisClient(8).StringSetAsync(key, notify.ToJsonString());
  1811. //3天 * 24 =72小时
  1812. #if DEBUG
  1813. await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, new TimeSpan(0, 0, 60));
  1814. #else
  1815. await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, new TimeSpan(72, 0, 0));
  1816. #endif
  1817. }
  1818. }
  1819. return Ok(new { code = 200 });
  1820. }
  1821. case bool when $"{_grant_type}".Equals("sync_edited", StringComparison.OrdinalIgnoreCase):
  1822. {
  1823. try {
  1824. json.TryGetProperty("editedStus", out JsonElement _editedStus);
  1825. List<GroupListSemester> groupListSemesters = _editedStus.ToObject<List<GroupListSemester>>();
  1826. List<RMember> syncedMembers = new List<RMember>();
  1827. foreach (var z in groupListSemesters)
  1828. {
  1829. z.code=$"GroupListSemester-{z.school}";
  1830. Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync(z.id, new PartitionKey(z.code));
  1831. if (response.Status==200)
  1832. {
  1833. GroupListSemester groupListSemester = JsonDocument.Parse(response.Content).ToObject<GroupListSemester>();
  1834. var notIn = z.members.ExceptBy(groupListSemester.members.Select(z => z.id), x => x.id);
  1835. if (notIn!=null && notIn.Count()>0)
  1836. {
  1837. syncedMembers.AddRange(notIn);
  1838. groupListSemester.members.AddRange(notIn);
  1839. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync(groupListSemester, new PartitionKey(z.code));
  1840. }
  1841. }
  1842. else
  1843. {
  1844. z.scope="school";
  1845. z.type="class";
  1846. z.pk= "GroupListSemester";
  1847. syncedMembers.AddRange(z.members);
  1848. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync(z, new PartitionKey(z.code));
  1849. }
  1850. }
  1851. return Ok(new { code = 200 , syncedMembers });
  1852. }
  1853. catch (Exception ex ){
  1854. await _dingDing.SendBotMsg($"{_option.Location},{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  1855. return Ok(new { code = 500 });
  1856. }
  1857. }
  1858. }
  1859. return Ok(new { code=400 });
  1860. }
  1861. //新学年8.1号开学 ,第二学期开学2.17,设置提示区间60天
  1862. //2023-8-7 type = "studyYearStarted";新学年已经开始
  1863. //2023-10-7 type = "";不提示
  1864. //2024-1-20 type = "semesterEnding";本学期即将结束
  1865. //2024-3-20 type = "semesterStarted";新学期已经开始
  1866. //2024-4-20 type = "";不提示
  1867. //2024-7-20 type = "studyYearEnding";本学年即将结束
  1868. /// <
  1869. /// summary>
  1870. /// 检查当前学期的开学时间和学期结束时间
  1871. /// </summary>
  1872. /// <param name="json"></param>
  1873. /// <returns></returns>
  1874. [ProducesDefaultResponseType]
  1875. [HttpPost("check-class-sync")]
  1876. #if !DEBUG
  1877. [AuthToken(Roles = "teacher,admin")]
  1878. [Authorize(Roles = "IES")]
  1879. #endif
  1880. public async Task<IActionResult> CheckSemesters(JsonElement json)
  1881. {
  1882. if (!json.TryGetProperty("schoolId", out JsonElement _schoolId)) { return BadRequest(); }
  1883. School school = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(_schoolId.GetString(), new PartitionKey("Base"));
  1884. List<dynamic> periodNotify = new List<dynamic>();
  1885. foreach (var period in school.period) {
  1886. if (period!=null)
  1887. {
  1888. //var semesterInfo = SchoolService.GetSemester(period, DateTimeOffset.Now.ToUnixTimeMilliseconds());
  1889. var semesterInfo = SchoolService.GetSemester(period, time:$"{json.GetProperty("time")}");
  1890. var start = period.semesters.Where(z => z.start==1).FirstOrDefault();
  1891. if (start!=null)
  1892. {
  1893. var alreadySemester = semesterInfo.date.Subtract(semesterInfo.currSemesterDate);
  1894. var soonSemester = semesterInfo.nextSemester.Subtract(semesterInfo.date);
  1895. var semesterStarted = Math.Abs((int)alreadySemester.TotalDays);
  1896. var semesterEnding = Math.Abs((int)soonSemester.TotalDays);
  1897. string currStudyYear = $"{semesterInfo.studyYear}-{start.month}-{start.day}";
  1898. string nextStudyYear = $"{(semesterInfo.studyYear+1)}-{start.month}-{start.day}";
  1899. DateTimeOffset.TryParse(currStudyYear, out DateTimeOffset currYear);
  1900. DateTimeOffset.TryParse(nextStudyYear, out DateTimeOffset nextYear);
  1901. var alreadyYear = semesterInfo.date.Subtract(currYear);
  1902. var soonYear = nextYear.Subtract(semesterInfo.date);
  1903. var studyYearStarted = Math.Abs((int)alreadyYear.TotalDays);
  1904. var studyYearEnding = Math.Abs((int)soonYear.TotalDays);
  1905. string type = string.Empty;
  1906. //开始天数小于60天
  1907. if (semesterStarted<=60)
  1908. {
  1909. type = "semesterStarted";
  1910. }
  1911. //结束天数小于60天
  1912. if (semesterEnding<=60)
  1913. {
  1914. type = "semesterEnding";
  1915. }
  1916. //开始天数小于60天
  1917. if (studyYearStarted<=60)
  1918. {
  1919. type = "studyYearStarted";
  1920. }
  1921. //结束天数小于60天
  1922. if (studyYearEnding<=60)
  1923. {
  1924. type = "studyYearEnding";
  1925. }
  1926. string sqlClass = string.Empty;
  1927. string idPrefix = string.Empty;
  1928. string key =string.Empty;
  1929. var lastSemesterDate = semesterInfo.currSemesterDate.AddDays(-1);
  1930. var lastSemesterInfo = SchoolService.GetSemester(period, lastSemesterDate.ToUnixTimeMilliseconds());
  1931. if (type.Contains("Started"))
  1932. { //semesterStarted studyYearStarted
  1933. //获取上学期的任意时间,以获取学年,学期信息。
  1934. sqlClass = $"select value c from c where c.year >={lastSemesterInfo.studyYear-period.grades.Count+1} and c.year <={lastSemesterInfo.studyYear} and c.periodId='{period.id}' ";
  1935. idPrefix=$"{lastSemesterInfo.studyYear}-{lastSemesterInfo.currSemester.id}-";
  1936. key = $"SemesterStudyYearNotify:{_schoolId}:{lastSemesterInfo.studyYear}:{lastSemesterInfo.currSemester.id}:{type}";
  1937. }
  1938. //Ending //semesterEnding studyYearEnding
  1939. else
  1940. {
  1941. sqlClass = $"select value c from c where c.year >={semesterInfo.studyYear-period.grades.Count+1} and c.year <={semesterInfo.studyYear} and c.periodId='{period.id}' ";
  1942. idPrefix=$"{semesterInfo.studyYear}-{semesterInfo.currSemester.id}-";
  1943. key = $"SemesterStudyYearNotify:{_schoolId}:{semesterInfo.studyYear}:{semesterInfo.currSemester.id}:{type}";
  1944. }
  1945. var keyExists = await _azureRedis.GetRedisClient(8).KeyExistsAsync(key);
  1946. if (keyExists)
  1947. {
  1948. var data = await _azureRedis.GetRedisClient(8).StringGetAsync(key);
  1949. if (data.HasValue)
  1950. {
  1951. SemesterStudyYearNotify notify = data.ToString().ToObject<SemesterStudyYearNotify>();
  1952. if (notify.ignore==1)
  1953. {
  1954. //忽略提示
  1955. type="";
  1956. }
  1957. else
  1958. {
  1959. //已经处理过的不再处理
  1960. if (notify.process==1)
  1961. {
  1962. type="";
  1963. }
  1964. }
  1965. }
  1966. }
  1967. else
  1968. {
  1969. await _azureRedis.GetRedisClient(8).StringSetAsync(key, new SemesterStudyYearNotify { studyYear=semesterInfo.studyYear, semester=semesterInfo.currSemester.id, ignore=0, type=type }.ToJsonString());
  1970. //60天 * 24 =1440小时
  1971. await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, new TimeSpan(1440, 0, 0));
  1972. }
  1973. /*
  1974. //2022-11-01
  1975. var dataSemester = SchoolService.GetSemester(period, 1667232000000);
  1976. string id = $"{dataSemester.studyYear}-{dataSemester.currSemester.id}-{group.id}";
  1977. string code = $"GroupListSemester-{school.id}";
  1978. GroupListSemester groupListSemester = group.ToJsonString().ToObject<GroupListSemester>();
  1979. groupListSemester.id = id;
  1980. groupListSemester.code = code;
  1981. groupListSemester.pk="GroupListSemester";
  1982. groupListSemester.semesterId=dataSemester.currSemester.id;
  1983. groupListSemester.groupListId=group.id;
  1984. groupListSemester.studyYear=dataSemester.studyYear;
  1985. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync<GroupListSemester>(groupListSemester, new PartitionKey(groupListSemester.code));
  1986. listSemesters.Add(groupListSemester);
  1987. */
  1988. //已同步的学生。
  1989. List<Student> syncedStus = new List<Student>();
  1990. //未同步的学生
  1991. //List<dynamic> unsyncStus = new List<dynamic>();
  1992. //有调整的学生
  1993. List<dynamic> editedStus = new List<dynamic>();
  1994. if (!string.IsNullOrWhiteSpace(type))
  1995. {
  1996. var resultClasses = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<Class>(sqlClass, $"Class-{school.id}");
  1997. if (resultClasses.list.IsNotEmpty()) {
  1998. string sqlStudents = $"select value c from c where c.classId in ({string.Join(",", resultClasses.list.Select(z => $"'{z.id}'"))})";
  1999. var resultStudents = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).GetList<Student>(sqlStudents, $"Base-{school.id}");
  2000. if (resultStudents.list.IsNotEmpty()) {
  2001. foreach (var clazz in resultClasses.list) {
  2002. string id = $"{idPrefix}{clazz.id}";
  2003. string code = $"GroupListSemester-{school.id}";
  2004. var studentList = resultStudents.list.FindAll(z => z.classId.Equals(clazz.id));
  2005. Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync(id, new PartitionKey(code));
  2006. if (response.Status==200)
  2007. {
  2008. bool changeGroupListSemester = false;
  2009. GroupListSemester groupListSemester = JsonDocument.Parse(response.Content).ToObject<GroupListSemester>();
  2010. var stuslist = studentList.ExceptBy(groupListSemester.members.Select(z=>z.id), x => x.id);
  2011. //学年学期结束 不用处理有更新编辑的学生,直接批量处理。
  2012. if (type.Contains("Ending", StringComparison.OrdinalIgnoreCase)) {
  2013. if (stuslist.Any() && stuslist.Count()>0)
  2014. {
  2015. //var stus = new
  2016. //{
  2017. // id=id ,
  2018. // status=200,
  2019. // type,
  2020. // periodId = period.id,
  2021. // periodName = period.name,
  2022. // classId = clazz.id,
  2023. // className = clazz.name,
  2024. // students = stuslist.Select(z => new { z.id, z.name, z.picture, z._ts })
  2025. //};
  2026. groupListSemester.members.AddRange(stuslist.Select(z => new RMember {
  2027. id= z.id,
  2028. code=z.schoolId,
  2029. name =z.name,
  2030. type=2,
  2031. picture=z.picture,
  2032. gender=z.gender,
  2033. no=z.no,
  2034. irs=z.irs,
  2035. classId=z.classId,
  2036. groupId=z.groupId,
  2037. groupName=z.groupName,
  2038. graduate=z.graduate,
  2039. year=z.year,
  2040. periodId=z.periodId,
  2041. }));
  2042. changeGroupListSemester = true;
  2043. }
  2044. }
  2045. if (type.Contains("Started", StringComparison.OrdinalIgnoreCase))
  2046. {
  2047. if (stuslist.Any() && stuslist.Count()>0) {
  2048. //获取开学时间
  2049. var kxdata = $"{semesterInfo.currSemesterDate.Year}-{semesterInfo.currSemester.month}-{semesterInfo.currSemester.day}";
  2050. DateTimeOffset.TryParse(kxdata, out DateTimeOffset kxData);
  2051. long time = kxData.ToUnixTimeSeconds();
  2052. var editStu = stuslist.Where(z => z._ts>=time);
  2053. if (editStu!=null && editStu.Count()>0) {
  2054. var stus = new
  2055. {
  2056. id = id,
  2057. status = 404,
  2058. type,
  2059. periodId = period.id,
  2060. periodName = period.name,
  2061. groupListId = clazz.id,
  2062. name = clazz.name,
  2063. className = clazz.name,
  2064. school = school.id,
  2065. no = clazz.no,
  2066. year = clazz.year,
  2067. studyYear = lastSemesterInfo.studyYear,
  2068. semesterId = lastSemesterInfo.currSemester.id,
  2069. leader = clazz.teacher?.id,
  2070. grades = new List<int> { clazz.year },
  2071. members = editStu.Select(z => new {
  2072. z.id,
  2073. code = z.schoolId,
  2074. gender = z.gender,
  2075. no = z.no,
  2076. irs = z.irs,
  2077. classId = z.classId,
  2078. groupId = z.groupId,
  2079. groupName = z.groupName,
  2080. graduate = z.graduate,
  2081. periodId = z.periodId,
  2082. z.name,
  2083. z.picture,
  2084. z._ts,
  2085. z.year
  2086. })
  2087. };
  2088. editedStus.Add(stus);
  2089. }
  2090. var uneditStu = studentList.Where(z => z._ts<time);
  2091. if (uneditStu!=null &&uneditStu.Count()>0)
  2092. {
  2093. //var stus = new
  2094. //{
  2095. // id = id,
  2096. // status = 200,
  2097. // type,
  2098. // periodId = period.id,
  2099. // periodName = period.name,
  2100. // classId = clazz.id,
  2101. // className = clazz.name,
  2102. // students = uneditStu.Select(z => new { z.id, z.name, z.picture, z._ts })
  2103. //};
  2104. groupListSemester.members.AddRange(uneditStu.Select(z => new RMember
  2105. {
  2106. id= z.id,
  2107. code=z.schoolId,
  2108. name =z.name,
  2109. type=2,
  2110. picture=z.picture,
  2111. gender=z.gender,
  2112. no=z.no,
  2113. irs=z.irs,
  2114. classId=z.classId,
  2115. groupId=z.groupId,
  2116. groupName=z.groupName,
  2117. graduate=z.graduate,
  2118. year=z.year,
  2119. periodId=z.periodId,
  2120. }));
  2121. changeGroupListSemester = true;
  2122. }
  2123. }
  2124. }
  2125. if (changeGroupListSemester) {
  2126. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync(groupListSemester, new PartitionKey(code));
  2127. }
  2128. }
  2129. else
  2130. {
  2131. //学年学期结束 不用处理有更新编辑的学生,直接批量处理。
  2132. if (type.Contains("Ending", StringComparison.OrdinalIgnoreCase))
  2133. {
  2134. //var stus = new
  2135. //{
  2136. // id = id,
  2137. // status = 404,
  2138. // type,
  2139. // periodId = period.id,
  2140. // periodName = period.name,
  2141. // classId = clazz.id,
  2142. // className = clazz.name,
  2143. // students = studentList.Select(z => new { z.id, z.name, z.picture, z._ts })
  2144. //};
  2145. GroupListSemester groupListSemester = new GroupListSemester();
  2146. groupListSemester.id = id;
  2147. groupListSemester.name=clazz.name;
  2148. groupListSemester.no=clazz.no;
  2149. groupListSemester.periodId=period.id;
  2150. groupListSemester.scope="school";
  2151. groupListSemester.school=school.id;
  2152. groupListSemester.type="class";
  2153. groupListSemester.year=clazz.year;
  2154. groupListSemester.studyYear=semesterInfo.studyYear;
  2155. groupListSemester.code = code;
  2156. groupListSemester.pk="GroupListSemester";
  2157. groupListSemester.semesterId=semesterInfo.currSemester.id;
  2158. groupListSemester.groupListId=clazz.id;
  2159. groupListSemester.members.AddRange(studentList.Select(z => new RMember
  2160. {
  2161. id= z.id,
  2162. code=z.schoolId,
  2163. name =z.name,
  2164. type=2,
  2165. picture=z.picture,
  2166. gender=z.gender,
  2167. no=z.no,
  2168. irs=z.irs,
  2169. classId=z.classId,
  2170. groupId=z.groupId,
  2171. groupName=z.groupName,
  2172. graduate=z.graduate,
  2173. year=z.year,
  2174. periodId=z.periodId,
  2175. }));
  2176. groupListSemester.scount = groupListSemester.members.Count();
  2177. groupListSemester.leader=clazz.teacher?.id;
  2178. groupListSemester.grades.Add(clazz.year);
  2179. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync<GroupListSemester>(groupListSemester, new PartitionKey(groupListSemester.code));
  2180. }
  2181. //开始则需要处理当前学期有变更的学生数据
  2182. if (type.Contains("Started", StringComparison.OrdinalIgnoreCase))
  2183. {
  2184. //获取开学时间
  2185. var kxdata = $"{semesterInfo.currSemesterDate.Year}-{semesterInfo.currSemester.month}-{semesterInfo.currSemester.day}";
  2186. DateTimeOffset.TryParse(kxdata, out DateTimeOffset kxData);
  2187. long time = kxData.ToUnixTimeSeconds();
  2188. //在开学日期之后编辑的学生
  2189. var editStu = studentList.FindAll(z => z._ts>=time);
  2190. if (editStu.IsNotEmpty()) {
  2191. var stus = new
  2192. {
  2193. id = id,
  2194. status = 404,
  2195. type,
  2196. periodId = period.id,
  2197. periodName = period.name,
  2198. groupListId = clazz.id,
  2199. name = clazz.name,
  2200. className = clazz.name,
  2201. school = school.id,
  2202. no = clazz.no,
  2203. year = clazz.year,
  2204. studyYear = lastSemesterInfo.studyYear,
  2205. semesterId = lastSemesterInfo.currSemester.id,
  2206. leader = clazz.teacher?.id,
  2207. grades = new List<int> { clazz.year },
  2208. members = editStu.Select(z => new { z.id,
  2209. code = z.schoolId,
  2210. gender = z.gender,
  2211. no = z.no,
  2212. irs = z.irs,
  2213. classId = z.classId,
  2214. groupId = z.groupId,
  2215. groupName = z.groupName,
  2216. graduate = z.graduate,
  2217. periodId = z.periodId,
  2218. z.name, z.picture, z._ts,z.year })
  2219. };
  2220. editedStus.Add(stus);
  2221. }
  2222. //在开学日期之前编辑的学生
  2223. var uneditStu = studentList.FindAll(z => z._ts<time);
  2224. if (uneditStu.IsNotEmpty()) {
  2225. //var stus = new
  2226. //{
  2227. // id = id,
  2228. // status = 404,
  2229. // type,
  2230. // periodId = period.id,
  2231. // periodName = period.name,
  2232. // classId = clazz.id,
  2233. // className = clazz.name,
  2234. // students = uneditStu.Select(z => new { z.id, z.name, z.picture, z._ts })
  2235. //};
  2236. GroupListSemester groupListSemester = new GroupListSemester();
  2237. groupListSemester.id = id;
  2238. groupListSemester.name=clazz.name;
  2239. groupListSemester.no=clazz.no;
  2240. groupListSemester.periodId=period.id;
  2241. groupListSemester.scope="school";
  2242. groupListSemester.school=school.id;
  2243. groupListSemester.type="class";
  2244. groupListSemester.year=clazz.year;
  2245. groupListSemester.studyYear=lastSemesterInfo.studyYear;
  2246. groupListSemester.code = code;
  2247. groupListSemester.pk="GroupListSemester";
  2248. groupListSemester.semesterId=lastSemesterInfo.currSemester.id;
  2249. groupListSemester.groupListId=clazz.id;
  2250. groupListSemester.members.AddRange(studentList.Select(z => new RMember
  2251. {
  2252. id= z.id,
  2253. code=z.schoolId,
  2254. name =z.name,
  2255. type=2,
  2256. picture=z.picture,
  2257. gender=z.gender,
  2258. no=z.no,
  2259. irs=z.irs,
  2260. classId=z.classId,
  2261. groupId=z.groupId,
  2262. groupName=z.groupName,
  2263. graduate=z.graduate,
  2264. year=z.year,
  2265. periodId=z.periodId,
  2266. }));
  2267. groupListSemester.scount = groupListSemester.members.Count();
  2268. groupListSemester.leader=clazz.teacher?.id;
  2269. groupListSemester.grades.Add(clazz.year);
  2270. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync<GroupListSemester>(groupListSemester, new PartitionKey(groupListSemester.code));
  2271. }
  2272. }
  2273. }
  2274. }
  2275. }
  2276. }
  2277. }
  2278. //已经处理过的数据则不需要在进行处理
  2279. if (editedStus.IsEmpty() && !string.IsNullOrWhiteSpace(type))
  2280. {
  2281. keyExists = await _azureRedis.GetRedisClient(8).KeyExistsAsync(key);
  2282. if (keyExists)
  2283. {
  2284. var data = await _azureRedis.GetRedisClient(8).StringGetAsync(key);
  2285. if (data.HasValue)
  2286. {
  2287. SemesterStudyYearNotify notify = data.ToString().ToObject<SemesterStudyYearNotify>();
  2288. notify.process = 1;
  2289. await _azureRedis.GetRedisClient(8).StringSetAsync(key, notify.ToJsonString());
  2290. }
  2291. }
  2292. type="";
  2293. }
  2294. else {
  2295. periodNotify.Add(new { studyYearStarted, studyYearEnding, semesterStarted, semesterEnding, type, key, editedStus, periodId = period.id, periodName = period.name });
  2296. }
  2297. }
  2298. }
  2299. }
  2300. return Ok(new { code = 200, periodNotify });
  2301. }
  2302. }
  2303. }