StudentService.cs 170 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065
  1. using Azure;
  2. using Azure.Cosmos;
  3. using Azure.Messaging.ServiceBus;
  4. using DocumentFormat.OpenXml.Drawing;
  5. using DocumentFormat.OpenXml.Office2010.Excel;
  6. using DocumentFormat.OpenXml.Spreadsheet;
  7. using DocumentFormat.OpenXml.VariantTypes;
  8. using HTEXLib.COMM.Helpers;
  9. using HTEXLib.Helpers.ShapeHelpers;
  10. using Microsoft.AspNetCore.Http;
  11. using Microsoft.Extensions.Configuration;
  12. using NUnit.Framework;
  13. using NUnit.Framework.Interfaces;
  14. using OpenXmlPowerTools;
  15. using System;
  16. using System.Collections.Generic;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Net;
  20. using System.Text;
  21. using System.Text.Json;
  22. using System.Threading.Tasks;
  23. using TEAMModelOS.Models;
  24. using TEAMModelOS.SDK.DI;
  25. using TEAMModelOS.SDK.Extension;
  26. using TEAMModelOS.SDK.Models;
  27. using TEAMModelOS.SDK.Models.Service;
  28. using Member = TEAMModelOS.SDK.Models.Member;
  29. namespace TEAMModelOS.SDK
  30. {
  31. public class StudentService
  32. {
  33. public class StudentActivity
  34. {
  35. public string id { get; set; }
  36. public string code { get; set; }
  37. public string userType { get; set; }
  38. public string stuId { get; set; }
  39. /// <summary>
  40. /// 源数据的发布层级 类型 school teacher
  41. /// </summary>
  42. public string owner { get; set; }
  43. public string pk { get; set; }
  44. //评测模式
  45. public string source { get; set; }
  46. public string name { get; set; }
  47. public long startTime { get; set; }
  48. public long endTime { get; set; }
  49. public string scope { get; set; }
  50. public string school { get; set; }
  51. public string creatorId { get; set; }
  52. public string scode { get; set; }
  53. public string type { get; set; }
  54. public Custom examType { get; set; } = new Custom();
  55. public List<ExamSubject> subjects { get; set; } = new List<ExamSubject>();
  56. public List<string> classIds { get; set; } = new List<string>();
  57. public List<string> classes { get; set; } = new List<string>();
  58. public List<string> stuLists { get; set; } = new List<string>();
  59. public List<string> tchLists { get; set; } = new List<string>();
  60. public long createTime { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  61. public Dictionary<string, JsonElement> ext { get; set; } = new Dictionary<string, JsonElement>();
  62. /// 评分状态,0,未评分, 1已评分
  63. public int sStatus { get; set; } = 0;
  64. //评测 纸本1或者书面问答0
  65. public int qamode { get; set; } = 0;
  66. //标记作业活动是否比交
  67. public bool mustSubmit { get; set; } = false;
  68. //标记问卷是否重复提交 0 否 1 是
  69. public int isSub { get; set; } = 0;
  70. /// <summary>
  71. /// 任务完成状态,-1 未参与,0,未完成, 1已完成
  72. /// </summary>
  73. public int taskStatus { get; set; } = -1;
  74. public string recordUrl { get; set; }
  75. }
  76. /// <summary>
  77. ///
  78. /// </summary>
  79. /// <param name="request"></param>
  80. /// <param name="userId"></param>
  81. /// <param name="userType"></param>
  82. /// <param name="groupListIds"></param>
  83. /// <param name="school"></param>
  84. /// <param name="types">Exam ,Vote,Homework,Survey</param>
  85. /// <param name="_azureCosmos"></param>
  86. /// <param name="azureRedis"></param>
  87. public static async Task<List<StudentActivity>> FindActivity(JsonElement request, string userId, string userScope, List<string> groupListIds, List<string> subjects, string school, List<string> types, AzureCosmosFactory _azureCosmos)
  88. {
  89. string filed = "c.id ,c.code,c.owner,c.pk as type,c.examType,c.qamode,c.name,c.school,c.startTime,c.endTime,c.classes,c.stuLists,c.tchLists,c.createTime,c.creatorId,c.isSub,c.mustSubmit,c.sStatus,c.scope,c.source,c.subjects";
  90. if (string.IsNullOrWhiteSpace(school))
  91. {
  92. if (request.TryGetProperty("school", out JsonElement schooljson))
  93. {
  94. if (!schooljson.ValueKind.Equals(JsonValueKind.Undefined) && !schooljson.ValueKind.Equals(JsonValueKind.Null) && schooljson.ValueKind.Equals(JsonValueKind.String))
  95. {
  96. school = schooljson.GetString();
  97. }
  98. }
  99. }
  100. long stime = DateTimeOffset.UtcNow.AddDays(-30).ToUnixTimeMilliseconds(), etime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  101. if (request.TryGetProperty("stime", out JsonElement _stime))
  102. {
  103. if (!_stime.ValueKind.Equals(JsonValueKind.Undefined) && !_stime.ValueKind.Equals(JsonValueKind.Null) && _stime.TryGetInt64(out long data))
  104. {
  105. stime = data;
  106. }
  107. }
  108. if (request.TryGetProperty("etime", out JsonElement _etime))
  109. {
  110. if (!_etime.ValueKind.Equals(JsonValueKind.Undefined) && !_etime.ValueKind.Equals(JsonValueKind.Null) && _etime.TryGetInt64(out long data))
  111. {
  112. etime = data;
  113. }
  114. }
  115. string groupListSQL = string.Empty;
  116. if (groupListIds.IsNotEmpty())
  117. {
  118. List<string> arrayStr = new List<string>();
  119. groupListIds.ForEach(z =>
  120. {
  121. arrayStr.Add($"array_contains(c.classes,'{z}') ");
  122. arrayStr.Add($"array_contains(c.stuLists,'{z}') ");
  123. if (userScope.Equals(Constant.ScopeTeacher))
  124. {
  125. arrayStr.Add($"array_contains(c.tchLists,'{z}') ");
  126. }
  127. });
  128. groupListSQL = $"and ({string.Join(" or ", arrayStr)})";
  129. }
  130. else
  131. {
  132. throw new Exception("名单为空");
  133. }
  134. List<StudentActivity> datas = new List<StudentActivity>();
  135. if (types.IsEmpty() || types.Contains("Exam"))
  136. {
  137. string subjectSQL = "";
  138. string subjectJoin = "";
  139. if (subjects.IsNotEmpty())
  140. {
  141. subjectJoin = "join s in c.subjects";
  142. subjectSQL = $" and s.id in ({string.Join(",", subjects.Select(z => $"'{z}'"))}) ";
  143. }
  144. StringBuilder SQL = new StringBuilder($"select distinct {filed} from c {subjectJoin} where c.pk='Exam' {subjectSQL} {groupListSQL} and c.startTime>={stime} and c.startTime <= {etime} and c.qamode != 2 ");
  145. //获取学校发布的活动
  146. if (userScope.Equals(Constant.ScopeStudent) && !string.IsNullOrWhiteSpace(school))
  147. {
  148. var resultSchool = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList<StudentActivity>($"{SQL} and c.owner='school' ", $"Exam-{school}");
  149. if (resultSchool.list.Count > 0) {
  150. List<StudentActivity> activity = await getStuActivity(_azureCosmos, resultSchool.list, school, userId, userScope);
  151. datas.AddRange(activity);
  152. }
  153. }
  154. //获取教师发布的活动(个人名单,学校名单)
  155. {
  156. var resultTeacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList<StudentActivity>($"{SQL} and c.owner='teacher' ");
  157. if(resultTeacher.list.Count > 0) {
  158. List<StudentActivity> activity = await getStuActivity(_azureCosmos, resultTeacher.list, school, userId, userScope);
  159. datas.AddRange(activity);
  160. }
  161. }
  162. }
  163. if (types.IsEmpty() || types.Contains("Vote"))
  164. {
  165. StringBuilder SQL = new StringBuilder($"select {filed} from c where c.pk='Vote' {groupListSQL} and c.startTime>={stime} and c.startTime <= {etime} ");
  166. //获取学校发布的活动
  167. if (userScope.Equals(Constant.ScopeStudent) && !string.IsNullOrWhiteSpace(school))
  168. {
  169. var resultSchool = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList<StudentActivity>($"{SQL.ToString()} and c.owner='school' ", $"Vote-{school}");
  170. if (resultSchool.list.Count > 0)
  171. {
  172. foreach (var stu in resultSchool.list)
  173. {
  174. stu.classIds = stu.classes;
  175. }
  176. }
  177. datas.AddRange(resultSchool.list);
  178. }
  179. //获取教师发布的活动(个人名单,学校名单)
  180. {
  181. var resultTeacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList<StudentActivity>($"{SQL.ToString()} and c.owner='teacher' ");
  182. if (resultTeacher.list.Count > 0)
  183. {
  184. foreach (var stu in resultTeacher.list)
  185. {
  186. stu.classIds = stu.stuLists;
  187. }
  188. }
  189. datas.AddRange(resultTeacher.list);
  190. }
  191. }
  192. if (types.IsEmpty() || types.Contains("Survey"))
  193. {
  194. StringBuilder SQL = new StringBuilder($"select {filed} from c where c.pk='Survey' {groupListSQL} and c.startTime>={stime} and c.startTime <= {etime} ");
  195. //获取学校发布的活动
  196. if (userScope.Equals(Constant.ScopeStudent) && !string.IsNullOrWhiteSpace(school))
  197. {
  198. var resultSchool = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList<StudentActivity>($"{SQL.ToString()} and c.owner='school' ", $"Survey-{school}");
  199. if (resultSchool.list.Count > 0)
  200. {
  201. foreach (var stu in resultSchool.list)
  202. {
  203. stu.classIds = stu.classes;
  204. }
  205. }
  206. datas.AddRange(resultSchool.list);
  207. }
  208. //获取教师发布的活动(个人名单,学校名单)
  209. {
  210. var resultTeacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList<StudentActivity>($"{SQL.ToString()} and c.owner='teacher' ");
  211. if (resultTeacher.list.Count > 0)
  212. {
  213. foreach (var stu in resultTeacher.list)
  214. {
  215. stu.classIds = stu.stuLists;
  216. }
  217. }
  218. datas.AddRange(resultTeacher.list);
  219. }
  220. }
  221. if (types.IsEmpty() || types.Contains("Homework"))
  222. {
  223. StringBuilder SQL = new StringBuilder($"select {filed} from c where c.pk='Homework' {groupListSQL} and c.startTime>={stime} and c.startTime <= {etime} ");
  224. //获取学校发布的活动
  225. if (userScope.Equals(Constant.ScopeStudent) && !string.IsNullOrWhiteSpace(school))
  226. {
  227. var resultSchool = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList<StudentActivity>($"{SQL.ToString()} and c.owner='school' ", $"Homework-{school}");
  228. if (resultSchool.list.Count > 0)
  229. {
  230. foreach (var stu in resultSchool.list)
  231. {
  232. stu.classIds = stu.classes;
  233. }
  234. }
  235. datas.AddRange(resultSchool.list);
  236. }
  237. //获取教师发布的活动(个人名单,学校名单)
  238. {
  239. var resultTeacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList<StudentActivity>($"{SQL.ToString()} and c.owner='teacher' ");
  240. if (resultTeacher.list.Count > 0)
  241. {
  242. foreach (var stu in resultTeacher.list)
  243. {
  244. stu.classIds = stu.stuLists;
  245. }
  246. }
  247. datas.AddRange(resultTeacher.list);
  248. }
  249. }
  250. if (types.IsEmpty() || types.Contains("Art"))
  251. {
  252. string subjectSQL = "";
  253. string subjectJoin = "";
  254. if (subjects.IsNotEmpty())
  255. {
  256. subjectJoin = "join s in c.subjects";
  257. subjectSQL = $" and s.id in ({string.Join(",", subjects.Select(z => $"'{z}'"))}) ";
  258. }
  259. StringBuilder SQL = new($"select distinct {filed} from c {subjectJoin} where c.pk='Art' {subjectSQL} {groupListSQL} and c.startTime>={stime} and c.startTime <= {etime} ");
  260. //获取学校发布的活动
  261. if (userScope.Equals(Constant.ScopeStudent) && !string.IsNullOrWhiteSpace(school))
  262. {
  263. var resultSchool = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList<StudentActivity>($"{SQL} and c.school='{school}' ", $"Art-{school}");
  264. if (resultSchool.list.Count > 0)
  265. {
  266. foreach (var stu in resultSchool.list)
  267. {
  268. stu.classIds = stu.classes;
  269. }
  270. }
  271. datas.AddRange(resultSchool.list);
  272. }
  273. }
  274. if (types.IsEmpty() || types.Contains("Study"))
  275. {
  276. StringBuilder SQL = new StringBuilder($"select {filed} from c where c.pk='Study' {groupListSQL} and c.startTime>={stime} and c.startTime <= {etime} ");
  277. //获取学校发布的研修活动
  278. if (userScope.Equals(Constant.ScopeStudent) && !string.IsNullOrWhiteSpace(school))
  279. {
  280. var resultSchool = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList<StudentActivity>($"{SQL} and c.owner='school' ", $"Study-{school}");
  281. datas.AddRange(resultSchool.list);
  282. }
  283. /* //获取教师发布的活动(个人名单,学校名单)
  284. {
  285. var resultTeacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList<StudentActivity>($"{SQL.ToString()} and c.owner='teacher' ");
  286. datas.AddRange(resultTeacher.list);
  287. }*/
  288. }
  289. //作答 记录recordUrl taskStatus
  290. return datas;
  291. }
  292. /// <summary>
  293. ///
  294. /// </summary>
  295. /// <param name="schoolId"></param>
  296. /// <param name="students"></param>
  297. /// <returns></returns>
  298. public static async Task<List<Student>> GeStudentData(AzureCosmosFactory _azureCosmos, string schoolId, IEnumerable<string> students)
  299. {
  300. List<Student> studentDatas = new List<Student>();
  301. if (students.Any())
  302. {
  303. string queryText = $"SELECT c.id, c.code ,c.classId ,c.year FROM c WHERE c.id IN ({string.Join(",", students.Select(o => $"'{o}'"))})";
  304. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  305. {
  306. studentDatas.Add(item);
  307. }
  308. }
  309. return studentDatas;
  310. }
  311. public static async Task<List<StudentActivity>> getStuActivity(AzureCosmosFactory _azureCosmos, List<StudentActivity> activities, string school, string userId, string userScope)
  312. {
  313. //获取所有活动Id
  314. List<string> examIds = activities.Select(c => c.id).ToList();
  315. List<ExamClassResult> examClassResults = new();
  316. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
  317. queryText: $"select value(c) from c where c.examId in ({string.Join(",", examIds.Select(z => $"'{z}'"))}) and c.pk = 'ExamClassResult'" ))
  318. {
  319. examClassResults.Add(item);
  320. }
  321. bool iss = false;
  322. //标记学生作答状态
  323. int ts = 0;
  324. List<(string eId, int status)> et = new();
  325. List<(string eId, bool flag)> es = new();
  326. if (examClassResults.Count > 0)
  327. {
  328. foreach (ExamClassResult exam in examClassResults)
  329. {
  330. //List<(string eId, int status)> examTasks = new();
  331. //List<(string eId, bool flag)> examStatus = new();
  332. int index = exam.studentIds.IndexOf(userId);
  333. if (index != -1)
  334. {
  335. if (exam.studentAnswers[index].Count > 0)
  336. {
  337. bool flag = exam.studentScores[index].Exists(x => x == -1);
  338. if (!flag)
  339. {
  340. ts = 1;
  341. iss = true;
  342. //break;
  343. }
  344. else
  345. {
  346. iss = false;
  347. ts = 0;
  348. }
  349. et.Add((exam.examId, ts));
  350. es.Add((exam.examId,iss));
  351. }
  352. else
  353. {
  354. ts = -1;
  355. iss = false;
  356. et.Add((exam.examId, ts));
  357. es.Add((exam.examId, iss));
  358. }
  359. }
  360. }
  361. }
  362. var stuActivity = activities.Select(x => new StudentActivity
  363. {
  364. id = x.id,
  365. stuId = userId,
  366. userType = userScope,
  367. type = "Exam",
  368. name = x.name,
  369. source = x.source,
  370. startTime = x.startTime,
  371. endTime = x.endTime,
  372. scope = x.scope,
  373. school = x.school,
  374. scode = x.scode,
  375. creatorId = x.creatorId,
  376. subjects = x.subjects,
  377. owner = x.owner,
  378. classIds = x.classes.Count > 0 ? x.classes : x.stuLists,
  379. code = x.code,
  380. createTime = x.createTime,
  381. qamode = x.qamode,
  382. examType = x.examType,
  383. //taskStatus = et.Select(c => c[x.id]).FirstOrDefault(),
  384. //ext = new Dictionary<string, JsonElement>() { { "type", !string.IsNullOrEmpty(x.examType) ? x.examType.ToJsonString().ToObject<JsonElement>():new JsonElement() },
  385. //{ "subjects", x.subjects.ToJsonString().ToObject<JsonElement>() } },
  386. taskStatus = et.Where(c => c.eId.Equals(x.id)).FirstOrDefault().status,
  387. sStatus = es.Where(z => z.eId.Equals(x.id)).FirstOrDefault().flag ? 1 : 0
  388. //sStatus = es.Select(c => c[x.id]).FirstOrDefault() ? 1 : 0
  389. }).ToList();
  390. return stuActivity;
  391. }
  392. /// <summary>
  393. ///
  394. /// </summary>
  395. /// <param name="schoolId">学校编码</param>
  396. /// <param name="students">前端要修改的学生</param>
  397. /// <param name="opt">操作</param>
  398. /// <param name="prestudents">变更前的学生</param>
  399. /// <returns></returns>
  400. public static async Task<Dictionary<string, GroupChange>> CheckStudent(AzureServiceBusFactory _serviceBus, IConfiguration _configuration, AzureCosmosFactory _azureCosmos, string schoolId, List<Student> students, List<Student> prestudents)
  401. {
  402. List<Student> aftstudents = await StudentService.GeStudentData(_azureCosmos, schoolId, students?.Select(x => x.id));
  403. Dictionary<string, GroupChange> dictChange = new Dictionary<string, GroupChange>();
  404. if (prestudents.Count >= aftstudents.Count)
  405. {
  406. foreach (var pstu in prestudents)
  407. {
  408. var afstu = aftstudents.Find(x => x.id.Equals(pstu.id));
  409. if (afstu != null)
  410. {
  411. if (string.IsNullOrEmpty(pstu.classId) && !string.IsNullOrEmpty(afstu.classId))
  412. {
  413. //则是加入的学生
  414. if (dictChange.ContainsKey(afstu.classId))
  415. {
  416. dictChange[afstu.classId].stujoin.Add(
  417. new Member
  418. {
  419. id = afstu.id,
  420. code = $"{schoolId}",
  421. type = 2
  422. });
  423. }
  424. else
  425. {
  426. GroupChange change = new GroupChange
  427. {
  428. scope = "school",
  429. school = schoolId,
  430. type = "student",
  431. originCode = schoolId,
  432. listid = afstu.classId,
  433. stujoin = new List<Member>
  434. {
  435. new Member
  436. {
  437. id= afstu.id,
  438. code= $"{schoolId}",
  439. type =2
  440. }
  441. }
  442. };
  443. dictChange.Add(afstu.classId, change);
  444. }
  445. }
  446. else if (!string.IsNullOrEmpty(pstu.classId) && string.IsNullOrEmpty(afstu.classId))
  447. {
  448. //则该学生是解除了班级状态
  449. if (dictChange.ContainsKey(pstu.classId))
  450. {
  451. dictChange[pstu.classId].stuleave.Add(
  452. new Member
  453. {
  454. id = pstu.id,
  455. code = $"{schoolId}",
  456. type = 2
  457. });
  458. }
  459. else
  460. {
  461. GroupChange change = new GroupChange
  462. {
  463. scope = "school",
  464. school = schoolId,
  465. type = "student",
  466. originCode = schoolId,
  467. listid = pstu.classId,
  468. stuleave = new List<Member>
  469. {
  470. new Member
  471. {
  472. id= pstu.id,
  473. code= $"{schoolId}",
  474. type=2
  475. }
  476. }
  477. };
  478. dictChange.Add(pstu.classId, change);
  479. }
  480. }
  481. else if (!string.IsNullOrEmpty(pstu.classId) && !string.IsNullOrEmpty(afstu.classId))
  482. {
  483. //id不同则有异动
  484. if (!pstu.classId.Equals(afstu.classId))
  485. {
  486. //则是加入的学生
  487. if (dictChange.ContainsKey(afstu.classId))
  488. {
  489. dictChange[afstu.classId].stujoin.Add(
  490. new Member
  491. {
  492. id = afstu.id,
  493. code = $"{schoolId}",
  494. type = 2
  495. });
  496. }
  497. else
  498. {
  499. GroupChange change = new GroupChange
  500. {
  501. scope = "school",
  502. school = schoolId,
  503. type = "student",
  504. originCode = schoolId,
  505. listid = afstu.classId,
  506. stujoin = new List<Member>
  507. {
  508. new Member
  509. {
  510. id= afstu.id,
  511. code= $"{schoolId}",
  512. type = 2
  513. }
  514. }
  515. };
  516. dictChange.Add(afstu.classId, change);
  517. }//则该学生是解除了班级状态
  518. if (dictChange.ContainsKey(pstu.classId))
  519. {
  520. dictChange[pstu.classId].stuleave.Add(
  521. new Member
  522. {
  523. id = pstu.id,
  524. code = $"{schoolId}",
  525. type = 2
  526. });
  527. }
  528. else
  529. {
  530. GroupChange change = new GroupChange
  531. {
  532. scope = "school",
  533. school = schoolId,
  534. type = "student",
  535. originCode = schoolId,
  536. listid = pstu.classId,
  537. stuleave = new List<Member>
  538. {
  539. new Member
  540. {
  541. id= pstu.id,
  542. code= $"{schoolId}",
  543. type= 2
  544. }
  545. }
  546. };
  547. dictChange.Add(pstu.classId, change);
  548. }
  549. }
  550. else
  551. {
  552. //相同则不管
  553. }
  554. }
  555. else
  556. {
  557. //变更前后都没绑定班级则不管。
  558. }
  559. }
  560. else
  561. {
  562. if (!string.IsNullOrEmpty(pstu.classId))
  563. {
  564. //则该学生是被删除的学生
  565. if (dictChange.ContainsKey(pstu.classId))
  566. {
  567. dictChange[pstu.classId].stuleave.Add(
  568. new Member
  569. {
  570. id = pstu.id,
  571. code = $"Base-{schoolId}",
  572. type = 2
  573. });
  574. }
  575. else
  576. {
  577. GroupChange change = new GroupChange
  578. {
  579. scope = "school",
  580. school = schoolId,
  581. type = "student",
  582. originCode = schoolId,
  583. listid = pstu.classId,
  584. stuleave = new List<Member>
  585. {
  586. new Member
  587. {
  588. id= pstu.id,
  589. code= $"{schoolId}",
  590. type = 2
  591. }
  592. }
  593. };
  594. dictChange.Add(pstu.classId, change);
  595. }
  596. }
  597. }
  598. }
  599. }
  600. else
  601. {
  602. foreach (var afstu in aftstudents)
  603. {
  604. var pstu = prestudents.Find(x => x.id.Equals(afstu.id));
  605. if (pstu != null)
  606. {
  607. if (string.IsNullOrEmpty(pstu.classId) && !string.IsNullOrEmpty(afstu.classId))
  608. {
  609. //则是加入的学生
  610. if (dictChange.ContainsKey(afstu.classId))
  611. {
  612. dictChange[afstu.classId].stujoin.Add(
  613. new Member
  614. {
  615. id = afstu.id,
  616. code = $"{schoolId}",
  617. type = 2
  618. });
  619. }
  620. else
  621. {
  622. GroupChange change = new GroupChange
  623. {
  624. scope = "school",
  625. school = schoolId,
  626. type = "student",
  627. originCode = schoolId,
  628. listid = afstu.classId,
  629. stujoin = new List<Member>
  630. {
  631. new Member
  632. {
  633. id= afstu.id,
  634. code= $"Base-{schoolId}",
  635. type = 2
  636. }
  637. }
  638. };
  639. dictChange.Add(afstu.classId, change);
  640. }
  641. }
  642. else if (!string.IsNullOrEmpty(pstu.classId) && string.IsNullOrEmpty(afstu.classId))
  643. {
  644. //则该学生是解除了班级状态
  645. if (dictChange.ContainsKey(pstu.classId))
  646. {
  647. dictChange[pstu.classId].stuleave.Add(
  648. new Member
  649. {
  650. id = pstu.id,
  651. code = $"{schoolId}",
  652. type = 2
  653. });
  654. }
  655. else
  656. {
  657. GroupChange change = new GroupChange
  658. {
  659. scope = "school",
  660. school = schoolId,
  661. type = "student",
  662. originCode = schoolId,
  663. listid = pstu.classId,
  664. stuleave = new List<Member>
  665. {
  666. new Member
  667. {
  668. id= pstu.id,
  669. code= $"{schoolId}",
  670. type= 2
  671. }
  672. }
  673. };
  674. dictChange.Add(pstu.classId, change);
  675. }
  676. }
  677. else if (!string.IsNullOrEmpty(pstu.classId) && !string.IsNullOrEmpty(afstu.classId))
  678. {
  679. //id不同则有异动
  680. if (!pstu.classId.Equals(afstu.classId))
  681. {
  682. //则是加入的学生
  683. if (dictChange.ContainsKey(afstu.classId))
  684. {
  685. dictChange[afstu.classId].stujoin.Add(
  686. new Member
  687. {
  688. id = afstu.id,
  689. code = $"{schoolId}",
  690. type = 2
  691. });
  692. }
  693. else
  694. {
  695. GroupChange change = new GroupChange
  696. {
  697. scope = "school",
  698. school = schoolId,
  699. type = "student",
  700. originCode = schoolId,
  701. listid = afstu.classId,
  702. stujoin = new List<Member>
  703. {
  704. new Member
  705. {
  706. id= afstu.id,
  707. code= $"{schoolId}",
  708. type = 2
  709. }
  710. }
  711. };
  712. dictChange.Add(afstu.classId, change);
  713. }//则该学生是解除了班级状态
  714. if (dictChange.ContainsKey(pstu.classId))
  715. {
  716. dictChange[pstu.classId].stuleave.Add(
  717. new Member
  718. {
  719. id = pstu.id,
  720. code = $"{schoolId}",
  721. type = 2
  722. });
  723. }
  724. else
  725. {
  726. GroupChange change = new GroupChange
  727. {
  728. scope = "school",
  729. school = schoolId,
  730. type = "student",
  731. originCode = schoolId,
  732. listid = pstu.classId,
  733. stuleave = new List<Member>
  734. {
  735. new Member
  736. {
  737. id= pstu.id,
  738. code= $"{schoolId}",
  739. type=2
  740. }
  741. }
  742. };
  743. dictChange.Add(pstu.classId, change);
  744. }
  745. }
  746. else
  747. {
  748. //相同则不管
  749. }
  750. }
  751. else
  752. {
  753. //变更前后都没绑定班级则不管。
  754. }
  755. }
  756. else
  757. {
  758. if (!string.IsNullOrEmpty(afstu.classId))
  759. {
  760. //代表学生是新增的
  761. if (dictChange.ContainsKey(afstu.classId))
  762. {
  763. dictChange[afstu.classId].stujoin.Add(
  764. new Member
  765. {
  766. id = afstu.id,
  767. code = $"{schoolId}",
  768. type = 2
  769. });
  770. }
  771. else
  772. {
  773. GroupChange change = new GroupChange
  774. {
  775. scope = "school",
  776. school = schoolId,
  777. type = "student",
  778. originCode = schoolId,
  779. listid = afstu.classId,
  780. stujoin = new List<Member>
  781. {
  782. new Member
  783. {
  784. id= afstu.id,
  785. code= $"{schoolId}",
  786. type = 2
  787. }
  788. }
  789. };
  790. dictChange.Add(afstu.classId, change);
  791. }
  792. }
  793. }
  794. }
  795. }
  796. foreach (var changed in dictChange.Keys)
  797. {
  798. var change = dictChange[changed];
  799. if (change.stujoin.Count != 0 || change.stuleave.Count != 0)
  800. {
  801. var messageChange = new ServiceBusMessage(change.ToJsonString());
  802. messageChange.ApplicationProperties.Add("name", "GroupChange");
  803. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  804. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
  805. }
  806. }
  807. return dictChange;
  808. }
  809. public record StudentInfo
  810. {
  811. public string studentId { get; set; }
  812. public string picture { get; set; }
  813. public string name { get; set; }
  814. public string mobile { get; set; }
  815. public string mail { get; set; }
  816. /// <summary>
  817. /// f女性 m男性 n 保密
  818. /// </summary>
  819. public string gender { get; set; }
  820. }
  821. /// <summary>
  822. /// 整理前端匯入的學生資訊
  823. /// </summary>
  824. /// <param name="schoolId"></param>
  825. /// <param name="students"></param>
  826. /// <returns></returns>
  827. private static (Dictionary<string, (string name, string no, int year, string salt, string pw, string classNo, string className, string periodId, int classYear,
  828. string guardian, string gName, string gPhone, string imei, List<StudentGuardian> guardians, string gender)> studs,
  829. Dictionary<string, (string className, string periodId, int year, string no)> classInfo,
  830. Dictionary<string, List<(string id, string no)>> classStudNo,
  831. List<string> errorYear,
  832. List<string> duplId) doSortImpStuds(string schoolId, JsonElement.ArrayEnumerator students)
  833. {
  834. //批量匯入 檢查輸入數據 確認座號 確認教室(創建教室) 確認學生存不存在或是要不要更新
  835. //存放輸入的學生資訊 key:stud id value:學生詳細資料
  836. Dictionary<string, (string name, string no, int year, string salt, string pw, string classNo, string className, string periodId, int classYear,
  837. string guardian, string gName, string gPhone, string imei, List<StudentGuardian> guardians, string gender)> dicStuds =
  838. new Dictionary<string, (string name, string no, int year, string salt, string pw, string classNo, string className, string periodId, int classYear,
  839. string guardian, string gName, string gPhone, string imei, List<StudentGuardian> guardians, string gender)>();
  840. //存放教室資訊用 key:classNo value:className
  841. Dictionary<string, (string className, string periodId, int year, string classNo)> dicClassInfo = new Dictionary<string, (string className, string periodId, int year, string classNo)>();
  842. //存放欲加入該間教室的學生座號清單 key:classNo value:no list
  843. Dictionary<string, List<(string id, string no)>> dicClassStudNo = new Dictionary<string, List<(string id, string no)>>();
  844. //存放輸入id重複
  845. List<string> duplId = new List<string>();
  846. List<string> errorYear = new List<string>();
  847. while (students.MoveNext())
  848. {
  849. //string id = null, no = null, name = null, year = null, pw = null, classNo = null, className = null;
  850. JsonElement student = students.Current;
  851. //ClassNo內的座號
  852. //欲加入的教室
  853. //查學生
  854. //該間教室的座號與目前欲更新的是否有重複 有些可能是同教室換座號 反正都要將學生讀出來
  855. //舊學生完整資料+新學生資料
  856. //進行輸入資料的整理
  857. if (student.TryGetProperty("id", out var tmpId))
  858. {
  859. string id = tmpId.GetString();
  860. //如果id欄位是空的,則跳過該筆資料
  861. if (string.IsNullOrWhiteSpace(id)) continue;
  862. //輸入的id不應有重複
  863. if (dicStuds.ContainsKey(id))
  864. {
  865. //如果id重複,則將之從整理清單內清除
  866. duplId.Add(id);
  867. dicStuds.Remove(id);
  868. }
  869. (string name, string no, int year, string salt, string pw, string classNo, string className, string periodId, int classYear,
  870. string guardian, string gName, string gPhone, string imei, List<StudentGuardian> guardians, string gender) studentInfo =
  871. (null, null, 0, null, null, null, null, null, 0, null, null, null, null, null, null);
  872. if (student.TryGetProperty("name", out var tmpName) && !string.IsNullOrWhiteSpace(tmpName.GetString())) studentInfo.name = tmpName.GetString();
  873. //入學學年為必須,故若是無給值則將之紀錄並跳過該筆資料
  874. if (student.TryGetProperty("year", out var tmpYear) && !string.IsNullOrWhiteSpace(Convert.ToString(tmpYear))) studentInfo.year = tmpYear.GetInt32();
  875. else
  876. {
  877. errorYear.Add(id);
  878. continue;
  879. }
  880. //Password,若沒給則使用學號當密碼
  881. studentInfo.salt = Utils.CreatSaltString(8);
  882. studentInfo.pw = student.TryGetProperty("pw", out var tmpPw) && !string.IsNullOrWhiteSpace(tmpPw.GetString())
  883. ? Utils.HashedPassword(tmpPw.GetString(), studentInfo.salt)
  884. : Utils.HashedPassword(id, studentInfo.salt);
  885. if (student.TryGetProperty("periodId", out var tmpPeriodId) && !string.IsNullOrWhiteSpace(tmpPeriodId.GetString())) studentInfo.periodId = tmpPeriodId.GetString();
  886. // if (student.TryGetProperty("gradeIndex", out var tmpGradeIndex)) studentInfo.gradeIndex = tmpGradeIndex.GetInt32();
  887. if (student.TryGetProperty("classNo", out var tmpClassNo) && !string.IsNullOrWhiteSpace(tmpClassNo.GetString()))
  888. {
  889. studentInfo.classNo = tmpClassNo.GetString();
  890. //在新建帳號上,應要給classNo才能設定no,但是若只是已存在的帳號要進行座號更新呢? 為避免使用者出錯,故已存在的帳號也應當給classNo。
  891. if (student.TryGetProperty("no", out var tmpNo) && !string.IsNullOrWhiteSpace(tmpNo.GetString()))
  892. {
  893. studentInfo.no = tmpNo.GetString();
  894. //這邊先將該間教室欲使用到的no整理出來
  895. if (dicClassStudNo.ContainsKey(tmpClassNo.GetString())) dicClassStudNo[tmpClassNo.GetString()].Add((id, tmpNo.GetString()));
  896. else dicClassStudNo.Add(tmpClassNo.GetString(), new List<(string id, string no)>() { (id, tmpNo.GetString()) });
  897. }
  898. //有給classNo才會紀錄className,classNo屬於實體教室門牌號,全校理當只會有一個。
  899. int year = 0;
  900. if (student.TryGetProperty("classYear", out var tmpClassYear) && tmpClassYear.TryGetInt32(out int syear))
  901. {
  902. year = syear;
  903. studentInfo.classYear = syear;
  904. }
  905. if (student.TryGetProperty("className", out var tmpClassName) && !string.IsNullOrWhiteSpace(tmpClassName.GetString()))
  906. {
  907. studentInfo.className = tmpClassName.GetString();
  908. if (!dicClassInfo.ContainsKey($"{studentInfo.periodId}_{year}_{tmpClassNo.GetString()}"))
  909. { dicClassInfo.Add($"{studentInfo.periodId}_{year}_{tmpClassNo.GetString()}", (tmpClassName.GetString(), studentInfo.periodId, year, tmpClassNo.GetString())); }
  910. }
  911. }
  912. ///导入的时候
  913. if (student.TryGetProperty("guardian", out var guardian) && !string.IsNullOrWhiteSpace($"{guardian}"))
  914. {
  915. studentInfo.guardian = $"{guardian}";
  916. student.TryGetProperty("gName", out var gName);
  917. student.TryGetProperty("gPhone", out var gPhone);
  918. studentInfo.gName = $"{gName}";
  919. studentInfo.gPhone = $"{gPhone}";
  920. }
  921. //更新的时候
  922. if (student.TryGetProperty("guardians", out var _guardians) && _guardians.ValueKind.Equals(JsonValueKind.Array))
  923. {
  924. List<StudentGuardian> guardians = _guardians.Deserialize<List<StudentGuardian>>();
  925. studentInfo.guardians = guardians;
  926. }
  927. if (student.TryGetProperty("imei", out var tmpImei) && !string.IsNullOrWhiteSpace($"{tmpImei}")) studentInfo.imei = tmpImei.GetString();
  928. if (student.TryGetProperty("gender", out var tmpgender) && !string.IsNullOrWhiteSpace($"{tmpgender}")) studentInfo.gender = tmpgender.GetString();
  929. //將最後結果加到字典內
  930. dicStuds.Add(id, studentInfo);
  931. }
  932. }
  933. return (dicStuds, dicClassInfo, dicClassStudNo, errorYear, duplId);
  934. }
  935. /// <summary>
  936. /// 更新或是新增學生
  937. /// </summary>
  938. /// <param name="schoolId"></param>
  939. /// <param name="students"></param>
  940. /// <returns></returns>
  941. public static async Task<(List<object> studs, Dictionary<string, List<string>> classDuplNos, List<string> errorIds)> upsertStudents(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option,
  942. string schoolId,
  943. JsonElement.ArrayEnumerator students)
  944. {
  945. try
  946. {
  947. var sortedImpData = doSortImpStuds(schoolId, students);
  948. //var classNos = sortedImpData.classInfo.Select(o => new {key= o.Key, periodId=o.Value.periodId,index= o.Value.gradeIndex,year = o.Value.year }).ToList();
  949. //抓到教室資訊
  950. var classInfos = await getClassInfoUseNo(_azureCosmos, _dingDing, _option, schoolId, sortedImpData.classInfo);
  951. //取出已存在教室的classId,後面查座號要用。
  952. List<Task> tasks = new List<Task>();
  953. //Key:ClassNo Value:No 匯入時只有ClassNo
  954. Dictionary<string, List<(string id, string no)>> classStudNos = new Dictionary<string, List<(string id, string no)>>();
  955. //Key:ClassNo_gradeId Value:ClassId 存放教室no及id的變數
  956. Dictionary<string, (string classId, string className, string periodId, string gradeId, int year)> classNoId = new Dictionary<string, (string classId, string className, string periodId, string gradeId, int year)>();
  957. List<Class> classes = new List<Class>();
  958. foreach (var classInfo in classInfos)
  959. {
  960. classes.Add(classInfo.Value);
  961. string classGradeId = classInfo.Value.gradeId;
  962. int classYear = classInfo.Value.year;
  963. classNoId.Add(classInfo.Value.no + "_" + classYear,
  964. (classInfo.Value.id, classInfo.Value.name, classInfo.Value.periodId, classGradeId, classYear));
  965. tasks.Add(
  966. Task.Run(
  967. async () =>
  968. {
  969. //(id,no)
  970. var studNo = await checkStudNo(_azureCosmos, _dingDing, _option, schoolId, classInfo.Value.id);
  971. classStudNos.Add(classInfo.Value.no + "_" + classInfo.Value.year, studNo);
  972. }));
  973. }
  974. //這邊整理出不存在的教室,之後創建新教室用(比對classNo)。
  975. //var nonexistentClassNo = classNos.Except(classInfos.Select(o => o.Key).ToList());
  976. List<string> exsitkey = new List<string>();
  977. foreach (var classInfo in classInfos)
  978. {
  979. //$"{studentInfo.periodId}_{year}_{tmpClassNo.GetString()}"
  980. var key = $"{classInfo.Value.periodId}_{classInfo.Value.year}_{classInfo.Value.no}";
  981. exsitkey.Add(key);
  982. }
  983. List<KeyValuePair<string, (string className, string periodId, int year, string no)>> nonexistentClassNo = new List<KeyValuePair<string, (string className, string periodId, int year, string no)>>();
  984. foreach (var key in sortedImpData.classInfo.Keys)
  985. {
  986. if (!exsitkey.Contains(key))
  987. {
  988. nonexistentClassNo.Add(new KeyValuePair<string, (string className, string periodId, int year, string no)>(key, sortedImpData.classInfo[key]));
  989. }
  990. }
  991. // var nonexistentClassNo = exsitkey.Except(sortedImpData.classInfo.Select(o => o.Key).ToList());
  992. if (nonexistentClassNo.Count() != 0)
  993. {
  994. var gradesInfo = await getGrades(_azureCosmos, _dingDing, _option, schoolId);
  995. foreach (var item in nonexistentClassNo)
  996. {
  997. string gradeId = string.Empty;
  998. string periodId = periodId = sortedImpData.classInfo[item.Key].periodId;
  999. int year = sortedImpData.classInfo[item.Key].year;
  1000. //確認該學段存在及輸入的年級index正確(-1後大於等於0)
  1001. //if (gradesInfo.ContainsKey(sortedImpData.classInfo[item].periodId) && sortedImpData.classInfo[item].gradeIndex - 1>=0)
  1002. // {
  1003. // periodId = sortedImpData.classInfo[item].periodId;
  1004. //gradeId = gradesInfo[sortedImpData.classInfo[item].periodId][sortedImpData.classInfo[item].gradeIndex - 1].gradeId;
  1005. //}
  1006. //建立新教室
  1007. (string classId, string classNo, string className, string periodId, string gradeId, int classYear) retCreateClassInfo =
  1008. await createClassInfo(_azureCosmos, _dingDing, _option,
  1009. schoolId,
  1010. null,
  1011. sortedImpData.classInfo[item.Key].className,
  1012. sortedImpData.classInfo[item.Key].no,
  1013. periodId,
  1014. gradeId,
  1015. year);
  1016. classStudNos.Add(retCreateClassInfo.classNo + "_" + retCreateClassInfo.classYear, new List<(string id, string no)>());
  1017. classNoId.Add(retCreateClassInfo.classNo + "_" + retCreateClassInfo.classYear, (retCreateClassInfo.classId, retCreateClassInfo.className, periodId, gradeId, year));
  1018. }
  1019. }
  1020. var taskWhenAll = Task.WhenAll(tasks);
  1021. taskWhenAll.Wait();
  1022. //-------------------------------------------------------------------------
  1023. //建立學生或是更新學生,並且要確認座號是否重複
  1024. //每間教室的全部座號 欲更新的教室座號
  1025. //先新建帳號若出現409則進行資料更新
  1026. //紀錄有重複做號的id
  1027. Dictionary<string, List<string>> duplNos = new Dictionary<string, List<string>>();
  1028. List<string> errorIds = new List<string>();
  1029. List<object> retStuds = new List<object>();
  1030. CosmosContainer cosmosContainer = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student");
  1031. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  1032. //並行處理
  1033. foreach (var stud in sortedImpData.studs)
  1034. {
  1035. //這邊一樣要確認已存在和欲加入還有欲修改的座號。
  1036. //欲修改的不會有重複
  1037. string classId = null;
  1038. bool isContinue = false;
  1039. if (!string.IsNullOrWhiteSpace(stud.Value.no) && !string.IsNullOrWhiteSpace(stud.Value.classNo))
  1040. {
  1041. classId = classNoId[stud.Value.classNo + "_" + stud.Value.classYear].classId;
  1042. (string id, string no) existNoInfo = (null, null);
  1043. //檢查要更新的座號是否已存在於雲端座號(已被其他同學使用)
  1044. classStudNos[stud.Value.classNo + "_" + stud.Value.classYear].ForEach(
  1045. o =>
  1046. {
  1047. if (o.no.Equals(stud.Value.no) && !o.id.Equals(stud.Key))
  1048. {
  1049. existNoInfo = (o.id, o.no);
  1050. if (duplNos.ContainsKey(stud.Value.classNo)) duplNos[stud.Value.classNo].Add(stud.Key);
  1051. else duplNos.Add(stud.Value.classNo, new List<string>() { stud.Key });
  1052. }
  1053. });
  1054. //如果不是空的代表有座號重覆到,此時要再確認這個重複座號的id,是否存在於這次的更新,而且是要更新座號的。
  1055. if (!string.IsNullOrWhiteSpace(existNoInfo.id))
  1056. {
  1057. isContinue = true;
  1058. //輪巡所有匯入的學生資料,並檢查匯入的座號。
  1059. sortedImpData.classStudNo[stud.Value.classNo].ForEach(
  1060. o =>
  1061. {
  1062. if (o.id.Equals(existNoInfo.id) && !o.no.Equals(existNoInfo.no))
  1063. {
  1064. //可以更新該座號
  1065. isContinue = false;
  1066. duplNos[stud.Value.classNo].Remove(stud.Key);
  1067. return;
  1068. }
  1069. });
  1070. }
  1071. }
  1072. if (isContinue) continue;
  1073. (string id, string name, string picture, int year, string no, string classId, string classNo, string className, string gradeId, string periodId) tmpStudInfo
  1074. = (stud.Key, stud.Value.name, null, stud.Value.year, stud.Value.no, null, stud.Value.classNo, null, null, null);
  1075. using var memoryStream = new MemoryStream();
  1076. using var writerNew = new Utf8JsonWriter(memoryStream);
  1077. writerNew.WriteStartObject();
  1078. writerNew.WriteString("id", stud.Key);
  1079. writerNew.WriteString("pk", $"Base");
  1080. writerNew.WriteString("code", $"Base-{schoolId}");
  1081. writerNew.WriteString("schoolId", schoolId);
  1082. writerNew.WriteNumber("year", stud.Value.year);
  1083. writerNew.WriteNumber("createTime", now);
  1084. writerNew.WriteString("salt", stud.Value.salt);
  1085. writerNew.WriteString("pw", stud.Value.pw);
  1086. if (string.IsNullOrWhiteSpace(stud.Value.name)) writerNew.WriteNull("name");
  1087. else writerNew.WriteString("name", stud.Value.name);
  1088. if (string.IsNullOrWhiteSpace(stud.Value.gender)) writerNew.WriteNull("gender");
  1089. else writerNew.WriteString("gender", stud.Value.gender);
  1090. writerNew.WriteNull("picture");
  1091. writerNew.WriteNull("mail");
  1092. writerNew.WriteNull("mobile");
  1093. writerNew.WriteNull("country");
  1094. if (!string.IsNullOrWhiteSpace(stud.Value.periodId))
  1095. {
  1096. writerNew.WriteString("periodId", stud.Value.periodId);
  1097. }
  1098. if (string.IsNullOrWhiteSpace(stud.Value.classNo)) writerNew.WriteNull("classId");
  1099. else
  1100. {
  1101. writerNew.WriteString("classId", classId);
  1102. tmpStudInfo.classId = classId;
  1103. tmpStudInfo.className = classNoId[stud.Value.classNo + "_" + stud.Value.classYear].className;
  1104. tmpStudInfo.gradeId = classNoId[stud.Value.classNo + "_" + stud.Value.classYear].gradeId;
  1105. tmpStudInfo.periodId = classNoId[stud.Value.classNo + "_" + stud.Value.classYear].periodId;
  1106. }
  1107. if (string.IsNullOrWhiteSpace(stud.Value.no))
  1108. {
  1109. writerNew.WriteNull("no");
  1110. writerNew.WriteNull("irs");
  1111. }
  1112. else
  1113. {
  1114. writerNew.WriteString("irs", stud.Value.no);
  1115. writerNew.WriteString("no", stud.Value.no);
  1116. };
  1117. writerNew.WriteNull("groupId");
  1118. writerNew.WriteNull("groupName");
  1119. ///写入监护人
  1120. if (!string.IsNullOrWhiteSpace(stud.Value.gPhone))
  1121. {
  1122. writerNew.WriteStartArray("guardians");
  1123. writerNew.WriteStartObject();
  1124. writerNew.WriteString("relation", stud.Value.guardian);
  1125. writerNew.WriteString("name", stud.Value.gName);
  1126. writerNew.WriteString("mobile", stud.Value.gPhone);
  1127. writerNew.WriteEndObject();
  1128. writerNew.WriteEndArray();
  1129. }
  1130. writerNew.WriteEndObject();
  1131. writerNew.Flush();
  1132. if (!string.IsNullOrWhiteSpace(stud.Value.imei))
  1133. {
  1134. await upsertImei(stud.Key, stud.Value.imei, schoolId, "keep", cosmosContainer);
  1135. }
  1136. var response = await cosmosContainer.CreateItemStreamAsync(memoryStream, new PartitionKey($"Base-{schoolId}"));
  1137. if (response.Status == (int)HttpStatusCode.Created)
  1138. {
  1139. //如果是Created則啥都不做,讓他去下面進行資料的彙整。
  1140. }
  1141. //查到已存在的id,則進行基本資料更新。
  1142. else if (response.Status == (int)HttpStatusCode.Conflict)
  1143. {
  1144. try
  1145. {
  1146. bool isUpPwDone = false;
  1147. Student student = await _azureCosmos
  1148. .GetCosmosClient()
  1149. .GetContainer(Constant.TEAMModelOS, "Student")
  1150. .ReadItemAsync<Student>(stud.Key, new PartitionKey($"Base-{schoolId}"));
  1151. if (!string.IsNullOrWhiteSpace(stud.Value.name))
  1152. {
  1153. student.name = stud.Value.name;
  1154. }
  1155. if (stud.Value.year > 0)
  1156. {
  1157. student.year = stud.Value.year;
  1158. }
  1159. if (!string.IsNullOrWhiteSpace(stud.Value.no))
  1160. {
  1161. student.no = stud.Value.no;
  1162. student.irs = stud.Value.no;
  1163. }
  1164. if (!string.IsNullOrWhiteSpace(stud.Value.gender))
  1165. {
  1166. student.gender = stud.Value.gender;
  1167. }
  1168. if (!string.IsNullOrWhiteSpace(stud.Value.classNo))
  1169. {
  1170. student.classId = classId;
  1171. }
  1172. if (!string.IsNullOrWhiteSpace(stud.Value.periodId))
  1173. {
  1174. student.periodId = stud.Value.periodId;
  1175. }
  1176. if (!string.IsNullOrWhiteSpace(student.classId))
  1177. {
  1178. var clazz = classes.FindAll(x => x.id.Equals(student.classId));
  1179. if (clazz.IsNotEmpty())
  1180. {
  1181. student.graduate = clazz[0].graduate;
  1182. }
  1183. }
  1184. if (!isUpPwDone)
  1185. {
  1186. student.pw = stud.Value.pw;
  1187. student.salt = stud.Value.salt;
  1188. isUpPwDone = true;
  1189. }
  1190. tmpStudInfo.picture = student.picture;
  1191. if (!string.IsNullOrWhiteSpace(stud.Value.gPhone))
  1192. {
  1193. List<Guardian> guardians = new List<Guardian>();
  1194. string sql = $"select distinct value (c) from c where c.mobile='{stud.Value.gPhone}' ";
  1195. await foreach (var item in cosmosContainer.GetItemQueryIterator<Guardian>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base-Guardian") }))
  1196. {
  1197. guardians.Add(item);
  1198. }
  1199. if (guardians.Any())
  1200. {
  1201. guardians.ForEach(async x =>
  1202. {
  1203. GuardianStudent guardianStudent = x.students.Find(s => s.id.Equals(stud.Key) && s.code.Equals(schoolId));
  1204. if (guardianStudent == null)
  1205. {
  1206. x.students.Add(new GuardianStudent { relation = stud.Value.guardian, type = 2, id = stud.Key, code = schoolId, name = stud.Value.name });
  1207. }
  1208. await cosmosContainer.ReplaceItemAsync(x, x.id, new PartitionKey(x.code));
  1209. });
  1210. }
  1211. else
  1212. {
  1213. Guardian guardian = new Guardian
  1214. {
  1215. id = Guid.NewGuid().ToString(),
  1216. code = "Base-Guardian",
  1217. pk = "Guardian",
  1218. mobile = stud.Value.gPhone,
  1219. name = stud.Value.gName,
  1220. students = new List<GuardianStudent> { new GuardianStudent { relation = stud.Value.guardian, type = 2, id = stud.Key, code = schoolId, name = stud.Value.name } }
  1221. };
  1222. await cosmosContainer.CreateItemAsync(guardian, new PartitionKey(guardian.code));
  1223. }
  1224. var studentGuardian = student.guardians.Find(x => !string.IsNullOrWhiteSpace(x.mobile) && x.mobile.Equals(stud.Value.gPhone));
  1225. if (studentGuardian != null)
  1226. {
  1227. studentGuardian.name = stud.Value.gName;
  1228. studentGuardian.relation = stud.Value.guardian;
  1229. }
  1230. else
  1231. {
  1232. student.guardians.Add(new StudentGuardian { mobile = stud.Value.gPhone, name = stud.Value.gName, relation = stud.Value.guardian });
  1233. }
  1234. }
  1235. if (stud.Value.guardians.IsNotEmpty())
  1236. {
  1237. student.guardians = stud.Value.guardians;
  1238. }
  1239. await cosmosContainer.ReplaceItemAsync(student, stud.Key, new PartitionKey($"Base-{schoolId}"));
  1240. }
  1241. catch (CosmosException ex)
  1242. {
  1243. errorIds.Add(stud.Key);
  1244. continue;
  1245. }
  1246. }
  1247. else
  1248. {
  1249. errorIds.Add(stud.Key);
  1250. continue;
  1251. }
  1252. //整理輸出用資料
  1253. retStuds.Add(
  1254. new
  1255. {
  1256. tmpStudInfo.id,
  1257. tmpStudInfo.name,
  1258. tmpStudInfo.picture,
  1259. tmpStudInfo.year,
  1260. tmpStudInfo.no,
  1261. tmpStudInfo.classId,
  1262. tmpStudInfo.classNo,
  1263. tmpStudInfo.className,
  1264. // tmpStudInfo.gradeId,
  1265. // tmpStudInfo.periodId
  1266. });
  1267. }
  1268. return (retStuds, duplNos.Where(o => o.Value.Count != 0).ToDictionary(o => o.Key, o => o.Value), errorIds);
  1269. }
  1270. catch (Exception ex)
  1271. {
  1272. await _dingDing.SendBotMsg(
  1273. $"IES5,{_option.Location},StudentController/upsertStudents()\nex:{ex.Message}\n{ex.StackTrace}",
  1274. GroupNames.醍摩豆服務運維群組);
  1275. }
  1276. return (null, null, null);
  1277. }
  1278. /// <summary>
  1279. /// grand_type
  1280. /// 为import:如果导入则已最新,没导入则不动这个字段的值,维持现状
  1281. /// 为create:如果有值,则绑定,并删除stuid关联的别的imei.
  1282. /// 为update
  1283. /// 为delete
  1284. /// </summary>
  1285. /// <param name="stuid"></param>
  1286. /// <param name="imei"></param>
  1287. /// <param name="schoolId"></param>
  1288. /// <param name="grand_type"></param>
  1289. /// <param name="cosmosContainer">
  1290. /// clean 当传入的电子学生证值为空,判断要强制清除关联的学生电子学生证 ,
  1291. /// keep 保持现状,导入时
  1292. /// delete 因学生被删除,强制删除电子学生证。</param>
  1293. /// <returns></returns>
  1294. public static async Task upsertImei(string stuid, string imeiid, string schoolId, string grand_type, CosmosContainer cosmosContainer)
  1295. {
  1296. List<Imei> imeis = new List<Imei>();
  1297. string sql = $"select value c from c where c.stuid='{stuid}' and c.school='{schoolId}' ";
  1298. await foreach (var item in cosmosContainer.GetItemQueryIterator<Imei>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Imei") }))
  1299. {
  1300. imeis.Add(item);
  1301. }
  1302. switch (grand_type)
  1303. {
  1304. case "clean":
  1305. case "keep":
  1306. bool notin = true;
  1307. List<Imei> update = new List<Imei>();
  1308. List<Imei> delete = new List<Imei>();
  1309. imeis.ForEach(x =>
  1310. {
  1311. //如果传入的电子学生证id不存在,且是单个更新或创建,则解除学生id的电子学生证绑定,并删除该电子学生证。
  1312. if (string.IsNullOrWhiteSpace(imeiid))
  1313. {
  1314. if (grand_type.Equals("clean"))
  1315. {
  1316. delete.Add(x);
  1317. }// 如果是导入模式,且电子学生证没有值则不动。
  1318. }
  1319. else
  1320. {
  1321. //如果电子学生证有值则,解除之前的所有与当前电子学生证id不符的绑定。
  1322. if (!x.id.Equals(imeiid))
  1323. {
  1324. x.stuid = null;
  1325. x.school = null;
  1326. delete.Add(x);
  1327. }
  1328. else
  1329. {
  1330. //存在且正确绑定
  1331. notin = false;
  1332. }
  1333. }
  1334. });
  1335. //当前学生还未有任何电子学生证,且有新的电子学生证id传入,则需要捞出电子学生证,绑定,如果没有捞出,则新建电子学生证,并绑定
  1336. if (notin && !string.IsNullOrWhiteSpace(imeiid))
  1337. {
  1338. var imeiResponse = await cosmosContainer.ReadItemStreamAsync(imeiid, new PartitionKey("Imei"));
  1339. if (imeiResponse.Status == 200)
  1340. {
  1341. Imei imeiDb = JsonDocument.Parse(imeiResponse.Content).RootElement.Deserialize<Imei>();
  1342. imeiDb.stuid = stuid;
  1343. imeiDb.school = schoolId;
  1344. await cosmosContainer.ReplaceItemAsync(imeiDb, imeiDb.id, new PartitionKey("Imei"));
  1345. }
  1346. else
  1347. {
  1348. Imei imei = new Imei { id = imeiid, code = "Imei", pk = "Imei", stuid = stuid, school = schoolId };
  1349. await cosmosContainer.CreateItemAsync(imei, new PartitionKey($"Imei"));
  1350. };
  1351. }
  1352. if (delete.Any())
  1353. {
  1354. await cosmosContainer.DeleteItemsStreamAsync(delete.Select(x => x.id).ToList(), "Imei");
  1355. }
  1356. break;
  1357. case "delete":
  1358. if (imeis.Any())
  1359. {
  1360. await cosmosContainer.DeleteItemsStreamAsync(imeis.Select(x => x.id).ToList(), "Imei");
  1361. }
  1362. break;
  1363. }
  1364. }
  1365. /// <summary>
  1366. /// 單純建立單一學生
  1367. /// </summary>
  1368. /// <param name="schoolId"></param>
  1369. /// <param name="studCreateInfo"></param>
  1370. public static async Task<bool> createStudent(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, studCreateInfo studCreateInfo)
  1371. {
  1372. try
  1373. {
  1374. using var stream = new MemoryStream();
  1375. using var writer = new Utf8JsonWriter(stream);
  1376. writer.WriteStartObject();
  1377. writer.WriteString("pk", $"Base");
  1378. writer.WriteString("code", $"Base-{schoolId}");
  1379. writer.WriteString("id", studCreateInfo.id);
  1380. if (string.IsNullOrWhiteSpace(studCreateInfo.name)) writer.WriteNull("name");
  1381. else writer.WriteString("name", studCreateInfo.name);
  1382. if (string.IsNullOrWhiteSpace(studCreateInfo.gender)) writer.WriteNull("gender");
  1383. else writer.WriteString("gender", studCreateInfo.gender);
  1384. writer.WriteString("schoolId", schoolId);
  1385. //20210713 huanghb add 增加学段
  1386. if (string.IsNullOrWhiteSpace(studCreateInfo.periodId)) writer.WriteNull("periodId");
  1387. else writer.WriteString("periodId", studCreateInfo.periodId);
  1388. writer.WriteNumber("year", studCreateInfo.year);
  1389. writer.WriteNumber("createTime", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
  1390. writer.WriteNull("picture");
  1391. writer.WriteNull("mail");
  1392. writer.WriteNull("mobile");
  1393. writer.WriteNull("country");
  1394. //Password,若沒給則使用學號當密碼
  1395. string salt = Utils.CreatSaltString(8);
  1396. string hashPw = string.IsNullOrWhiteSpace(studCreateInfo.pw)
  1397. ? Utils.HashedPassword(studCreateInfo.id, salt)
  1398. : Utils.HashedPassword(studCreateInfo.pw, salt);
  1399. writer.WriteString("salt", salt);
  1400. writer.WriteString("pw", hashPw);
  1401. if (string.IsNullOrWhiteSpace(studCreateInfo.classId)) writer.WriteNull("classId");
  1402. else writer.WriteString("classId", studCreateInfo.classId);
  1403. if (string.IsNullOrWhiteSpace(studCreateInfo.no))
  1404. {
  1405. writer.WriteNull("no");
  1406. writer.WriteNull("irs");
  1407. }
  1408. else
  1409. {
  1410. writer.WriteString("no", studCreateInfo.no);
  1411. writer.WriteString("irs", studCreateInfo.no);
  1412. }
  1413. writer.WriteNull("groupId");
  1414. writer.WriteNull("groupName");
  1415. if (studCreateInfo.guardians.IsNotEmpty())
  1416. {
  1417. writer.WriteStartArray("guardians");
  1418. foreach (var guardian in studCreateInfo.guardians)
  1419. {
  1420. writer.WriteStartObject();
  1421. writer.WriteString("relation", guardian.relation);
  1422. writer.WriteString("name", guardian.name);
  1423. writer.WriteString("mobile", guardian.mobile);
  1424. writer.WriteEndObject();
  1425. }
  1426. writer.WriteEndArray();
  1427. foreach (var studentGuardian in studCreateInfo.guardians)
  1428. {
  1429. List<Guardian> guardians = new List<Guardian>();
  1430. string sql = $"select distinct value (c) from c where c.mobile='{studentGuardian.mobile}' ";
  1431. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).GetItemQueryIterator<Guardian>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base-Guardian") }))
  1432. {
  1433. guardians.Add(item);
  1434. }
  1435. if (guardians.Any())
  1436. {
  1437. guardians.ForEach(async x =>
  1438. {
  1439. GuardianStudent guardianStudent = x.students.Find(s => s.id.Equals(studCreateInfo.id) && s.code.Equals(schoolId));
  1440. if (guardianStudent == null)
  1441. {
  1442. x.students.Add(new GuardianStudent { relation = studentGuardian.relation, type = 2, id = studCreateInfo.id, code = schoolId, name = studCreateInfo.name });
  1443. }
  1444. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).ReplaceItemAsync(x, x.id, new PartitionKey(x.code));
  1445. });
  1446. }
  1447. else
  1448. {
  1449. Guardian guardian = new Guardian
  1450. {
  1451. id = Guid.NewGuid().ToString(),
  1452. code = "Base-Guardian",
  1453. pk = "Guardian",
  1454. mobile = studentGuardian.mobile,
  1455. name = studentGuardian.name,
  1456. students = new List<GuardianStudent> { new GuardianStudent { relation = studentGuardian.relation, type = 2, id = studCreateInfo.id, code = schoolId, name = studCreateInfo.name } }
  1457. };
  1458. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).CreateItemAsync(guardian, new PartitionKey(guardian.code));
  1459. }
  1460. }
  1461. }
  1462. else
  1463. {
  1464. writer.WriteStartArray("guardians");
  1465. writer.WriteStartObject();
  1466. writer.WriteEndObject();
  1467. writer.WriteEndArray();
  1468. }
  1469. writer.WriteEndObject();
  1470. writer.Flush();
  1471. var response = await _azureCosmos
  1472. .GetCosmosClient()
  1473. .GetContainer(Constant.TEAMModelOS, "Student")
  1474. .CreateItemStreamAsync(stream, new PartitionKey($"Base-{schoolId}"));
  1475. //更新电子学生证、
  1476. await upsertImei(studCreateInfo.id, studCreateInfo.imei, schoolId, "keep", _azureCosmos
  1477. .GetCosmosClient()
  1478. .GetContainer(Constant.TEAMModelOS, "Student"));
  1479. if (response.Status == (int)HttpStatusCode.Created || response.Status == (int)HttpStatusCode.OK) return true;
  1480. if (response.Status == (int)HttpStatusCode.Conflict) return false;
  1481. else
  1482. {
  1483. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createStudent()\nCosmosDB Create response status = {response.Status}\nID:{studCreateInfo.id}", GroupNames.醍摩豆服務運維群組);
  1484. return false;
  1485. }
  1486. }
  1487. catch (Exception ex)
  1488. {
  1489. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createStudent()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1490. return false;
  1491. }
  1492. }
  1493. /// <summary>
  1494. /// 生成Class資料
  1495. /// </summary>
  1496. /// <param name="schoolId"></param>
  1497. /// <param name="classId"></param>
  1498. /// <param name="className"></param>
  1499. /// <param name="students"></param>
  1500. /// <returns></returns>
  1501. private static async Task<(string classId, string classNo, string className, string periodId, string gradeId, int classYear)> createClassInfo(
  1502. AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option,
  1503. string schoolId, string classId, string className, string classNo, string periodId, string gradeId, int classYear)
  1504. {
  1505. //組Class JSON
  1506. try
  1507. {
  1508. string cId = classId;
  1509. using var memoryStream = new MemoryStream();
  1510. using var writer = new Utf8JsonWriter(memoryStream);
  1511. writer.WriteStartObject();
  1512. writer.WriteString("pk", "Class");
  1513. writer.WriteString("code", $"Class-{schoolId}");
  1514. //如果classId是空的,則生成一組GUID。
  1515. if (string.IsNullOrWhiteSpace(classId))
  1516. {
  1517. cId = Guid.NewGuid().ToString();
  1518. writer.WriteString("id", cId);
  1519. }
  1520. else writer.WriteString("id", classId);
  1521. if (string.IsNullOrWhiteSpace(classNo)) writer.WriteNull("no");
  1522. else writer.WriteString("no", classNo);
  1523. writer.WriteNull("x");
  1524. writer.WriteNull("y");
  1525. if (string.IsNullOrWhiteSpace(className)) writer.WriteNull("name");
  1526. else writer.WriteString("name", className);
  1527. writer.WritePropertyName("teacher");
  1528. writer.WriteStartObject();
  1529. writer.WriteNull("id");
  1530. writer.WriteNull("name");
  1531. writer.WriteEndObject();
  1532. //if (string.IsNullOrWhiteSpace(gradeId)) writer.WriteNull("gradeId");
  1533. //else writer.WriteString("gradeId", gradeId);
  1534. if (string.IsNullOrWhiteSpace(periodId)) writer.WriteNull("periodId");
  1535. else writer.WriteString("periodId", periodId);
  1536. writer.WriteNumber("year", classYear);
  1537. writer.WriteNumber("createTime", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
  1538. writer.WriteNull("sn");
  1539. writer.WriteString("style", "smart");
  1540. writer.WriteString("openType", "1");
  1541. writer.WriteString("scope", "school");
  1542. writer.WriteEndObject();
  1543. writer.Flush();
  1544. var ret = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").CreateItemStreamAsync(memoryStream, new PartitionKey($"Class-{schoolId}"));
  1545. if (ret.Status != (int)HttpStatusCode.Created)
  1546. {
  1547. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createClassInfo()\nStatus:{ret.Status}\nSchoolId:{schoolId},ClassId:{classId}", GroupNames.醍摩豆服務運維群組);
  1548. }
  1549. return (cId, classNo, className, periodId, gradeId, classYear);
  1550. }
  1551. catch (CosmosException ex)
  1552. {
  1553. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createClassInfo()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1554. }
  1555. catch (Exception ex)
  1556. {
  1557. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createClassInfo()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1558. }
  1559. return (null, null, null, null, null, 0);
  1560. }
  1561. /// <summary>
  1562. /// 使用學校代碼查詢該校所有學生,並且在查詢該學生所屬的教室及座號,支援offset和limit操作已及ContinuationToken,若有ContinuationToken,則會優先使用ContinuationToken。
  1563. /// </summary>
  1564. /// <param name="schoolId"></param>
  1565. /// <param name="byNameOrId">透過Name或Id來查,所以不會管學制、學級和教室</param>
  1566. /// <param name="byPeriod"></param>
  1567. /// <param name="byGrade"></param>
  1568. /// <param name="byClassId"></param>
  1569. /// <param name="offset"></param>
  1570. /// <param name="limit"></param>
  1571. /// <param name="token"></param>
  1572. /// <returns></returns>
  1573. private async Task<(List<object> students, string continuationToken)> getStudents(
  1574. AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option,
  1575. string schoolId, string byNameOrId = null, string byPeriod = null, string byGrade = null, string byClassId = null, int offset = -1, int limit = -1, string token = default)
  1576. {
  1577. try
  1578. {
  1579. //以學校學生角度去抓資料
  1580. List<(string id, string name, string picture, int year)> listStudent = new List<(string id, string name, string picture, int year)>();
  1581. string queryText = $"SELECT c.id, c.name, c.picture, c.year FROM c WHERE c.code = 'Base-{schoolId}'";
  1582. //如果有選擇ClassId的話,則先取得該教室內的學生。
  1583. List<string> searchId = new List<string>();
  1584. if (!string.IsNullOrWhiteSpace(byClassId))
  1585. {
  1586. var classInfos = await getClassInfoUseId(_azureCosmos, _dingDing, _option, schoolId, new List<string>() { byClassId });
  1587. foreach (var classInfo in classInfos)
  1588. {
  1589. var students = classInfo.Value.GetProperty("students").EnumerateArray();
  1590. while (students.MoveNext())
  1591. {
  1592. JsonElement stud = students.Current;
  1593. string id = stud.GetProperty("id").GetString();
  1594. searchId.Add(id);
  1595. }
  1596. }
  1597. //將使用者過濾classId所取得的學生ID加入sql字串內
  1598. if (searchId.Count != 0)
  1599. {
  1600. queryText = $"{queryText} AND c.id IN ({string.Join(",", searchId.Select(o => $"'{o}'"))})";
  1601. }
  1602. }
  1603. //檢查是否有接續token及是否要在sql語法內多增加offset及limit
  1604. if (string.IsNullOrWhiteSpace(token))
  1605. {
  1606. token = default;
  1607. if (offset != -1 && limit != -1) queryText = $"{queryText} OFFSET {offset} LIMIT {limit}";
  1608. }
  1609. //回傳用ContinuationToken
  1610. string continuationToken = string.Empty;
  1611. //進行學生資料的查詢
  1612. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student")
  1613. .GetItemQueryStreamIterator(
  1614. queryText: queryText,
  1615. continuationToken: token,
  1616. requestOptions: new QueryRequestOptions()
  1617. { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  1618. {
  1619. continuationToken = item.GetContinuationToken();
  1620. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1621. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1622. {
  1623. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1624. while (accounts.MoveNext())
  1625. {
  1626. JsonElement account = accounts.Current;
  1627. listStudent.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString(), account.GetProperty("picture").GetString(), account.GetProperty("year").GetInt32()));
  1628. }
  1629. }
  1630. //單筆查詢上限為100條,所以查完一次即返回,並且給接續token。
  1631. break;
  1632. }
  1633. //查學生所屬的教室及座號
  1634. List<object> ret = new List<object>();
  1635. //查教室資訊,使用上面的學生id並透過子查詢查詢。
  1636. queryText = $"SELECT c.id, c.name, c.gradeId, c.students FROM c JOIN (SELECT VALUE t FROM t IN c.students WHERE t.id IN ({string.Join(",", listStudent.Select(o => $"'{o.id}'"))}))";
  1637. await foreach (Response item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
  1638. .GetItemQueryStreamIterator(
  1639. queryText: queryText,
  1640. //continuationToken: token,
  1641. requestOptions: new QueryRequestOptions()
  1642. { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  1643. {
  1644. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1645. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1646. {
  1647. var classrooms = json.RootElement.GetProperty("Documents").EnumerateArray();
  1648. while (classrooms.MoveNext())
  1649. {
  1650. JsonElement classroom = classrooms.Current;
  1651. var studs = classroom.GetProperty("students").EnumerateArray();
  1652. while (studs.MoveNext())
  1653. {
  1654. JsonElement stud = studs.Current;
  1655. string id = stud.GetProperty("id").GetString();
  1656. //整理出前端所需的資訊
  1657. var tmp = listStudent
  1658. .Where(o => o.id.Equals(id, StringComparison.Ordinal))
  1659. .Select(o =>
  1660. new
  1661. {
  1662. o.id,
  1663. o.name,
  1664. o.picture,
  1665. o.year,
  1666. no = stud.GetProperty("no").GetString(),
  1667. gradeId = classroom.GetProperty("gradeId").GetString(),
  1668. className = classroom.GetProperty("name").GetString()
  1669. });
  1670. ret.AddRange(tmp);
  1671. //刪除已整理完的ID
  1672. listStudent.RemoveAll(o => o.id.Equals(id, StringComparison.Ordinal));
  1673. }
  1674. }
  1675. }
  1676. }
  1677. var notJoinClassStuds = listStudent.Select(o =>
  1678. new
  1679. {
  1680. o.id,
  1681. o.name,
  1682. o.picture,
  1683. o.year,
  1684. no = (string)null,
  1685. gradeId = (string)null,
  1686. className = (string)null
  1687. });
  1688. ret.AddRange(notJoinClassStuds);
  1689. return (ret, continuationToken);
  1690. }
  1691. catch (CosmosException ex)
  1692. {
  1693. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1694. }
  1695. catch (Exception ex)
  1696. {
  1697. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1698. }
  1699. return (null, null);
  1700. }
  1701. /// <summary>
  1702. /// 取得該學校的所有學生。
  1703. /// </summary>
  1704. /// <param name="schoolId"></param>
  1705. /// <returns> [{id,name,picture,year,no,classId,classNo,className,gradeId,periodId},{id,name,picture,..}..]</returns>
  1706. public static async Task<List<object>> getAllStudent(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, int inyear, int graduate = 0)
  1707. {
  1708. try
  1709. {
  1710. //TODO : 進階查詢選項調整、部分地方可用並行處理
  1711. //以學校學生角度去抓資料
  1712. Dictionary<string, List<(string id, string name, string picture, int year, string no, string periodId, string irs, string imei, string gender, int graduate, bool hasEduOpenId, List<StudentGuardian> guardians)>> dicClassStuds =
  1713. new Dictionary<string, List<(string id, string name, string picture, int year, string no, string periodId, string irs, string imei, string gender, int graduate, bool hasEduOpenId, List<StudentGuardian> guardians)>>();
  1714. List<(string id, string name, string picture, int year, string no, string periodId, string irs, string imei, string gender, int graduate, bool hasEduOpenId, List<StudentGuardian> guardians)> notJoinClassStuds =
  1715. new List<(string id, string name, string picture, int year, string no, string periodId, string irs, string imei, string gender, int graduate, bool hasEduOpenId, List<StudentGuardian> guardians)>();
  1716. List<Imei> imeis = new List<Imei>();
  1717. string imeiQueryText = $"SELECT * FROM c WHERE c.school = '{schoolId}'";
  1718. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student")
  1719. .GetItemQueryIterator<Imei>(queryText: imeiQueryText, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Imei") }))
  1720. {
  1721. imeis.Add(item);
  1722. }
  1723. List<Student> graduate_students = new List<Student>();
  1724. List<Class> school_classes = new List<Class>();
  1725. string queryText = "";
  1726. if (graduate == 0)
  1727. {
  1728. queryText = $"SELECT * FROM c WHERE c.code = 'Base-{schoolId}' and (c.graduate = 0 or IS_DEFINED(c.graduate) = false )";
  1729. }
  1730. else
  1731. {
  1732. queryText = $"SELECT * FROM c WHERE c.code = 'Base-{schoolId}' and c.graduate = 1 and c.year ={inyear} ";
  1733. ///查询当年的毕业班
  1734. string sql = sql = $"SELECT value c FROM c where c.graduate =1 and c.year ={inyear}"; ;
  1735. var client = _azureCosmos.GetCosmosClient();
  1736. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Class>
  1737. (queryText: sql,
  1738. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  1739. {
  1740. school_classes.Add(item);
  1741. }
  1742. //如果已经毕业的班级不为空。
  1743. if (school_classes.IsNotEmpty())
  1744. {
  1745. string classSql = $"SELECT value c FROM c WHERE c.code = 'Base-{schoolId}' and c.graduate = 1 and c.classId in( {string.Join(",", school_classes.Select(x => $"'{x.id}'"))} )";
  1746. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: classSql,
  1747. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  1748. {
  1749. graduate_students.Add(item);
  1750. }
  1751. }
  1752. }
  1753. //回傳用ContinuationToken
  1754. string continuationToken = string.Empty;
  1755. var container = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student");
  1756. //進行學生資料的查詢 TEAMModelOS-Student
  1757. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student")
  1758. .GetItemQueryStreamIterator(
  1759. queryText: queryText,
  1760. requestOptions: new QueryRequestOptions()
  1761. { PartitionKey = new PartitionKey($"Base-{schoolId}"), MaxItemCount = -1 }))
  1762. {
  1763. continuationToken = item.GetContinuationToken();
  1764. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1765. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1766. {
  1767. List<(string id, string name, string picture, int year, string no, List<StudentGuardian> guardians)> students = new List<(string id, string name, string picture, int year, string no, List<StudentGuardian> guardians)>();
  1768. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1769. while (accounts.MoveNext())
  1770. {
  1771. JsonElement acc = accounts.Current;
  1772. string classId = acc.GetProperty("classId").GetString();
  1773. acc.TryGetProperty("irs", out JsonElement irs);
  1774. acc.TryGetProperty("guardians", out JsonElement _guardians);
  1775. List<StudentGuardian> guardians = new List<StudentGuardian>();
  1776. if (_guardians.ValueKind.Equals(JsonValueKind.Array))
  1777. {
  1778. guardians = _guardians.Deserialize<List<StudentGuardian>>();
  1779. if (guardians.Any())
  1780. {
  1781. guardians = guardians.FindAll(x => !string.IsNullOrWhiteSpace(x.mobile));
  1782. }
  1783. }
  1784. var imeiObj = imeis.Find(x => x.stuid.Equals(acc.GetProperty("id").GetString()));
  1785. if (string.IsNullOrWhiteSpace(classId))
  1786. {
  1787. notJoinClassStuds.Add(
  1788. (
  1789. acc.GetProperty("id").GetString(),
  1790. acc.GetProperty("name").GetString(),
  1791. acc.GetProperty("picture").GetString(),
  1792. acc.GetProperty("year").GetInt32(),
  1793. acc.GetProperty("no").GetString(),
  1794. acc.TryGetProperty("periodId", out JsonElement _periodId) && _periodId.ValueKind.Equals(JsonValueKind.String) ? _periodId.GetString() : null,
  1795. $"{irs}",
  1796. imeiObj?.id,//imei
  1797. acc.TryGetProperty("gender", out JsonElement _gender) && _gender.ValueKind.Equals(JsonValueKind.String) ? _gender.GetString() : null,
  1798. acc.TryGetProperty("graduate", out JsonElement _graduate) && _graduate.ValueKind.Equals(JsonValueKind.Number) ? int.Parse($"{_graduate}") : 0,
  1799. acc.TryGetProperty("openId", out JsonElement _openId) && !string.IsNullOrWhiteSpace(_openId.GetString()) ? true : false,
  1800. guardians
  1801. )
  1802. );
  1803. }
  1804. else
  1805. {
  1806. if (dicClassStuds.ContainsKey(classId))
  1807. {
  1808. dicClassStuds[classId].Add(
  1809. (
  1810. acc.GetProperty("id").GetString(),
  1811. acc.GetProperty("name").GetString(),
  1812. acc.GetProperty("picture").GetString(),
  1813. acc.GetProperty("year").GetInt32(),
  1814. acc.GetProperty("no").GetString(), acc.TryGetProperty("periodId", out JsonElement _periodId) && _periodId.ValueKind.Equals(JsonValueKind.String) ? _periodId.GetString() : null,
  1815. $"{irs}",
  1816. imeiObj?.id,//imei
  1817. acc.TryGetProperty("gender", out JsonElement _gender) && _gender.ValueKind.Equals(JsonValueKind.String) ? _gender.GetString() : null,
  1818. acc.TryGetProperty("graduate", out JsonElement _graduate) && _graduate.ValueKind.Equals(JsonValueKind.Number) ? int.Parse($"{_graduate}") : 0,
  1819. acc.TryGetProperty("openId", out JsonElement _openId) && !string.IsNullOrWhiteSpace(_openId.GetString()) ? true : false,
  1820. guardians
  1821. )
  1822. );
  1823. }
  1824. else
  1825. {
  1826. dicClassStuds.Add(classId,
  1827. new List<(string id, string name, string picture, int year, string no, string periodId, string irs, string imei, string gender, int graduate, bool hasEduOpenId, List<StudentGuardian> guardians)>()
  1828. {
  1829. (
  1830. acc.GetProperty("id").GetString(),
  1831. acc.GetProperty("name").GetString(),
  1832. acc.GetProperty("picture").GetString(),
  1833. acc.GetProperty("year").GetInt32(),
  1834. acc.GetProperty("no").GetString(), acc.TryGetProperty("periodId",out JsonElement _periodId)&& _periodId.ValueKind.Equals(JsonValueKind.String) ? _periodId.GetString() : null,
  1835. $"{irs}" ,
  1836. imeiObj?.id,//imei
  1837. acc.TryGetProperty("gender", out JsonElement _gender) && _gender.ValueKind.Equals(JsonValueKind.String) ? _gender.GetString() : null,
  1838. acc.TryGetProperty("graduate", out JsonElement _graduate) && _graduate.ValueKind.Equals(JsonValueKind.Number) ? int.Parse($"{_graduate}"): 0,
  1839. acc.TryGetProperty("openId", out JsonElement _openId) && !string.IsNullOrWhiteSpace(_openId.GetString()) ? true : false,
  1840. guardians
  1841. )
  1842. }
  1843. );
  1844. }
  1845. }
  1846. }
  1847. }
  1848. }
  1849. //查學生所屬的教室及座號
  1850. List<object> ret = new List<object>();
  1851. //查教室的資訊,用以取得gradeId,periodId資訊。
  1852. var classInfos = await getClassInfoUseId(_azureCosmos, _dingDing, _option, schoolId, dicClassStuds.Keys.ToList());
  1853. //輪循所有教室學生的資料
  1854. foreach (var classStud in dicClassStuds)
  1855. {
  1856. string classId = null, classNo = null, className = null, gradeId = null, periodId = null;
  1857. int classYear = -1;
  1858. if (classInfos.ContainsKey(classStud.Key))
  1859. {
  1860. classId = classInfos[classStud.Key].GetProperty("id").GetString();
  1861. classNo = classInfos[classStud.Key].GetProperty("no").GetString();
  1862. className = classInfos[classStud.Key].GetProperty("name").GetString();
  1863. periodId = classInfos[classStud.Key].TryGetProperty("periodId", out JsonElement _periodId) && _periodId.ValueKind.Equals(JsonValueKind.String) ? _periodId.GetString() : null;
  1864. if (classInfos[classStud.Key].TryGetProperty("year", out JsonElement year))
  1865. {
  1866. if (year.ValueKind.Equals(JsonValueKind.Number))
  1867. {
  1868. classYear = classInfos[classStud.Key].GetProperty("year").GetInt32();
  1869. }
  1870. }
  1871. }
  1872. var tmp = classStud.Value.Select(o =>
  1873. new
  1874. {
  1875. o.id,
  1876. o.name,
  1877. o.picture,
  1878. o.year,
  1879. o.no,
  1880. classId,
  1881. classNo,
  1882. className,
  1883. gradeId,
  1884. periodId = string.IsNullOrEmpty(periodId) ? o.periodId : periodId,
  1885. classYear,
  1886. irs = o.irs,
  1887. imei = o.imei,
  1888. gender = o.gender,
  1889. graduate = o.graduate,
  1890. hasEduOpenId = o.hasEduOpenId,
  1891. guardians = o.guardians,
  1892. });
  1893. ret.AddRange(tmp);
  1894. }
  1895. //彙整沒有加入教室的學生
  1896. notJoinClassStuds.ForEach(o => ret.Add(
  1897. new
  1898. {
  1899. o.id,
  1900. o.name,
  1901. o.picture,
  1902. o.year,
  1903. o.no,
  1904. classId = (string)null,
  1905. classNo = (string)null,
  1906. className = (string)null,
  1907. gradeId = (string)null,
  1908. o.periodId,
  1909. classYear = -1,
  1910. irs = o.irs,
  1911. imei = o.imei,
  1912. gender = o.gender,
  1913. hasEduOpenId = o.hasEduOpenId,
  1914. guardians = o.guardians,
  1915. }));
  1916. graduate_students.ForEach(o =>
  1917. {
  1918. var imeiObj = imeis.Find(x => x.stuid.Equals(o.id));
  1919. Class stuClass = school_classes.Find(x => x.id.Equals(o.classId));
  1920. ret.Add(
  1921. new
  1922. {
  1923. o.id,
  1924. o.name,
  1925. o.picture,
  1926. o.year,
  1927. o.no,
  1928. classId = stuClass?.id,
  1929. classNo = stuClass?.no,
  1930. className = stuClass?.name,
  1931. gradeId = stuClass?.gradeId,
  1932. o.periodId,
  1933. classYear = stuClass?.year,
  1934. irs = o.irs,
  1935. imei = imeiObj?.id,
  1936. gender = o.gender,
  1937. hasEduOpenId = (!string.IsNullOrWhiteSpace(o.openId)) ? true : false,
  1938. guardians = o.guardians,
  1939. });
  1940. });
  1941. return ret;
  1942. }
  1943. catch (Exception ex)
  1944. {
  1945. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getStudents()\n{ex.Message}\n{ex.StackTrace},", GroupNames.醍摩豆服務運維群組);
  1946. }
  1947. return null;
  1948. }
  1949. /// <summary>
  1950. /// 取得該校所有教室內的名單
  1951. /// </summary>
  1952. /// <param name="schoolId"></param>
  1953. /// <returns></returns>
  1954. public async Task<Dictionary<string, JsonElement>> getClassStudent(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, string classId = null)
  1955. {
  1956. try
  1957. {
  1958. string queryText = $"SELECT VALUE FROM c WHERE c.";
  1959. //if (!string.IsNullOrWhiteSpace(classId)) queryText += $" AND c.id = '{classId}'";
  1960. Dictionary<string, JsonElement> listStudent = new Dictionary<string, JsonElement>();
  1961. await foreach (Response item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
  1962. .GetItemQueryStreamIterator(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  1963. {
  1964. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1965. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1966. {
  1967. JsonElement.ArrayEnumerator accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1968. while (accounts.MoveNext())
  1969. {
  1970. JsonElement account = accounts.Current;
  1971. string cId = account.GetProperty("id").GetString();
  1972. var students = account.GetProperty("students").Clone();
  1973. listStudent.Add(cId, students);
  1974. }
  1975. }
  1976. }
  1977. return listStudent;
  1978. }
  1979. catch (Exception ex)
  1980. {
  1981. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassStudentAsync()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1982. }
  1983. return null;
  1984. }
  1985. /// <summary>
  1986. /// 刪除學生,非透過批量刪除方法。
  1987. /// </summary>
  1988. /// <param name="schoolId"></param>
  1989. /// <param name="students"></param>
  1990. /// <returns></returns>
  1991. public static async Task<List<string>> deleteStudents(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, JsonElement.ArrayEnumerator students)
  1992. {
  1993. List<string> sucIds = new List<string>();
  1994. try
  1995. {
  1996. var exceptions = new List<Exception>();
  1997. List<GroupList> scGroupLists = new List<GroupList>();
  1998. List<GroupList> teGroupLists = new List<GroupList>();
  1999. var container = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student");
  2000. while (students.MoveNext())
  2001. {
  2002. string id = string.Empty;
  2003. try
  2004. {
  2005. JsonElement student = students.Current;
  2006. id = student.GetProperty("id").GetString();
  2007. var ret = await container.DeleteItemStreamAsync(id, new PartitionKey($"Base-{schoolId}"));
  2008. await upsertImei(id, null, schoolId, "delete", container);
  2009. if (ret.Status == (int)HttpStatusCode.NoContent) sucIds.Add(id);
  2010. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupList>(queryText: $"select value(c) from c join A0 in c.members where A0.id = '{id}' and A0.code='{schoolId}' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{schoolId}") }))
  2011. {
  2012. scGroupLists.Add(item);
  2013. }
  2014. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<GroupList>(queryText: $"select value(c) from c join A0 in c.members where A0.id = '{id}' and A0.code='{schoolId}' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList") }))
  2015. {
  2016. teGroupLists.Add(item);
  2017. }
  2018. if (scGroupLists.Count > 0)
  2019. {
  2020. foreach (GroupList stuList in scGroupLists)
  2021. {
  2022. for (int j = 0; j < stuList.members.Count; j++)
  2023. {
  2024. if (id.Equals(stuList.members[j].id) && stuList.members[j].code.Equals(schoolId))
  2025. {
  2026. stuList.members.RemoveAt(j);
  2027. stuList.scount -= 1;
  2028. break;
  2029. }
  2030. }
  2031. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(stuList, stuList.id, new PartitionKey(stuList.code));
  2032. }
  2033. }
  2034. if (teGroupLists.Count > 0)
  2035. {
  2036. foreach (GroupList stuList in teGroupLists)
  2037. {
  2038. for (int j = 0; j < stuList.members.Count; j++)
  2039. {
  2040. if (id.Equals(stuList.members[j].id) && stuList.members[j].code.Equals(schoolId))
  2041. {
  2042. stuList.members.RemoveAt(j);
  2043. stuList.scount -= 1;
  2044. break;
  2045. }
  2046. }
  2047. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(stuList, stuList.id, new PartitionKey(stuList.code));
  2048. }
  2049. }
  2050. }
  2051. catch (CosmosException ex)
  2052. {
  2053. exceptions.Add(ex);
  2054. }
  2055. catch (Exception ex)
  2056. {
  2057. exceptions.Add(ex);
  2058. }
  2059. }
  2060. if (exceptions.Count == 0) return sucIds;
  2061. else if (exceptions.Count > 1) throw new AggregateException(exceptions);
  2062. else if (exceptions.Count == 1) throw exceptions.Single();
  2063. }
  2064. catch (CosmosException ex)
  2065. {
  2066. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/deleteStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2067. }
  2068. catch (Exception ex)
  2069. {
  2070. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/deleteStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2071. }
  2072. return sucIds;
  2073. }
  2074. /// <summary>
  2075. /// 將學生基本資料內的classId、no、groupId及groupName清為null。
  2076. /// </summary>
  2077. /// <param name="schoolId"></param>
  2078. /// <param name="students">["id1","id2",...]</param>
  2079. /// <returns></returns>
  2080. public static async Task<(List<string> studs, List<string> nonexistentIds, List<string> errorIds)> removeStudentClassInfo(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, JsonElement.ArrayEnumerator students)
  2081. {
  2082. //紀錄輸入的學生
  2083. List<string> impStuds = new List<string>();
  2084. //紀錄更新成功的學生
  2085. List<string> sucStuds = new List<string>();
  2086. //記錄沒查到的學生
  2087. List<string> nonexistentIds = new List<string>();
  2088. //紀錄更新出錯的學生
  2089. List<string> errorIds = new List<string>();
  2090. //整理輸入的學生資訊
  2091. while (students.MoveNext())
  2092. {
  2093. JsonElement student = students.Current;
  2094. impStuds.Add(student.GetString());
  2095. }
  2096. if (impStuds.Count == 0) return (null, null, null);
  2097. string queryText = $"SELECT VALUE c FROM c WHERE c.id IN ({string.Join(",", impStuds.Select(o => $"'{o}'"))})";
  2098. await foreach (Response item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student")
  2099. .GetItemQueryStreamIterator(
  2100. queryText: queryText,
  2101. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  2102. {
  2103. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  2104. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2105. {
  2106. JsonElement.ArrayEnumerator docs = json.RootElement.GetProperty("Documents").EnumerateArray();
  2107. while (docs.MoveNext())
  2108. {
  2109. JsonElement doc = docs.Current;
  2110. doc.TryGetProperty("id", out var tmpId);
  2111. var id = tmpId.GetString();
  2112. using var stream = new MemoryStream();
  2113. using var writer = new Utf8JsonWriter(stream);
  2114. writer.WriteStartObject();
  2115. foreach (var element in doc.EnumerateObject())
  2116. {
  2117. //將教室相關欄位清空
  2118. switch (true)
  2119. {
  2120. case bool _ when element.Name.Equals("classId", StringComparison.Ordinal):
  2121. writer.WriteNull("classId");
  2122. break;
  2123. case bool _ when element.Name.Equals("no", StringComparison.Ordinal):
  2124. writer.WriteNull("no");
  2125. break;
  2126. case bool _ when element.Name.Equals("groupId", StringComparison.Ordinal):
  2127. writer.WriteNull("groupId");
  2128. break;
  2129. case bool _ when element.Name.Equals("groupName", StringComparison.Ordinal):
  2130. writer.WriteNull("groupName");
  2131. break;
  2132. case bool _ when element.Name.Equals("irs", StringComparison.Ordinal):
  2133. writer.WriteNull("irs");
  2134. break;
  2135. case bool _ when element.Name.StartsWith("_", StringComparison.Ordinal):
  2136. break;
  2137. default:
  2138. element.WriteTo(writer);
  2139. break;
  2140. }
  2141. }
  2142. writer.WriteEndObject();
  2143. writer.Flush();
  2144. var ret = await _azureCosmos
  2145. .GetCosmosClient()
  2146. .GetContainer(Constant.TEAMModelOS, "Student")
  2147. .ReplaceItemStreamAsync(stream, id, new PartitionKey($"Base-{schoolId}"));
  2148. if (ret.Status == (int)HttpStatusCode.OK)
  2149. {
  2150. sucStuds.Add(id);
  2151. }
  2152. else
  2153. {
  2154. impStuds.Remove(id);
  2155. errorIds.Add(id);
  2156. await _dingDing.SendBotMsg(
  2157. $"IES5,{_option.Location},StudentController/removeStudentClassInfo(),CosmosDB response:{ret.Status}\nBase-{schoolId},id:{id}",
  2158. GroupNames.醍摩豆服務運維群組);
  2159. }
  2160. }
  2161. }
  2162. }
  2163. //將impStuds內的資料移除sucStuds及errorIds,所得的結果就是不存在於資料庫的id。
  2164. sucStuds.ForEach(o => impStuds.Remove(o));
  2165. errorIds.ForEach(o => impStuds.Remove(o));
  2166. return (sucStuds, impStuds, errorIds);
  2167. }
  2168. /// <summary>
  2169. /// 取得教室資訊,使用classId進行查詢。
  2170. /// </summary>
  2171. /// <returns></returns>
  2172. private static async Task<Dictionary<string, JsonElement>> getClassInfoUseId(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, List<string> classIds)
  2173. {
  2174. try
  2175. {
  2176. if (!(classIds == null || classIds.Count == 0))
  2177. {
  2178. string queryText = $"SELECT * FROM c WHERE c.code = 'Class-{schoolId}' AND c.id IN ({string.Join(",", classIds.Select(o => $"'{o}'"))})";
  2179. Dictionary<string, JsonElement> dicClassInfo = new Dictionary<string, JsonElement>();
  2180. await foreach (Response item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
  2181. .GetItemQueryStreamIterator(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  2182. {
  2183. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  2184. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2185. {
  2186. var classInfos = json.RootElement.GetProperty("Documents").EnumerateArray();
  2187. while (classInfos.MoveNext())
  2188. {
  2189. JsonElement account = classInfos.Current;
  2190. string id = account.GetProperty("id").GetString();
  2191. dicClassInfo.Add(id, account.Clone());
  2192. }
  2193. }
  2194. }
  2195. return dicClassInfo;
  2196. }
  2197. else return null;
  2198. }
  2199. catch (CosmosException ex)
  2200. {
  2201. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassInfoUseId()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2202. }
  2203. catch (Exception ex)
  2204. {
  2205. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassInfoUseId()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2206. }
  2207. return null;
  2208. }
  2209. /// <summary>
  2210. /// 取得教室資訊,使用classNo進行查詢。
  2211. /// </summary>
  2212. /// <returns></returns>
  2213. private static async Task<Dictionary<string, Class>> getClassInfoUseNo(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, Dictionary<string, (string className, string periodId, int year, string no)> classNos)
  2214. {
  2215. try
  2216. {
  2217. Dictionary<string, Class> dicClassInfo = new Dictionary<string, Class>();
  2218. if (!(classNos == null || classNos.Count == 0))
  2219. {
  2220. foreach (var key in classNos.Keys)
  2221. {
  2222. string queryText = $"SELECT * FROM c WHERE c.code = 'Class-{schoolId}' AND c.no='{classNos[key].no}' and c.year={classNos[key].year} and c.periodId='{classNos[key].periodId}' ";
  2223. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
  2224. .GetItemQueryIterator<Class>(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  2225. {
  2226. dicClassInfo[item.id] = item;
  2227. item.name = classNos[key].className;
  2228. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<Class>(item, item.id, new PartitionKey(item.code));
  2229. }
  2230. }
  2231. return dicClassInfo;
  2232. }
  2233. else return null;
  2234. }
  2235. catch (CosmosException ex)
  2236. {
  2237. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassInfoUseId()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2238. }
  2239. catch (Exception ex)
  2240. {
  2241. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassInfoUseId()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2242. }
  2243. return null;
  2244. }
  2245. /// <summary>
  2246. /// 批量更新學生資訊,目前支持更新姓名、密碼、座號、性別及教室id,匯入時ClassId為必填。
  2247. /// </summary>
  2248. /// <param name="schoolId"></param>
  2249. /// <param name="students"></param>
  2250. /// <returns></returns>
  2251. public static async Task<(List<object> studs, Dictionary<string, List<string>> classDuplNos, List<string> nonexistentIds, List<string> errorIds,
  2252. Dictionary<string, List<string>> errorNos, List<string> errorClassId)>
  2253. updateStudents(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, JsonElement.ArrayEnumerator students)
  2254. {
  2255. try
  2256. {
  2257. //整理輸入的資料->檢查輸入資料有沒有重複座號->取得欲加入的教室資訊->查詢學生並將資料更新並寫入
  2258. //Key:id Value:學生基本資訊
  2259. var studentInfos
  2260. = new Dictionary<string, (string salt, string pw, string name, int year, string picture, string gender, string mail, string mobile,
  2261. string classId, string no, string periodId, string irs, string imei, List<StudentGuardian> guardians)>();
  2262. //用於進行座號是否重複查詢時使用
  2263. var classStuds
  2264. = new Dictionary<string, List<(string id, string salt, string pw, string name, int year, string picture, string gender, string mail, string mobile,
  2265. string classId, string no, string periodId)>>();
  2266. //紀錄教室"輸入"的學生座號是否有重複
  2267. var impClassDuplNo = new Dictionary<string, List<string>>();
  2268. //紀錄不存在的學生id
  2269. var nonexistentIds = new List<string>();
  2270. //紀錄跟現有雲端學生座號重複的
  2271. var errorNos = new Dictionary<string, List<string>>();
  2272. //紀錄處理錯誤的id,cosmosdb寫入時錯誤等...
  2273. var errorIds = new List<string>();
  2274. //紀錄沒找到的classId
  2275. var errorClassId = new List<string>();
  2276. //紀錄輸出結果
  2277. var retStuds = new List<object>();
  2278. //整理輸入資料
  2279. while (students.MoveNext())
  2280. {
  2281. JsonElement student = students.Current;
  2282. if (student.TryGetProperty("id", out var id))
  2283. {
  2284. //確認是否有id欄位,並且確認是否有給pw欄位,若無給或是null empty等,則使用id當密碼。
  2285. if (!string.IsNullOrWhiteSpace(id.GetString()))
  2286. {
  2287. string salt = null,
  2288. pw = null,
  2289. name = null,
  2290. gender = null,
  2291. mail = null,
  2292. mobile = null,
  2293. classId = null,
  2294. periodId = null,
  2295. irs = null,
  2296. imei = null,
  2297. no = null;
  2298. List<StudentGuardian> guardians = null;
  2299. int year = 0;
  2300. //有給pw欄位才進行處理
  2301. if (student.TryGetProperty("pw", out var tmpPw) && !"******".Equals($"{tmpPw}"))
  2302. {
  2303. var response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemStreamAsync(id.GetString(), new PartitionKey($"Base-{schoolId}"));
  2304. if (response.Status == 200)
  2305. {
  2306. var rjson = await JsonDocument.ParseAsync(response.ContentStream);
  2307. rjson.RootElement.TryGetProperty("salt", out JsonElement _salt);
  2308. salt = $"{_salt}";
  2309. }
  2310. if (string.IsNullOrWhiteSpace(salt))
  2311. {
  2312. salt = Utils.CreatSaltString(8);
  2313. }
  2314. pw = !string.IsNullOrWhiteSpace(tmpPw.GetString())
  2315. ? Utils.HashedPassword(tmpPw.GetString(), salt)
  2316. : Utils.HashedPassword(id.GetString(), salt);
  2317. }
  2318. if (student.TryGetProperty("name", out var tmpName)) name = tmpName.GetString();
  2319. if (student.TryGetProperty("gender", out var tmpGender)) gender = tmpGender.GetString();
  2320. if (student.TryGetProperty("mail", out var tmpMail)) mail = tmpMail.GetString();
  2321. if (student.TryGetProperty("mobile", out var tmpMobile)) mobile = tmpMobile.GetString();
  2322. if (student.TryGetProperty("year", out var tmpYear)) year = tmpYear.GetInt32();
  2323. if (student.TryGetProperty("periodId", out var tmpperiodId)) periodId = tmpperiodId.GetString();
  2324. if (student.TryGetProperty("irs", out var tmpIrs)) irs = tmpIrs.GetString();
  2325. if (student.TryGetProperty("imei", out var tmpImei)) imei = tmpImei.GetString();
  2326. if (student.TryGetProperty("classId", out var tmpclassId)) classId = tmpclassId.GetString();
  2327. else
  2328. {
  2329. errorClassId.Add(id.GetString());
  2330. continue;
  2331. }
  2332. if (student.TryGetProperty("guardians", out var _guardians) && _guardians.ValueKind.Equals(JsonValueKind.Array))
  2333. {
  2334. guardians = _guardians.Deserialize<List<StudentGuardian>>();
  2335. }
  2336. //如果有給該欄位,且是給空的,代表要清空
  2337. if (student.TryGetProperty("no", out var tmpNo)) no = tmpNo.GetString();
  2338. if (!studentInfos.ContainsKey(id.GetString()))
  2339. {
  2340. //如果有給classId且是給空的,則也將no設為空,後續才能將no欄位清空。
  2341. if (classId != null && classId.Length == 0) no = string.Empty;
  2342. //classId => 沒給欄位(null) 有給欄位("") 但更新一定得給教室?
  2343. if (classId == null)
  2344. {
  2345. classId = "";
  2346. }
  2347. if (classStuds.ContainsKey(classId))
  2348. {
  2349. classStuds[classId].Add((id.GetString(), salt, pw, name, year, null, gender, null, null, classId, no, periodId));
  2350. }
  2351. else
  2352. {
  2353. classStuds.Add(
  2354. classId,
  2355. new List<(string id, string salt, string pw, string name, int year, string picture, string gender, string mail, string mobile, string classId, string no, string periodId)>()
  2356. { (id.GetString(), salt, pw, name, year, null, gender, null, null, classId, no,periodId) });
  2357. }
  2358. //picture,mail,mobile暫不支持批量更新
  2359. studentInfos.Add(id.GetString(), (salt, pw, name, year, null, gender, null, null, classId, no, periodId, irs, imei, guardians));
  2360. //先將id加進去後面再做刪除動作
  2361. nonexistentIds.Add(id.GetString());
  2362. }
  2363. }
  2364. }
  2365. }
  2366. //檢查所有輸入的班級資料內,學生座號是否有重複。
  2367. for (int ii = 0; ii <= classStuds.Values.Count - 1; ii++)
  2368. {
  2369. var duplicateNo = classStuds.ElementAt(ii).Value.GroupBy(o => o.no).Where(o => o.Count() > 1).Select(o => o.Key).ToList();
  2370. duplicateNo.Remove("");
  2371. duplicateNo.Remove(null);
  2372. var wrongStuds = classStuds.ElementAt(ii).Value.Where(o => duplicateNo.Contains(o.no)).Select(o => o).ToList();
  2373. impClassDuplNo.Add(classStuds.ElementAt(ii).Key, wrongStuds.Select(o => o.id).ToList());
  2374. wrongStuds.ForEach(o => { classStuds.ElementAt(ii).Value.Remove(o); nonexistentIds.Remove(o.id); });
  2375. classStuds[classStuds.ElementAt(ii).Key] = classStuds.ElementAt(ii).Value;
  2376. }
  2377. //查詢欲加入的教室資訊。
  2378. var classInfo = await getClassInfoUseId(_azureCosmos, _dingDing, _option, schoolId, classStuds.Keys.ToList());
  2379. //準備查詢db資料
  2380. CosmosContainer cosmosContainer = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student");
  2381. //查要移除教室或是沒加入教室的學生
  2382. foreach (var item in classStuds)
  2383. {
  2384. //如果沒有任何學生要更新,則跳過該間教室。
  2385. if (item.Value.Count == 0) continue;
  2386. string classId = null, className = null, classNo = null, gradeId = null, periodId = null;
  2387. //如果教室不存在的話(填錯教室之類的狀況),則記錄教室的id及學生id。
  2388. if (classInfo.ContainsKey(item.Key))
  2389. {
  2390. classId = item.Key;
  2391. className = classInfo[item.Key].GetProperty("name").GetString();
  2392. classNo = classInfo[item.Key].GetProperty("no").GetString();
  2393. //gradeId = classInfo[item.Key].GetProperty("gradeId").GetString(); 此欄位已不使用
  2394. periodId = classInfo[item.Key].GetProperty("periodId").GetString();
  2395. }
  2396. else if (item.Key.Length == 0)
  2397. {
  2398. }
  2399. else
  2400. {
  2401. //沒查到有該間教室的資訊,故將該間教室的ID及學生資料清單記起來,並且跳過不處理該資料。
  2402. errorClassId.Add(item.Key);
  2403. item.Value.ForEach(o => nonexistentIds.Remove(o.id));
  2404. continue;
  2405. }
  2406. //檢查座號是否有重複
  2407. //若只是改基本資料,該處還是會查到相同的座號。
  2408. var sutdNos = item.Value.Select(o => o.no).ToList();
  2409. var existNos = await checkStudNo(_azureCosmos, _dingDing, _option, schoolId, item.Key, sutdNos);
  2410. //更新並寫入學生資料
  2411. if (item.Value.Count != 0)
  2412. {
  2413. //查學生的基本資料(該間教室全部的學生)
  2414. string queryText = $"SELECT * FROM c WHERE c.id IN ({string.Join(",", item.Value.Select(o => $"'{o.id}'"))})";
  2415. List<JsonElement> listStudent = new List<JsonElement>();
  2416. await foreach (Response responseItem in cosmosContainer
  2417. .GetItemQueryStreamIterator(
  2418. queryText: queryText,
  2419. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  2420. {
  2421. using var json = await JsonDocument.ParseAsync(responseItem.ContentStream);
  2422. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2423. {
  2424. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  2425. while (accounts.MoveNext())
  2426. {
  2427. JsonElement account = accounts.Current;
  2428. string id = $"{account.GetProperty("id")}";
  2429. nonexistentIds.Remove(id);
  2430. //舊的座號,基本上不會重複,但可能會是空的
  2431. string no = $"{account.GetProperty("no")}";
  2432. account.TryGetProperty("irs", out JsonElement irsjson);
  2433. string irs = $"{irsjson}";
  2434. //用來記錄最後更改完的資料
  2435. (string salt, string pw, string name, int year, string picture, string gender, string mail, string mobile, string classId, string no, string periodId, string irs, string imei, List<StudentGuardian> guardians) tmpData
  2436. = (studentInfos[id].salt, studentInfos[id].pw, studentInfos[id].name, studentInfos[id].year, studentInfos[id].picture, studentInfos[id].gender, studentInfos[id].mail, studentInfos[id].mobile, studentInfos[id].classId, studentInfos[id].no, studentInfos[id].periodId,
  2437. studentInfos[id].irs, studentInfos[id].imei, studentInfos[id].guardians);
  2438. bool isUpPwDone = false;
  2439. bool isWrong = false;
  2440. //開始組Json
  2441. using var memoryStream = new MemoryStream();
  2442. using var writer = new Utf8JsonWriter(memoryStream);
  2443. writer.WriteStartObject();
  2444. foreach (var element in account.EnumerateObject())
  2445. {
  2446. if (isWrong) break;
  2447. switch (true)
  2448. {
  2449. case bool _ when element.Name.Equals("name", StringComparison.Ordinal):
  2450. if (string.IsNullOrWhiteSpace(studentInfos[id].name))
  2451. {
  2452. element.WriteTo(writer);
  2453. tmpData.name = element.Value.GetString();
  2454. }
  2455. else
  2456. {
  2457. writer.WriteString("name", studentInfos[id].name);
  2458. }
  2459. break;
  2460. case bool _ when element.Name.Equals("pw", StringComparison.Ordinal):
  2461. case bool _ when element.Name.Equals("salt", StringComparison.Ordinal):
  2462. if (!isUpPwDone && !string.IsNullOrWhiteSpace(studentInfos[id].salt) && !string.IsNullOrWhiteSpace(studentInfos[id].pw))
  2463. {
  2464. writer.WriteString("salt", studentInfos[id].salt);
  2465. writer.WriteString("pw", studentInfos[id].pw);
  2466. isUpPwDone = true;
  2467. }
  2468. break;
  2469. case bool _ when element.Name.Equals("periodId", StringComparison.Ordinal):
  2470. if (string.IsNullOrWhiteSpace(studentInfos[id].periodId))
  2471. {
  2472. element.WriteTo(writer);
  2473. tmpData.periodId = element.Value.GetString();
  2474. }
  2475. else
  2476. {
  2477. writer.WriteString("periodId", studentInfos[id].periodId);
  2478. }
  2479. break;
  2480. case bool _ when element.Name.Equals("gender", StringComparison.Ordinal):
  2481. if (string.IsNullOrWhiteSpace(studentInfos[id].gender))
  2482. {
  2483. element.WriteTo(writer);
  2484. tmpData.gender = element.Value.GetString();
  2485. }
  2486. else
  2487. {
  2488. writer.WriteString("gender", studentInfos[id].gender);
  2489. }
  2490. break;
  2491. case bool _ when element.Name.Equals("year", StringComparison.Ordinal):
  2492. if (studentInfos[id].year == 0)
  2493. {
  2494. element.WriteTo(writer);
  2495. tmpData.year = element.Value.GetInt32();
  2496. }
  2497. else
  2498. {
  2499. writer.WriteNumber("year", studentInfos[id].year);
  2500. }
  2501. break;
  2502. case bool _ when element.Name.Equals("classId", StringComparison.Ordinal):
  2503. if (studentInfos[id].classId != null && studentInfos[id].classId.Length == 0)
  2504. {
  2505. writer.WriteNull("classId");
  2506. writer.WriteNull("groupId");
  2507. writer.WriteNull("groupName");
  2508. tmpData.classId = null;
  2509. }
  2510. else if (string.IsNullOrWhiteSpace(studentInfos[id].classId))
  2511. {
  2512. element.WriteTo(writer);
  2513. tmpData.classId = element.Value.GetString();
  2514. }
  2515. else
  2516. {
  2517. writer.WriteString("classId", studentInfos[id].classId);
  2518. }
  2519. break;
  2520. case bool _ when element.Name.Equals("no", StringComparison.Ordinal):
  2521. //移除座號的話會給空的
  2522. if (studentInfos[id].no != null && studentInfos[id].no.Length == 0)
  2523. {
  2524. writer.WriteNull("no");
  2525. tmpData.no = null;
  2526. }
  2527. else if (string.IsNullOrWhiteSpace(studentInfos[id].no))
  2528. {
  2529. element.WriteTo(writer);
  2530. tmpData.no = element.Value.GetString();
  2531. //#2769 C343 学生管理--导入学生名单,IRS编号默认与座号一致
  2532. tmpData.irs = element.Value.GetString();
  2533. }
  2534. else
  2535. {
  2536. //如果要更新的座號,跟已存在的座號相同,則不進行更新。
  2537. //沒有設定過舊no,或舊座號與新座號不同,則要進行重複座號的檢查。 舊no=null or 舊no!=新no
  2538. //if (string.IsNullOrWhiteSpace(no) || (!string.IsNullOrWhiteSpace(no) && !no.Equals(studentInfos[id].no)))
  2539. //{
  2540. // //如果有檢查到新座號和舊座號重複
  2541. // if (existNos.Any(o => o.Item2.Contains(studentInfos[id].no))) //.Contains(studentInfos[id].no))
  2542. // {
  2543. // if (errorNos.ContainsKey(id))
  2544. // {
  2545. // errorNos[id].Add(studentInfos[id].no);
  2546. // }
  2547. // else
  2548. // {
  2549. // errorNos.Add(id, new List<string>() { studentInfos[id].no });
  2550. // }
  2551. // isWrong = true;
  2552. // break;
  2553. // }
  2554. //}
  2555. writer.WriteString("no", studentInfos[id].no);
  2556. //#2769 C343 学生管理--导入学生名单,IRS编号默认与座号一致
  2557. writer.WriteString("irs", studentInfos[id].no);
  2558. }
  2559. break;
  2560. //case bool _ when element.Name.Equals("irs", StringComparison.Ordinal):
  2561. // //移除座號的話會給空的
  2562. // if (studentInfos[id].irs != null && studentInfos[id].irs.Length == 0)
  2563. // {
  2564. // writer.WriteNull("irs");
  2565. // tmpData.irs = null;
  2566. // }
  2567. // else if (string.IsNullOrWhiteSpace(studentInfos[id].irs))
  2568. // {
  2569. // element.WriteTo(writer);
  2570. // tmpData.irs = element.Value.GetString();
  2571. // }
  2572. // else
  2573. // {
  2574. // writer.WriteString("irs", studentInfos[id].irs);
  2575. // }
  2576. // break;
  2577. case bool _ when element.Name.StartsWith("_", StringComparison.Ordinal):
  2578. break;
  2579. default:
  2580. element.WriteTo(writer);
  2581. break;
  2582. }
  2583. }
  2584. var stu = account.Deserialize<Student>();
  2585. if (stu.guardians.IsNotEmpty() && studentInfos[id].guardians != null)
  2586. {
  2587. var mobiles = stu.guardians.Select(m => m.mobile);
  2588. var except = mobiles.Except(studentInfos[id].guardians.Select(x => x.mobile));
  2589. if (except.Any())
  2590. {
  2591. //清除移除的监护人
  2592. List<Guardian> guardians = new List<Guardian>();
  2593. string sql = $"select distinct value (c) from c where c.mobile in ({string.Join(",", except.Select(z => $"'{z}'"))} )";
  2594. await foreach (var guard in cosmosContainer.GetItemQueryIterator<Guardian>(queryText: sql,
  2595. requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base-Guardian") }))
  2596. {
  2597. guard.students.RemoveAll(s => s.id.Equals(id) && s.code.Equals(schoolId));
  2598. guardians.Add(guard);
  2599. }
  2600. guardians.ForEach(async x =>
  2601. {
  2602. if (x.students.IsNotEmpty())
  2603. {
  2604. try { await cosmosContainer.ReplaceItemAsync(x, x.id, new PartitionKey(x.code)); } catch { }
  2605. }
  2606. else
  2607. {
  2608. try
  2609. {
  2610. await cosmosContainer.DeleteItemStreamAsync(x.id, new PartitionKey(x.code));
  2611. }
  2612. catch
  2613. {
  2614. }
  2615. }
  2616. });
  2617. }
  2618. }
  2619. if (studentInfos[id].guardians.IsNotEmpty())
  2620. {
  2621. foreach (var gtudentGuardian in studentInfos[id].guardians)
  2622. {
  2623. List<Guardian> guardians = new List<Guardian>();
  2624. string sql = $"select distinct value (c) from c where c.mobile='{gtudentGuardian.mobile}' ";
  2625. await foreach (var guard in cosmosContainer.GetItemQueryIterator<Guardian>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base-Guardian") }))
  2626. {
  2627. guardians.Add(guard);
  2628. }
  2629. if (guardians.Any())
  2630. {
  2631. guardians.ForEach(async x =>
  2632. {
  2633. GuardianStudent guardianStudent = x.students.Find(s => s.id.Equals(id) && s.code.Equals(schoolId));
  2634. if (guardianStudent == null)
  2635. {
  2636. x.students.Add(new GuardianStudent { relation = gtudentGuardian.relation, type = 2, id = id, code = schoolId, name = studentInfos[id].name });
  2637. }
  2638. try { await cosmosContainer.ReplaceItemAsync(x, x.id, new PartitionKey(x.code)); } catch { }
  2639. });
  2640. }
  2641. else
  2642. {
  2643. Guardian guardian = new Guardian
  2644. {
  2645. id = Guid.NewGuid().ToString(),
  2646. code = "Base-Guardian",
  2647. pk = "Guardian",
  2648. mobile = gtudentGuardian.mobile,
  2649. name = gtudentGuardian.name,
  2650. students = new List<GuardianStudent> { new GuardianStudent { relation = gtudentGuardian.relation, type = 2, id = id, code = schoolId, name = studentInfos[id].name } }
  2651. };
  2652. try { await cosmosContainer.CreateItemAsync(guardian, new PartitionKey(guardian.code)); } catch { }
  2653. }
  2654. }
  2655. writer.WriteStartArray("guardians");
  2656. foreach (var guardian in studentInfos[id].guardians)
  2657. {
  2658. writer.WriteStartObject();
  2659. writer.WriteString("relation", guardian.relation);
  2660. writer.WriteString("name", guardian.name);
  2661. writer.WriteString("mobile", guardian.mobile);
  2662. writer.WriteString("mail", guardian.mail);
  2663. writer.WriteString("picture", guardian.picture);
  2664. writer.WriteString("tmdid", guardian.tmdid);
  2665. writer.WriteEndObject();
  2666. }
  2667. writer.WriteEndArray();
  2668. }
  2669. else
  2670. {
  2671. writer.WriteStartArray("guardians");
  2672. //writer.WriteStartObject();
  2673. //writer.WriteEndObject();
  2674. writer.WriteEndArray();
  2675. }
  2676. //如果有錯誤,如座號重覆等,就會跳過該次更新。
  2677. if (isWrong)
  2678. {
  2679. await writer.DisposeAsync();
  2680. continue;
  2681. }
  2682. //#2769 C343 学生管理--导入学生名单,IRS编号默认与座号一致
  2683. //if (!account.TryGetProperty("irs", out JsonElement _irs) || _irs.ValueKind.Equals(JsonValueKind.Undefined))
  2684. //{
  2685. // writer.WriteString("irs", studentInfos[id].irs);
  2686. //}
  2687. writer.WriteString("irs", studentInfos[id].no);
  2688. //若密碼和鹽沒有更新,就把舊的資料寫回去
  2689. if (!isUpPwDone)
  2690. {
  2691. writer.WriteString("salt", account.GetProperty("salt").GetString());
  2692. writer.WriteString("pw", account.GetProperty("pw").GetString());
  2693. }
  2694. writer.WriteEndObject();
  2695. writer.Flush();
  2696. //编辑是是否要明确清除电子学生证。
  2697. await upsertImei(id, studentInfos[id].imei, schoolId, "clean", _azureCosmos
  2698. .GetCosmosClient()
  2699. .GetContainer(Constant.TEAMModelOS, "Student"));
  2700. try
  2701. {
  2702. var ret = await cosmosContainer.ReplaceItemStreamAsync(memoryStream, id, new PartitionKey($"Base-{schoolId}"));
  2703. //將更新完的id從字典內移除,保留沒查到的。
  2704. if (ret.Status == (int)HttpStatusCode.OK)
  2705. {
  2706. nonexistentIds.Remove(id);
  2707. retStuds.Add(new { id, tmpData.gender, tmpData.mail, tmpData.imei, tmpData.mobile, tmpData.name, tmpData.picture, tmpData.year, tmpData.no, classId, classNo, className, gradeId, periodId, tmpData.irs });
  2708. }
  2709. else errorIds.Add(id);
  2710. }
  2711. catch (CosmosException ex)
  2712. {
  2713. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/updateStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2714. errorIds.Add(id);
  2715. }
  2716. catch (Exception ex)
  2717. {
  2718. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/updateStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2719. errorIds.Add(id);
  2720. }
  2721. }
  2722. }
  2723. //將輸入不存在的資料移除。
  2724. // nonexistentIds.ForEach(o => studentInfos.Remove(o));
  2725. }
  2726. }
  2727. }
  2728. errorClassId.ForEach(o => impClassDuplNo.Remove(o));
  2729. return (retStuds, impClassDuplNo.Where(o => o.Value.Count != 0).ToDictionary(o => o.Key, o => o.Value), nonexistentIds, errorIds, errorNos, errorClassId);
  2730. }
  2731. catch (CosmosException ex)
  2732. {
  2733. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/updateStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2734. }
  2735. catch (Exception ex)
  2736. {
  2737. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/updateStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2738. }
  2739. return (null, null, null, null, null, null);
  2740. }
  2741. /// <summary>
  2742. /// 創建學生帳號,目前SDK4.0預覽版還不支援批量創建(TransactionalBatch),待SDK正式發行時在優化此代碼。
  2743. /// </summary>
  2744. /// <param name="userStudents"></param>
  2745. /// <returns>已存在的ID</returns>
  2746. private async Task<(bool isSuc, List<string> existId)> createStudents(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, List<Student> userStudents)
  2747. {
  2748. var existId = new List<string>();
  2749. var exceptions = new List<Exception>();
  2750. try
  2751. {
  2752. var container = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student");
  2753. Parallel.ForEach(userStudents, async item =>
  2754. {
  2755. try
  2756. {
  2757. await container.CreateItemAsync(item);
  2758. }
  2759. catch (CosmosException ex)
  2760. {
  2761. if (ex.Status == (int)HttpStatusCode.Conflict) existId.Add(item.id);
  2762. else exceptions.Add(ex);
  2763. }
  2764. catch (Exception ex)
  2765. {
  2766. exceptions.Add(ex);
  2767. }
  2768. });
  2769. if (exceptions.Count == 0) return (true, existId);
  2770. else if (exceptions.Count > 1) throw new AggregateException(exceptions);
  2771. else if (exceptions.Count == 1) throw exceptions.Single();
  2772. }
  2773. catch (AggregateException ex)
  2774. {
  2775. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2776. }
  2777. catch (Exception ex)
  2778. {
  2779. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2780. }
  2781. return (false, existId);
  2782. }
  2783. /// <summary>
  2784. /// 取得該教室的學生座號,若有給座號LIST,則座號存在才會被查到;反之,若沒給則會將該間教室所有座號抓出來。
  2785. /// </summary>
  2786. /// <param name="schoolId"></param>
  2787. /// <param name="classId"></param>
  2788. /// <param name="nos"></param>
  2789. /// <returns></returns>
  2790. public static async Task<List<(string id, string no)>> checkStudNo(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, string classId, List<string> nos = null)
  2791. {
  2792. List<(string id, string no)> ret = new List<(string id, string no)>();
  2793. string queryText = $"SELECT c.id, c.no FROM c WHERE c.classId = '{classId}' AND c.code = 'Base-{schoolId}'";
  2794. if (nos != null) queryText += $"AND c.no IN ({string.Join(",", nos.Select(o => $"'{o}'"))})";
  2795. await foreach (Response item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student")
  2796. .GetItemQueryStreamIterator(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  2797. {
  2798. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  2799. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2800. {
  2801. var classInfos = json.RootElement.GetProperty("Documents").EnumerateArray();
  2802. while (classInfos.MoveNext())
  2803. {
  2804. JsonElement account = classInfos.Current;
  2805. string id = account.GetProperty("id").GetString();
  2806. string no = account.GetProperty("no").GetString();
  2807. ret.Add((id, no));
  2808. }
  2809. }
  2810. }
  2811. return ret;
  2812. }
  2813. /// <summary>
  2814. /// 取得年級資訊
  2815. /// </summary>
  2816. /// <param name="schoolId"></param>
  2817. /// <returns>Key:periodId Vaule:list gradeInfo</returns>
  2818. public static async Task<Dictionary<string, List<(int gradeId, string gradeName)>>> getGrades(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId)
  2819. {
  2820. try
  2821. {
  2822. //Key:學制 Value:年級資訊list
  2823. Dictionary<string, List<(int gradeId, string gradeName)>> dicPeriod = new Dictionary<string, List<(int gradeId, string gradeName)>>();
  2824. var response = await _azureCosmos
  2825. .GetCosmosClient()
  2826. .GetContainer(Constant.TEAMModelOS, "School")
  2827. .ReadItemStreamAsync(schoolId, new PartitionKey("Base"));
  2828. if (response.Status != (int)HttpStatusCode.OK) return null;
  2829. using Stream stream = response.ContentStream;
  2830. var jsonDoc = await JsonDocument.ParseAsync(stream);
  2831. var emumObject = jsonDoc.RootElement.EnumerateObject();
  2832. var period = jsonDoc.RootElement.GetProperty("period").EnumerateArray();
  2833. while (period.MoveNext())
  2834. {
  2835. List<(int gradeId, string gradeName)> gradeInfos = new List<(int gradeId, string gradeName)>();
  2836. JsonElement jsonPeriod = period.Current;
  2837. var periodId = jsonPeriod.GetProperty("id").GetString();
  2838. var grades = jsonPeriod.GetProperty("grades").ToObject<List<string>>();
  2839. for (int index = 0; index < grades.Count; index++)
  2840. {
  2841. gradeInfos.Add((index, grades[index]));
  2842. }
  2843. //var grades = jsonPeriod.GetProperty("grades").EnumerateArray();
  2844. //while (grades.MoveNext())
  2845. //{
  2846. // JsonElement grade = grades.Current;
  2847. // var gradeId = grade.GetInt32();
  2848. // var gradeName = grade.GetProperty("name").GetString();
  2849. // gradeInfos.Add((gradeId, gradeName));
  2850. //}
  2851. dicPeriod.Add(periodId, gradeInfos);
  2852. }
  2853. return dicPeriod;
  2854. }
  2855. catch (Exception ex)
  2856. {
  2857. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getGrades()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2858. return null;
  2859. }
  2860. }
  2861. public struct studCreateInfo
  2862. {
  2863. public studCreateInfo(string id, string name, string gender, int year, string pw, string classId, string no, string periodId, string imei, List<StudentGuardian> guardians)
  2864. {
  2865. this.id = id;
  2866. this.name = name;
  2867. this.gender = gender;
  2868. this.year = year;
  2869. this.pw = pw;
  2870. this.classId = classId;
  2871. this.no = no;
  2872. this.periodId = periodId;
  2873. this.imei = imei;
  2874. this.guardians = guardians;
  2875. }
  2876. public string id { get; }
  2877. public string name { get; }
  2878. public string gender { get; }
  2879. public int year { get; }
  2880. public string pw { get; }
  2881. public string classId { get; }
  2882. public string no { get; }
  2883. public string periodId { get; set; }
  2884. public string imei { get; set; }
  2885. public List<StudentGuardian> guardians { get; set; }
  2886. }
  2887. }
  2888. }