StudentService.cs 176 KB

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