StudentService.cs 173 KB

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