StudentService.cs 177 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192
  1. using Azure;
  2. using Microsoft.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").GetItemQueryIteratorSql<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").GetItemQueryIteratorSql<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. if (classInfos!=null)
  1076. {
  1077. foreach (var classInfo in classInfos)
  1078. {
  1079. classes.Add(classInfo.Value);
  1080. string classGradeId = classInfo.Value.gradeId;
  1081. int classYear = classInfo.Value.year;
  1082. classNoId.Add(classInfo.Value.no + "_" + classYear,
  1083. (classInfo.Value.id, classInfo.Value.name, classInfo.Value.periodId, classGradeId, classYear));
  1084. tasks.Add(
  1085. Task.Run(
  1086. async () =>
  1087. {
  1088. //(id,no)
  1089. var studNo = await checkStudNo(_azureCosmos, _dingDing, _option, schoolId, classInfo.Value.id);
  1090. classStudNos.Add(classInfo.Value.no + "_" + classInfo.Value.year, studNo);
  1091. }));
  1092. }
  1093. }
  1094. //這邊整理出不存在的教室,之後創建新教室用(比對classNo)。
  1095. //var nonexistentClassNo = classNos.Except(classInfos.Select(o => o.Key).ToList());
  1096. List<string> exsitkey = new List<string>();
  1097. foreach (var classInfo in classInfos)
  1098. {
  1099. //$"{studentInfo.periodId}_{year}_{tmpClassNo.GetString()}"
  1100. var key = $"{classInfo.Value.periodId}_{classInfo.Value.year}_{classInfo.Value.no}";
  1101. exsitkey.Add(key);
  1102. }
  1103. List<KeyValuePair<string, (string className, string periodId, int year, string no)>> nonexistentClassNo = new List<KeyValuePair<string, (string className, string periodId, int year, string no)>>();
  1104. foreach (var key in sortedImpData.classInfo.Keys)
  1105. {
  1106. if (!exsitkey.Contains(key))
  1107. {
  1108. nonexistentClassNo.Add(new KeyValuePair<string, (string className, string periodId, int year, string no)>(key, sortedImpData.classInfo[key]));
  1109. }
  1110. }
  1111. // var nonexistentClassNo = exsitkey.Except(sortedImpData.classInfo.Select(o => o.Key).ToList());
  1112. if (nonexistentClassNo.Count() != 0)
  1113. {
  1114. var gradesInfo = await getGrades(_azureCosmos, _dingDing, _option, schoolId);
  1115. foreach (var item in nonexistentClassNo)
  1116. {
  1117. string gradeId = string.Empty;
  1118. string periodId = periodId = sortedImpData.classInfo[item.Key].periodId;
  1119. int year = sortedImpData.classInfo[item.Key].year;
  1120. //確認該學段存在及輸入的年級index正確(-1後大於等於0)
  1121. //if (gradesInfo.ContainsKey(sortedImpData.classInfo[item].periodId) && sortedImpData.classInfo[item].gradeIndex - 1>=0)
  1122. // {
  1123. // periodId = sortedImpData.classInfo[item].periodId;
  1124. //gradeId = gradesInfo[sortedImpData.classInfo[item].periodId][sortedImpData.classInfo[item].gradeIndex - 1].gradeId;
  1125. //}
  1126. //建立新教室
  1127. (string classId, string classNo, string className, string periodId, string gradeId, int classYear) retCreateClassInfo =
  1128. await createClassInfo(_azureCosmos, _dingDing, _option,
  1129. schoolId,
  1130. null,
  1131. sortedImpData.classInfo[item.Key].className,
  1132. sortedImpData.classInfo[item.Key].no,
  1133. periodId,
  1134. gradeId,
  1135. year);
  1136. classStudNos.Add(retCreateClassInfo.classNo + "_" + retCreateClassInfo.classYear, new List<(string id, string no)>());
  1137. classNoId.Add(retCreateClassInfo.classNo + "_" + retCreateClassInfo.classYear, (retCreateClassInfo.classId, retCreateClassInfo.className, periodId, gradeId, year));
  1138. }
  1139. }
  1140. var taskWhenAll = Task.WhenAll(tasks);
  1141. taskWhenAll.Wait();
  1142. //-------------------------------------------------------------------------
  1143. //建立學生或是更新學生,並且要確認座號是否重複
  1144. //每間教室的全部座號 欲更新的教室座號
  1145. //先新建帳號若出現409則進行資料更新
  1146. //紀錄有重複做號的id
  1147. Dictionary<string, List<string>> duplNos = new Dictionary<string, List<string>>();
  1148. List<string> errorIds = new List<string>();
  1149. List<object> retStuds = new List<object>();
  1150. Container cosmosContainer = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student");
  1151. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  1152. //並行處理
  1153. foreach (var stud in sortedImpData.studs)
  1154. {
  1155. //這邊一樣要確認已存在和欲加入還有欲修改的座號。
  1156. //欲修改的不會有重複
  1157. string classId = null;
  1158. bool isContinue = false;
  1159. if (!string.IsNullOrWhiteSpace(stud.Value.no) && !string.IsNullOrWhiteSpace(stud.Value.classNo))
  1160. {
  1161. classId = classNoId[stud.Value.classNo + "_" + stud.Value.classYear].classId;
  1162. (string id, string no) existNoInfo = (null, null);
  1163. //檢查要更新的座號是否已存在於雲端座號(已被其他同學使用)
  1164. classStudNos[stud.Value.classNo + "_" + stud.Value.classYear].ForEach(
  1165. o =>
  1166. {
  1167. if (o.no.Equals(stud.Value.no) && !o.id.Equals(stud.Key))
  1168. {
  1169. existNoInfo = (o.id, o.no);
  1170. if (duplNos.ContainsKey(stud.Value.classNo)) duplNos[stud.Value.classNo].Add(stud.Key);
  1171. else duplNos.Add(stud.Value.classNo, new List<string>() { stud.Key });
  1172. }
  1173. });
  1174. //如果不是空的代表有座號重覆到,此時要再確認這個重複座號的id,是否存在於這次的更新,而且是要更新座號的。
  1175. if (!string.IsNullOrWhiteSpace(existNoInfo.id))
  1176. {
  1177. isContinue = true;
  1178. //輪巡所有匯入的學生資料,並檢查匯入的座號。
  1179. sortedImpData.classStudNo[stud.Value.classNo].ForEach(
  1180. o =>
  1181. {
  1182. if (o.id.Equals(existNoInfo.id) && !o.no.Equals(existNoInfo.no))
  1183. {
  1184. //可以更新該座號
  1185. isContinue = false;
  1186. duplNos[stud.Value.classNo].Remove(stud.Key);
  1187. return;
  1188. }
  1189. });
  1190. }
  1191. }
  1192. if (isContinue) continue;
  1193. (string id, string name, string picture, int year, string no, string classId, string classNo, string className, string gradeId, string periodId) tmpStudInfo
  1194. = (stud.Key, stud.Value.name, null, stud.Value.year, stud.Value.no, null, stud.Value.classNo, null, null, null);
  1195. using var memoryStream = new MemoryStream();
  1196. using var writerNew = new Utf8JsonWriter(memoryStream);
  1197. writerNew.WriteStartObject();
  1198. writerNew.WriteString("id", stud.Key);
  1199. writerNew.WriteString("pk", $"Base");
  1200. writerNew.WriteString("code", $"Base-{schoolId}");
  1201. writerNew.WriteString("schoolId", schoolId);
  1202. writerNew.WriteNumber("year", stud.Value.year);
  1203. writerNew.WriteNumber("createTime", now);
  1204. writerNew.WriteString("salt", stud.Value.salt);
  1205. writerNew.WriteString("pw", stud.Value.pw);
  1206. if (string.IsNullOrWhiteSpace(stud.Value.name)) writerNew.WriteNull("name");
  1207. else writerNew.WriteString("name", stud.Value.name);
  1208. if (string.IsNullOrWhiteSpace(stud.Value.gender)) writerNew.WriteNull("gender");
  1209. else writerNew.WriteString("gender", stud.Value.gender);
  1210. writerNew.WriteNull("picture");
  1211. writerNew.WriteNull("mail");
  1212. writerNew.WriteNull("mobile");
  1213. writerNew.WriteNull("country");
  1214. if (!string.IsNullOrWhiteSpace(stud.Value.periodId))
  1215. {
  1216. writerNew.WriteString("periodId", stud.Value.periodId);
  1217. }
  1218. if (string.IsNullOrWhiteSpace(stud.Value.classNo)) writerNew.WriteNull("classId");
  1219. else
  1220. {
  1221. writerNew.WriteString("classId", classId);
  1222. tmpStudInfo.classId = classId;
  1223. tmpStudInfo.className = classNoId[stud.Value.classNo + "_" + stud.Value.classYear].className;
  1224. tmpStudInfo.gradeId = classNoId[stud.Value.classNo + "_" + stud.Value.classYear].gradeId;
  1225. tmpStudInfo.periodId = classNoId[stud.Value.classNo + "_" + stud.Value.classYear].periodId;
  1226. }
  1227. if (string.IsNullOrWhiteSpace(stud.Value.no))
  1228. {
  1229. writerNew.WriteNull("no");
  1230. writerNew.WriteNull("irs");
  1231. }
  1232. else
  1233. {
  1234. writerNew.WriteString("irs", stud.Value.no);
  1235. writerNew.WriteString("no", stud.Value.no);
  1236. };
  1237. writerNew.WriteNull("groupId");
  1238. writerNew.WriteNull("groupName");
  1239. ///写入监护人
  1240. if (!string.IsNullOrWhiteSpace(stud.Value.gPhone))
  1241. {
  1242. writerNew.WriteStartArray("guardians");
  1243. writerNew.WriteStartObject();
  1244. writerNew.WriteString("relation", stud.Value.guardian);
  1245. writerNew.WriteString("name", stud.Value.gName);
  1246. writerNew.WriteString("mobile", stud.Value.gPhone);
  1247. writerNew.WriteEndObject();
  1248. writerNew.WriteEndArray();
  1249. }
  1250. writerNew.WriteEndObject();
  1251. writerNew.Flush();
  1252. if (!string.IsNullOrWhiteSpace(stud.Value.imei))
  1253. {
  1254. await upsertImei(stud.Key, stud.Value.imei, schoolId, "keep", cosmosContainer);
  1255. }
  1256. var response = await cosmosContainer.CreateItemStreamAsync(memoryStream, new PartitionKey($"Base-{schoolId}"));
  1257. if (response.StatusCode == HttpStatusCode.Created)
  1258. {
  1259. //如果是Created則啥都不做,讓他去下面進行資料的彙整。
  1260. }
  1261. //查到已存在的id,則進行基本資料更新。
  1262. else if (response.StatusCode == HttpStatusCode.Conflict)
  1263. {
  1264. try
  1265. {
  1266. bool isUpPwDone = false;
  1267. Student student = await _azureCosmos
  1268. .GetCosmosClient()
  1269. .GetContainer(Constant.TEAMModelOS, "Student")
  1270. .ReadItemAsync<Student>(stud.Key, new PartitionKey($"Base-{schoolId}"));
  1271. if (!string.IsNullOrWhiteSpace(stud.Value.name))
  1272. {
  1273. student.name = stud.Value.name;
  1274. }
  1275. if (stud.Value.year > 0)
  1276. {
  1277. student.year = stud.Value.year;
  1278. }
  1279. if (!string.IsNullOrWhiteSpace(stud.Value.no))
  1280. {
  1281. student.no = stud.Value.no;
  1282. student.irs = stud.Value.no;
  1283. }
  1284. if (!string.IsNullOrWhiteSpace(stud.Value.gender))
  1285. {
  1286. student.gender = stud.Value.gender;
  1287. }
  1288. if (!string.IsNullOrWhiteSpace(stud.Value.classNo))
  1289. {
  1290. student.classId = classId;
  1291. }
  1292. if (!string.IsNullOrWhiteSpace(stud.Value.periodId))
  1293. {
  1294. student.periodId = stud.Value.periodId;
  1295. }
  1296. if (!string.IsNullOrWhiteSpace(student.classId))
  1297. {
  1298. var clazz = classes.FindAll(x => x.id.Equals(student.classId));
  1299. if (clazz.IsNotEmpty())
  1300. {
  1301. student.graduate = clazz[0].graduate;
  1302. }
  1303. }
  1304. if (!isUpPwDone)
  1305. {
  1306. student.pw = stud.Value.pw;
  1307. student.salt = stud.Value.salt;
  1308. isUpPwDone = true;
  1309. }
  1310. tmpStudInfo.picture = student.picture;
  1311. if (!string.IsNullOrWhiteSpace(stud.Value.gPhone))
  1312. {
  1313. List<Guardian> guardians = new List<Guardian>();
  1314. string sql = $"select distinct value (c) from c where c.mobile='{stud.Value.gPhone}' ";
  1315. await foreach (var item in cosmosContainer.GetItemQueryIteratorSql<Guardian>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base-Guardian") }))
  1316. {
  1317. guardians.Add(item);
  1318. }
  1319. if (guardians.Any())
  1320. {
  1321. guardians.ForEach(async x =>
  1322. {
  1323. GuardianStudent guardianStudent = x.students.Find(s => s.id.Equals(stud.Key) && s.code.Equals(schoolId));
  1324. if (guardianStudent == null)
  1325. {
  1326. x.students.Add(new GuardianStudent { relation = stud.Value.guardian, type = 2, id = stud.Key, code = schoolId, name = stud.Value.name });
  1327. }
  1328. await cosmosContainer.ReplaceItemAsync(x, x.id, new PartitionKey(x.code));
  1329. });
  1330. }
  1331. else
  1332. {
  1333. Guardian guardian = new Guardian
  1334. {
  1335. id = Guid.NewGuid().ToString(),
  1336. code = "Base-Guardian",
  1337. pk = "Guardian",
  1338. mobile = stud.Value.gPhone,
  1339. name = stud.Value.gName,
  1340. students = new List<GuardianStudent> { new GuardianStudent { relation = stud.Value.guardian, type = 2, id = stud.Key, code = schoolId, name = stud.Value.name } }
  1341. };
  1342. await cosmosContainer.CreateItemAsync(guardian, new PartitionKey(guardian.code));
  1343. }
  1344. var studentGuardian = student.guardians.Find(x => !string.IsNullOrWhiteSpace(x.mobile) && x.mobile.Equals(stud.Value.gPhone));
  1345. if (studentGuardian != null)
  1346. {
  1347. studentGuardian.name = stud.Value.gName;
  1348. studentGuardian.relation = stud.Value.guardian;
  1349. }
  1350. else
  1351. {
  1352. student.guardians.Add(new StudentGuardian { mobile = stud.Value.gPhone, name = stud.Value.gName, relation = stud.Value.guardian });
  1353. }
  1354. }
  1355. if (stud.Value.guardians.IsNotEmpty())
  1356. {
  1357. student.guardians = stud.Value.guardians;
  1358. }
  1359. await cosmosContainer.ReplaceItemAsync(student, stud.Key, new PartitionKey($"Base-{schoolId}"));
  1360. }
  1361. catch (CosmosException ex)
  1362. {
  1363. errorIds.Add(stud.Key);
  1364. continue;
  1365. }
  1366. }
  1367. else
  1368. {
  1369. errorIds.Add(stud.Key);
  1370. continue;
  1371. }
  1372. //整理輸出用資料
  1373. retStuds.Add(
  1374. new
  1375. {
  1376. tmpStudInfo.id,
  1377. tmpStudInfo.name,
  1378. tmpStudInfo.picture,
  1379. tmpStudInfo.year,
  1380. tmpStudInfo.no,
  1381. tmpStudInfo.classId,
  1382. tmpStudInfo.classNo,
  1383. tmpStudInfo.className,
  1384. // tmpStudInfo.gradeId,
  1385. // tmpStudInfo.periodId
  1386. });
  1387. }
  1388. return (retStuds, duplNos.Where(o => o.Value.Count != 0).ToDictionary(o => o.Key, o => o.Value), errorIds);
  1389. }
  1390. catch (Exception ex)
  1391. {
  1392. await _dingDing.SendBotMsg(
  1393. $"IES5,{_option.Location},StudentController/upsertStudents()\nex:{ex.Message}\n{ex.StackTrace}",
  1394. GroupNames.醍摩豆服務運維群組);
  1395. }
  1396. return (null, null, null);
  1397. }
  1398. /// <summary>
  1399. /// grand_type
  1400. /// 为import:如果导入则已最新,没导入则不动这个字段的值,维持现状
  1401. /// 为create:如果有值,则绑定,并删除stuid关联的别的imei.
  1402. /// 为update
  1403. /// 为delete
  1404. /// </summary>
  1405. /// <param name="stuid"></param>
  1406. /// <param name="imei"></param>
  1407. /// <param name="schoolId"></param>
  1408. /// <param name="grand_type"></param>
  1409. /// <param name="cosmosContainer">
  1410. /// clean 当传入的电子学生证值为空,判断要强制清除关联的学生电子学生证 ,
  1411. /// keep 保持现状,导入时
  1412. /// delete 因学生被删除,强制删除电子学生证。</param>
  1413. /// <returns></returns>
  1414. public static async Task upsertImei(string stuid, string imeiid, string schoolId, string grand_type, Container cosmosContainer)
  1415. {
  1416. List<Imei> imeis = new List<Imei>();
  1417. string sql = $"select value c from c where c.stuid='{stuid}' and c.school='{schoolId}' ";
  1418. await foreach (var item in cosmosContainer.GetItemQueryIteratorSql<Imei>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Imei") }))
  1419. {
  1420. imeis.Add(item);
  1421. }
  1422. switch (grand_type)
  1423. {
  1424. case "clean":
  1425. case "keep":
  1426. bool notin = true;
  1427. List<Imei> update = new List<Imei>();
  1428. List<Imei> delete = new List<Imei>();
  1429. imeis.ForEach(x =>
  1430. {
  1431. //如果传入的电子学生证id不存在,且是单个更新或创建,则解除学生id的电子学生证绑定,并删除该电子学生证。
  1432. if (string.IsNullOrWhiteSpace(imeiid))
  1433. {
  1434. if (grand_type.Equals("clean"))
  1435. {
  1436. delete.Add(x);
  1437. }// 如果是导入模式,且电子学生证没有值则不动。
  1438. }
  1439. else
  1440. {
  1441. //如果电子学生证有值则,解除之前的所有与当前电子学生证id不符的绑定。
  1442. if (!x.id.Equals(imeiid))
  1443. {
  1444. x.stuid = null;
  1445. x.school = null;
  1446. delete.Add(x);
  1447. }
  1448. else
  1449. {
  1450. //存在且正确绑定
  1451. notin = false;
  1452. }
  1453. }
  1454. });
  1455. //当前学生还未有任何电子学生证,且有新的电子学生证id传入,则需要捞出电子学生证,绑定,如果没有捞出,则新建电子学生证,并绑定
  1456. if (notin && !string.IsNullOrWhiteSpace(imeiid))
  1457. {
  1458. var imeiResponse = await cosmosContainer.ReadItemStreamAsync(imeiid, new PartitionKey("Imei"));
  1459. if (imeiResponse.StatusCode == HttpStatusCode.OK)
  1460. {
  1461. Imei imeiDb = JsonDocument.Parse(imeiResponse.Content).RootElement.Deserialize<Imei>();
  1462. imeiDb.stuid = stuid;
  1463. imeiDb.school = schoolId;
  1464. await cosmosContainer.ReplaceItemAsync(imeiDb, imeiDb.id, new PartitionKey("Imei"));
  1465. }
  1466. else
  1467. {
  1468. Imei imei = new Imei { id = imeiid, code = "Imei", pk = "Imei", stuid = stuid, school = schoolId };
  1469. await cosmosContainer.CreateItemAsync(imei, new PartitionKey($"Imei"));
  1470. };
  1471. }
  1472. if (delete.Any())
  1473. {
  1474. await cosmosContainer.DeleteItemsStreamAsync(delete.Select(x => x.id).ToList(), "Imei");
  1475. }
  1476. break;
  1477. case "delete":
  1478. if (imeis.Any())
  1479. {
  1480. await cosmosContainer.DeleteItemsStreamAsync(imeis.Select(x => x.id).ToList(), "Imei");
  1481. }
  1482. break;
  1483. }
  1484. }
  1485. /// <summary>
  1486. /// 單純建立單一學生
  1487. /// </summary>
  1488. /// <param name="schoolId"></param>
  1489. /// <param name="studCreateInfo"></param>
  1490. public static async Task<bool> createStudent(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, studCreateInfo studCreateInfo)
  1491. {
  1492. try
  1493. {
  1494. using var stream = new MemoryStream();
  1495. using var writer = new Utf8JsonWriter(stream);
  1496. writer.WriteStartObject();
  1497. writer.WriteString("pk", $"Base");
  1498. writer.WriteString("code", $"Base-{schoolId}");
  1499. writer.WriteString("id", studCreateInfo.id);
  1500. if (string.IsNullOrWhiteSpace(studCreateInfo.name)) writer.WriteNull("name");
  1501. else writer.WriteString("name", studCreateInfo.name);
  1502. if (string.IsNullOrWhiteSpace(studCreateInfo.gender)) writer.WriteNull("gender");
  1503. else writer.WriteString("gender", studCreateInfo.gender);
  1504. writer.WriteString("schoolId", schoolId);
  1505. //20210713 huanghb add 增加学段
  1506. if (string.IsNullOrWhiteSpace(studCreateInfo.periodId)) writer.WriteNull("periodId");
  1507. else writer.WriteString("periodId", studCreateInfo.periodId);
  1508. writer.WriteNumber("year", studCreateInfo.year);
  1509. writer.WriteNumber("createTime", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
  1510. writer.WriteNull("picture");
  1511. writer.WriteNull("mail");
  1512. writer.WriteNull("mobile");
  1513. writer.WriteNull("country");
  1514. //Password,若沒給則使用學號當密碼
  1515. string salt = Utils.CreatSaltString(8);
  1516. string hashPw = string.IsNullOrWhiteSpace(studCreateInfo.pw)
  1517. ? Utils.HashedPassword(studCreateInfo.id, salt)
  1518. : Utils.HashedPassword(studCreateInfo.pw, salt);
  1519. writer.WriteString("salt", salt);
  1520. writer.WriteString("pw", hashPw);
  1521. if (string.IsNullOrWhiteSpace(studCreateInfo.classId)) writer.WriteNull("classId");
  1522. else writer.WriteString("classId", studCreateInfo.classId);
  1523. if (string.IsNullOrWhiteSpace(studCreateInfo.no))
  1524. {
  1525. writer.WriteNull("no");
  1526. writer.WriteNull("irs");
  1527. }
  1528. else
  1529. {
  1530. writer.WriteString("no", studCreateInfo.no);
  1531. writer.WriteString("irs", studCreateInfo.no);
  1532. }
  1533. writer.WriteNull("groupId");
  1534. writer.WriteNull("groupName");
  1535. if (studCreateInfo.guardians.IsNotEmpty())
  1536. {
  1537. writer.WriteStartArray("guardians");
  1538. foreach (var guardian in studCreateInfo.guardians)
  1539. {
  1540. writer.WriteStartObject();
  1541. writer.WriteString("relation", guardian.relation);
  1542. writer.WriteString("name", guardian.name);
  1543. writer.WriteString("mobile", guardian.mobile);
  1544. writer.WriteEndObject();
  1545. }
  1546. writer.WriteEndArray();
  1547. foreach (var studentGuardian in studCreateInfo.guardians)
  1548. {
  1549. List<Guardian> guardians = new List<Guardian>();
  1550. string sql = $"select distinct value (c) from c where c.mobile='{studentGuardian.mobile}' ";
  1551. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).GetItemQueryIteratorSql<Guardian>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base-Guardian") }))
  1552. {
  1553. guardians.Add(item);
  1554. }
  1555. if (guardians.Any())
  1556. {
  1557. guardians.ForEach(async x =>
  1558. {
  1559. GuardianStudent guardianStudent = x.students.Find(s => s.id.Equals(studCreateInfo.id) && s.code.Equals(schoolId));
  1560. if (guardianStudent == null)
  1561. {
  1562. x.students.Add(new GuardianStudent { relation = studentGuardian.relation, type = 2, id = studCreateInfo.id, code = schoolId, name = studCreateInfo.name });
  1563. }
  1564. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).ReplaceItemAsync(x, x.id, new PartitionKey(x.code));
  1565. });
  1566. }
  1567. else
  1568. {
  1569. Guardian guardian = new Guardian
  1570. {
  1571. id = Guid.NewGuid().ToString(),
  1572. code = "Base-Guardian",
  1573. pk = "Guardian",
  1574. mobile = studentGuardian.mobile,
  1575. name = studentGuardian.name,
  1576. students = new List<GuardianStudent> { new GuardianStudent { relation = studentGuardian.relation, type = 2, id = studCreateInfo.id, code = schoolId, name = studCreateInfo.name } }
  1577. };
  1578. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).CreateItemAsync(guardian, new PartitionKey(guardian.code));
  1579. }
  1580. }
  1581. }
  1582. else
  1583. {
  1584. writer.WriteStartArray("guardians");
  1585. writer.WriteStartObject();
  1586. writer.WriteEndObject();
  1587. writer.WriteEndArray();
  1588. }
  1589. writer.WriteEndObject();
  1590. writer.Flush();
  1591. var response = await _azureCosmos
  1592. .GetCosmosClient()
  1593. .GetContainer(Constant.TEAMModelOS, "Student")
  1594. .CreateItemStreamAsync(stream, new PartitionKey($"Base-{schoolId}"));
  1595. //更新电子学生证、
  1596. await upsertImei(studCreateInfo.id, studCreateInfo.imei, schoolId, "keep", _azureCosmos
  1597. .GetCosmosClient()
  1598. .GetContainer(Constant.TEAMModelOS, "Student"));
  1599. if (response.StatusCode == HttpStatusCode.Created || response.StatusCode == HttpStatusCode.OK) return true;
  1600. if (response.StatusCode == HttpStatusCode.Conflict) return false;
  1601. else
  1602. {
  1603. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createStudent()\nCosmosDB Create response status = {response.StatusCode}\nID:{studCreateInfo.id}", GroupNames.醍摩豆服務運維群組);
  1604. return false;
  1605. }
  1606. }
  1607. catch (Exception ex)
  1608. {
  1609. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createStudent()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1610. return false;
  1611. }
  1612. }
  1613. /// <summary>
  1614. /// 生成Class資料
  1615. /// </summary>
  1616. /// <param name="schoolId"></param>
  1617. /// <param name="classId"></param>
  1618. /// <param name="className"></param>
  1619. /// <param name="students"></param>
  1620. /// <returns></returns>
  1621. private static async Task<(string classId, string classNo, string className, string periodId, string gradeId, int classYear)> createClassInfo(
  1622. AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option,
  1623. string schoolId, string classId, string className, string classNo, string periodId, string gradeId, int classYear)
  1624. {
  1625. //組Class JSON
  1626. try
  1627. {
  1628. string cId = classId;
  1629. using var memoryStream = new MemoryStream();
  1630. using var writer = new Utf8JsonWriter(memoryStream);
  1631. writer.WriteStartObject();
  1632. writer.WriteString("pk", "Class");
  1633. writer.WriteString("code", $"Class-{schoolId}");
  1634. //如果classId是空的,則生成一組GUID。
  1635. if (string.IsNullOrWhiteSpace(classId))
  1636. {
  1637. cId = Guid.NewGuid().ToString();
  1638. writer.WriteString("id", cId);
  1639. }
  1640. else writer.WriteString("id", classId);
  1641. if (string.IsNullOrWhiteSpace(classNo)) writer.WriteNull("no");
  1642. else writer.WriteString("no", classNo);
  1643. writer.WriteNull("x");
  1644. writer.WriteNull("y");
  1645. if (string.IsNullOrWhiteSpace(className)) writer.WriteNull("name");
  1646. else writer.WriteString("name", className);
  1647. writer.WritePropertyName("teacher");
  1648. writer.WriteStartObject();
  1649. writer.WriteNull("id");
  1650. writer.WriteNull("name");
  1651. writer.WriteEndObject();
  1652. //if (string.IsNullOrWhiteSpace(gradeId)) writer.WriteNull("gradeId");
  1653. //else writer.WriteString("gradeId", gradeId);
  1654. if (string.IsNullOrWhiteSpace(periodId)) writer.WriteNull("periodId");
  1655. else writer.WriteString("periodId", periodId);
  1656. writer.WriteNumber("year", classYear);
  1657. writer.WriteNumber("createTime", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
  1658. writer.WriteNull("sn");
  1659. writer.WriteString("style", "smart");
  1660. writer.WriteString("openType", "1");
  1661. writer.WriteString("scope", "school");
  1662. writer.WriteEndObject();
  1663. writer.Flush();
  1664. var ret = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").CreateItemStreamAsync(memoryStream, new PartitionKey($"Class-{schoolId}"));
  1665. if (ret.StatusCode !=HttpStatusCode.Created)
  1666. {
  1667. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createClassInfo()\nStatus:{ret.StatusCode}\nSchoolId:{schoolId},ClassId:{classId}", GroupNames.醍摩豆服務運維群組);
  1668. }
  1669. return (cId, classNo, className, periodId, gradeId, classYear);
  1670. }
  1671. catch (CosmosException ex)
  1672. {
  1673. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createClassInfo()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1674. }
  1675. catch (Exception ex)
  1676. {
  1677. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createClassInfo()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1678. }
  1679. return (null, null, null, null, null, 0);
  1680. }
  1681. /// <summary>
  1682. /// 使用學校代碼查詢該校所有學生,並且在查詢該學生所屬的教室及座號,支援offset和limit操作已及ContinuationToken,若有ContinuationToken,則會優先使用ContinuationToken。
  1683. /// </summary>
  1684. /// <param name="schoolId"></param>
  1685. /// <param name="byNameOrId">透過Name或Id來查,所以不會管學制、學級和教室</param>
  1686. /// <param name="byPeriod"></param>
  1687. /// <param name="byGrade"></param>
  1688. /// <param name="byClassId"></param>
  1689. /// <param name="offset"></param>
  1690. /// <param name="limit"></param>
  1691. /// <param name="token"></param>
  1692. /// <returns></returns>
  1693. private async Task<(List<object> students, string continuationToken)> getStudents(
  1694. AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option,
  1695. string schoolId, string byNameOrId = null, string byPeriod = null, string byGrade = null, string byClassId = null, int offset = -1, int limit = -1, string token = default)
  1696. {
  1697. try
  1698. {
  1699. //以學校學生角度去抓資料
  1700. List<(string id, string name, string picture, int year)> listStudent = new List<(string id, string name, string picture, int year)>();
  1701. string queryText = $"SELECT c.id, c.name, c.picture, c.year FROM c WHERE c.code = 'Base-{schoolId}'";
  1702. //如果有選擇ClassId的話,則先取得該教室內的學生。
  1703. List<string> searchId = new List<string>();
  1704. if (!string.IsNullOrWhiteSpace(byClassId))
  1705. {
  1706. var classInfos = await getClassInfoUseId(_azureCosmos, _dingDing, _option, schoolId, new List<string>() { byClassId });
  1707. foreach (var classInfo in classInfos)
  1708. {
  1709. var students = classInfo.Value.GetProperty("students").EnumerateArray();
  1710. while (students.MoveNext())
  1711. {
  1712. JsonElement stud = students.Current;
  1713. string id = stud.GetProperty("id").GetString();
  1714. searchId.Add(id);
  1715. }
  1716. }
  1717. //將使用者過濾classId所取得的學生ID加入sql字串內
  1718. if (searchId.Count != 0)
  1719. {
  1720. queryText = $"{queryText} AND c.id IN ({string.Join(",", searchId.Select(o => $"'{o}'"))})";
  1721. }
  1722. }
  1723. //檢查是否有接續token及是否要在sql語法內多增加offset及limit
  1724. if (string.IsNullOrWhiteSpace(token))
  1725. {
  1726. token = default;
  1727. if (offset != -1 && limit != -1) queryText = $"{queryText} OFFSET {offset} LIMIT {limit}";
  1728. }
  1729. //回傳用ContinuationToken
  1730. string continuationToken = string.Empty;
  1731. //進行學生資料的查詢
  1732. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student")
  1733. .GetItemQueryStreamIteratorSql(
  1734. queryText: queryText,
  1735. continuationToken: token,
  1736. requestOptions: new QueryRequestOptions()
  1737. { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  1738. {
  1739. continuationToken = item.ContinuationToken;
  1740. using var json = await JsonDocument.ParseAsync(item.Content);
  1741. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1742. {
  1743. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1744. while (accounts.MoveNext())
  1745. {
  1746. JsonElement account = accounts.Current;
  1747. listStudent.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString(), account.GetProperty("picture").GetString(), account.GetProperty("year").GetInt32()));
  1748. }
  1749. }
  1750. //單筆查詢上限為100條,所以查完一次即返回,並且給接續token。
  1751. break;
  1752. }
  1753. //查學生所屬的教室及座號
  1754. List<object> ret = new List<object>();
  1755. //查教室資訊,使用上面的學生id並透過子查詢查詢。
  1756. 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}'"))}))";
  1757. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
  1758. .GetItemQueryStreamIteratorSql(
  1759. queryText: queryText,
  1760. //continuationToken: token,
  1761. requestOptions: new QueryRequestOptions()
  1762. { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  1763. {
  1764. using var json = await JsonDocument.ParseAsync(item.Content);
  1765. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1766. {
  1767. var classrooms = json.RootElement.GetProperty("Documents").EnumerateArray();
  1768. while (classrooms.MoveNext())
  1769. {
  1770. JsonElement classroom = classrooms.Current;
  1771. var studs = classroom.GetProperty("students").EnumerateArray();
  1772. while (studs.MoveNext())
  1773. {
  1774. JsonElement stud = studs.Current;
  1775. string id = stud.GetProperty("id").GetString();
  1776. //整理出前端所需的資訊
  1777. var tmp = listStudent
  1778. .Where(o => o.id.Equals(id, StringComparison.Ordinal))
  1779. .Select(o =>
  1780. new
  1781. {
  1782. o.id,
  1783. o.name,
  1784. o.picture,
  1785. o.year,
  1786. no = stud.GetProperty("no").GetString(),
  1787. gradeId = classroom.GetProperty("gradeId").GetString(),
  1788. className = classroom.GetProperty("name").GetString()
  1789. });
  1790. ret.AddRange(tmp);
  1791. //刪除已整理完的ID
  1792. listStudent.RemoveAll(o => o.id.Equals(id, StringComparison.Ordinal));
  1793. }
  1794. }
  1795. }
  1796. }
  1797. var notJoinClassStuds = listStudent.Select(o =>
  1798. new
  1799. {
  1800. o.id,
  1801. o.name,
  1802. o.picture,
  1803. o.year,
  1804. no = (string)null,
  1805. gradeId = (string)null,
  1806. className = (string)null
  1807. });
  1808. ret.AddRange(notJoinClassStuds);
  1809. return (ret, continuationToken);
  1810. }
  1811. catch (CosmosException ex)
  1812. {
  1813. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1814. }
  1815. catch (Exception ex)
  1816. {
  1817. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1818. }
  1819. return (null, null);
  1820. }
  1821. /// <summary>
  1822. /// 取得該學校的所有學生。
  1823. /// </summary>
  1824. /// <param name="schoolId"></param>
  1825. /// <returns> [{id,name,picture,year,no,classId,classNo,className,gradeId,periodId},{id,name,picture,..}..]</returns>
  1826. public static async Task<List<object>> getAllStudent(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, int inyear, int graduate = 0)
  1827. {
  1828. try
  1829. {
  1830. //TODO : 進階查詢選項調整、部分地方可用並行處理
  1831. //以學校學生角度去抓資料
  1832. 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 =
  1833. 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)>>();
  1834. 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 =
  1835. 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)>();
  1836. List<Imei> imeis = new List<Imei>();
  1837. string imeiQueryText = $"SELECT * FROM c WHERE c.school = '{schoolId}'";
  1838. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student")
  1839. .GetItemQueryIteratorSql<Imei>(queryText: imeiQueryText, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Imei") }))
  1840. {
  1841. imeis.Add(item);
  1842. }
  1843. List<Student> graduate_students = new List<Student>();
  1844. List<Class> school_classes = new List<Class>();
  1845. string queryText = "";
  1846. if (graduate == 0)
  1847. {
  1848. queryText = $"SELECT * FROM c WHERE c.code = 'Base-{schoolId}' and (c.graduate = 0 or IS_DEFINED(c.graduate) = false )";
  1849. }
  1850. else
  1851. {
  1852. queryText = $"SELECT * FROM c WHERE c.code = 'Base-{schoolId}' and c.graduate = 1 and c.year ={inyear} ";
  1853. ///查询当年的毕业班
  1854. string sql = sql = $"SELECT value c FROM c where c.graduate =1 and c.year ={inyear}"; ;
  1855. var client = _azureCosmos.GetCosmosClient();
  1856. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<Class>
  1857. (queryText: sql,
  1858. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  1859. {
  1860. school_classes.Add(item);
  1861. }
  1862. //如果已经毕业的班级不为空。
  1863. if (school_classes.IsNotEmpty())
  1864. {
  1865. 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}'"))} )";
  1866. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIteratorSql<Student>(queryText: classSql,
  1867. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  1868. {
  1869. graduate_students.Add(item);
  1870. }
  1871. }
  1872. }
  1873. //回傳用ContinuationToken
  1874. string continuationToken = string.Empty;
  1875. var container = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student");
  1876. //進行學生資料的查詢 TEAMModelOS-Student
  1877. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student")
  1878. .GetItemQueryStreamIteratorSql(
  1879. queryText: queryText,
  1880. requestOptions: new QueryRequestOptions()
  1881. { PartitionKey = new PartitionKey($"Base-{schoolId}"), MaxItemCount = -1 }))
  1882. {
  1883. continuationToken = item.ContinuationToken;
  1884. using var json = await JsonDocument.ParseAsync(item.Content);
  1885. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1886. {
  1887. 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)>();
  1888. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1889. while (accounts.MoveNext())
  1890. {
  1891. JsonElement acc = accounts.Current;
  1892. string classId = acc.GetProperty("classId").GetString();
  1893. acc.TryGetProperty("irs", out JsonElement irs);
  1894. acc.TryGetProperty("guardians", out JsonElement _guardians);
  1895. List<StudentGuardian> guardians = new List<StudentGuardian>();
  1896. if (_guardians.ValueKind.Equals(JsonValueKind.Array))
  1897. {
  1898. guardians = _guardians.Deserialize<List<StudentGuardian>>();
  1899. if (guardians.Any())
  1900. {
  1901. guardians = guardians.FindAll(x => !string.IsNullOrWhiteSpace(x.mobile));
  1902. }
  1903. }
  1904. var imeiObj = imeis.Find(x => x.stuid.Equals(acc.GetProperty("id").GetString()));
  1905. if (string.IsNullOrWhiteSpace(classId))
  1906. {
  1907. notJoinClassStuds.Add(
  1908. (
  1909. acc.GetProperty("id").GetString(),
  1910. acc.GetProperty("name").GetString(),
  1911. acc.GetProperty("picture").GetString(),
  1912. acc.GetProperty("year").GetInt32(),
  1913. acc.GetProperty("no").GetString(),
  1914. acc.TryGetProperty("periodId", out JsonElement _periodId) && _periodId.ValueKind.Equals(JsonValueKind.String) ? _periodId.GetString() : null,
  1915. $"{irs}",
  1916. imeiObj?.id,//imei
  1917. acc.TryGetProperty("gender", out JsonElement _gender) && _gender.ValueKind.Equals(JsonValueKind.String) ? _gender.GetString() : null,
  1918. acc.TryGetProperty("graduate", out JsonElement _graduate) && _graduate.ValueKind.Equals(JsonValueKind.Number) ? int.Parse($"{_graduate}") : 0,
  1919. acc.TryGetProperty("openId", out JsonElement _openId) && !string.IsNullOrWhiteSpace(_openId.GetString()) ? true : false,
  1920. guardians
  1921. )
  1922. );
  1923. }
  1924. else
  1925. {
  1926. if (dicClassStuds.ContainsKey(classId))
  1927. {
  1928. dicClassStuds[classId].Add(
  1929. (
  1930. acc.GetProperty("id").GetString(),
  1931. acc.GetProperty("name").GetString(),
  1932. acc.GetProperty("picture").GetString(),
  1933. acc.GetProperty("year").GetInt32(),
  1934. acc.GetProperty("no").GetString(), acc.TryGetProperty("periodId", out JsonElement _periodId) && _periodId.ValueKind.Equals(JsonValueKind.String) ? _periodId.GetString() : null,
  1935. $"{irs}",
  1936. imeiObj?.id,//imei
  1937. acc.TryGetProperty("gender", out JsonElement _gender) && _gender.ValueKind.Equals(JsonValueKind.String) ? _gender.GetString() : null,
  1938. acc.TryGetProperty("graduate", out JsonElement _graduate) && _graduate.ValueKind.Equals(JsonValueKind.Number) ? int.Parse($"{_graduate}") : 0,
  1939. acc.TryGetProperty("openId", out JsonElement _openId) && !string.IsNullOrWhiteSpace(_openId.GetString()) ? true : false,
  1940. guardians
  1941. )
  1942. );
  1943. }
  1944. else
  1945. {
  1946. dicClassStuds.Add(classId,
  1947. 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)>()
  1948. {
  1949. (
  1950. acc.GetProperty("id").GetString(),
  1951. acc.GetProperty("name").GetString(),
  1952. acc.GetProperty("picture").GetString(),
  1953. acc.GetProperty("year").GetInt32(),
  1954. acc.GetProperty("no").GetString(), acc.TryGetProperty("periodId",out JsonElement _periodId)&& _periodId.ValueKind.Equals(JsonValueKind.String) ? _periodId.GetString() : null,
  1955. $"{irs}" ,
  1956. imeiObj?.id,//imei
  1957. acc.TryGetProperty("gender", out JsonElement _gender) && _gender.ValueKind.Equals(JsonValueKind.String) ? _gender.GetString() : null,
  1958. acc.TryGetProperty("graduate", out JsonElement _graduate) && _graduate.ValueKind.Equals(JsonValueKind.Number) ? int.Parse($"{_graduate}"): 0,
  1959. acc.TryGetProperty("openId", out JsonElement _openId) && !string.IsNullOrWhiteSpace(_openId.GetString()) ? true : false,
  1960. guardians
  1961. )
  1962. }
  1963. );
  1964. }
  1965. }
  1966. }
  1967. }
  1968. }
  1969. //查學生所屬的教室及座號
  1970. List<object> ret = new List<object>();
  1971. //查教室的資訊,用以取得gradeId,periodId資訊。
  1972. var classInfos = await getClassInfoUseId(_azureCosmos, _dingDing, _option, schoolId, dicClassStuds.Keys.ToList());
  1973. //輪循所有教室學生的資料
  1974. foreach (var classStud in dicClassStuds)
  1975. {
  1976. string classId = null, classNo = null, className = null, gradeId = null, periodId = null;
  1977. int classYear = -1;
  1978. if (classInfos.ContainsKey(classStud.Key))
  1979. {
  1980. classId = classInfos[classStud.Key].GetProperty("id").GetString();
  1981. classNo = classInfos[classStud.Key].GetProperty("no").GetString();
  1982. className = classInfos[classStud.Key].GetProperty("name").GetString();
  1983. periodId = classInfos[classStud.Key].TryGetProperty("periodId", out JsonElement _periodId) && _periodId.ValueKind.Equals(JsonValueKind.String) ? _periodId.GetString() : null;
  1984. if (classInfos[classStud.Key].TryGetProperty("year", out JsonElement year))
  1985. {
  1986. if (year.ValueKind.Equals(JsonValueKind.Number))
  1987. {
  1988. classYear = classInfos[classStud.Key].GetProperty("year").GetInt32();
  1989. }
  1990. }
  1991. }
  1992. var tmp = classStud.Value.Select(o =>
  1993. new
  1994. {
  1995. o.id,
  1996. o.name,
  1997. o.picture,
  1998. o.year,
  1999. o.no,
  2000. classId,
  2001. classNo,
  2002. className,
  2003. gradeId,
  2004. periodId = string.IsNullOrEmpty(periodId) ? o.periodId : periodId,
  2005. classYear,
  2006. irs = o.irs,
  2007. imei = o.imei,
  2008. gender = o.gender,
  2009. graduate = o.graduate,
  2010. hasEduOpenId = o.hasEduOpenId,
  2011. guardians = o.guardians,
  2012. });
  2013. ret.AddRange(tmp);
  2014. }
  2015. //彙整沒有加入教室的學生
  2016. notJoinClassStuds.ForEach(o => ret.Add(
  2017. new
  2018. {
  2019. o.id,
  2020. o.name,
  2021. o.picture,
  2022. o.year,
  2023. o.no,
  2024. classId = (string)null,
  2025. classNo = (string)null,
  2026. className = (string)null,
  2027. gradeId = (string)null,
  2028. o.periodId,
  2029. classYear = -1,
  2030. irs = o.irs,
  2031. imei = o.imei,
  2032. gender = o.gender,
  2033. hasEduOpenId = o.hasEduOpenId,
  2034. guardians = o.guardians,
  2035. }));
  2036. graduate_students.ForEach(o =>
  2037. {
  2038. var imeiObj = imeis.Find(x => x.stuid.Equals(o.id));
  2039. Class stuClass = school_classes.Find(x => x.id.Equals(o.classId));
  2040. ret.Add(
  2041. new
  2042. {
  2043. o.id,
  2044. o.name,
  2045. o.picture,
  2046. o.year,
  2047. o.no,
  2048. classId = stuClass?.id,
  2049. classNo = stuClass?.no,
  2050. className = stuClass?.name,
  2051. gradeId = stuClass?.gradeId,
  2052. o.periodId,
  2053. classYear = stuClass?.year,
  2054. irs = o.irs,
  2055. imei = imeiObj?.id,
  2056. gender = o.gender,
  2057. hasEduOpenId = (!string.IsNullOrWhiteSpace(o.openId)) ? true : false,
  2058. guardians = o.guardians,
  2059. });
  2060. });
  2061. return ret;
  2062. }
  2063. catch (Exception ex)
  2064. {
  2065. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getStudents()\n{ex.Message}\n{ex.StackTrace},", GroupNames.醍摩豆服務運維群組);
  2066. }
  2067. return null;
  2068. }
  2069. /// <summary>
  2070. /// 取得該校所有教室內的名單
  2071. /// </summary>
  2072. /// <param name="schoolId"></param>
  2073. /// <returns></returns>
  2074. public async Task<Dictionary<string, JsonElement>> getClassStudent(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, string classId = null)
  2075. {
  2076. try
  2077. {
  2078. string queryText = $"SELECT VALUE FROM c WHERE c.";
  2079. //if (!string.IsNullOrWhiteSpace(classId)) queryText += $" AND c.id = '{classId}'";
  2080. Dictionary<string, JsonElement> listStudent = new Dictionary<string, JsonElement>();
  2081. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
  2082. .GetItemQueryStreamIteratorSql(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  2083. {
  2084. using var json = await JsonDocument.ParseAsync(item.Content);
  2085. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2086. {
  2087. JsonElement.ArrayEnumerator accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  2088. while (accounts.MoveNext())
  2089. {
  2090. JsonElement account = accounts.Current;
  2091. string cId = account.GetProperty("id").GetString();
  2092. var students = account.GetProperty("students").Clone();
  2093. listStudent.Add(cId, students);
  2094. }
  2095. }
  2096. }
  2097. return listStudent;
  2098. }
  2099. catch (Exception ex)
  2100. {
  2101. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassStudentAsync()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2102. }
  2103. return null;
  2104. }
  2105. /// <summary>
  2106. /// 刪除學生,非透過批量刪除方法。
  2107. /// </summary>
  2108. /// <param name="schoolId"></param>
  2109. /// <param name="students"></param>
  2110. /// <returns></returns>
  2111. public static async Task<List<string>> deleteStudents(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, JsonElement.ArrayEnumerator students)
  2112. {
  2113. List<string> sucIds = new List<string>();
  2114. try
  2115. {
  2116. var exceptions = new List<Exception>();
  2117. List<GroupList> scGroupLists = new List<GroupList>();
  2118. List<GroupList> teGroupLists = new List<GroupList>();
  2119. var container = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student");
  2120. while (students.MoveNext())
  2121. {
  2122. string id = string.Empty;
  2123. try
  2124. {
  2125. JsonElement student = students.Current;
  2126. id = student.GetProperty("id").GetString();
  2127. var ret = await container.DeleteItemStreamAsync(id, new PartitionKey($"Base-{schoolId}"));
  2128. await upsertImei(id, null, schoolId, "delete", container);
  2129. if (ret.StatusCode == HttpStatusCode.NoContent) sucIds.Add(id);
  2130. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<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}") }))
  2131. {
  2132. scGroupLists.Add(item);
  2133. }
  2134. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<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") }))
  2135. {
  2136. teGroupLists.Add(item);
  2137. }
  2138. if (scGroupLists.Count > 0)
  2139. {
  2140. foreach (GroupList stuList in scGroupLists)
  2141. {
  2142. for (int j = 0; j < stuList.members.Count; j++)
  2143. {
  2144. if (id.Equals(stuList.members[j].id) && stuList.members[j].code.Equals(schoolId))
  2145. {
  2146. stuList.members.RemoveAt(j);
  2147. stuList.scount -= 1;
  2148. break;
  2149. }
  2150. }
  2151. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(stuList, stuList.id, new PartitionKey(stuList.code));
  2152. }
  2153. }
  2154. if (teGroupLists.Count > 0)
  2155. {
  2156. foreach (GroupList stuList in teGroupLists)
  2157. {
  2158. for (int j = 0; j < stuList.members.Count; j++)
  2159. {
  2160. if (id.Equals(stuList.members[j].id) && stuList.members[j].code.Equals(schoolId))
  2161. {
  2162. stuList.members.RemoveAt(j);
  2163. stuList.scount -= 1;
  2164. break;
  2165. }
  2166. }
  2167. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(stuList, stuList.id, new PartitionKey(stuList.code));
  2168. }
  2169. }
  2170. }
  2171. catch (CosmosException ex)
  2172. {
  2173. exceptions.Add(ex);
  2174. }
  2175. catch (Exception ex)
  2176. {
  2177. exceptions.Add(ex);
  2178. }
  2179. }
  2180. if (exceptions.Count == 0) return sucIds;
  2181. else if (exceptions.Count > 1) throw new AggregateException(exceptions);
  2182. else if (exceptions.Count == 1) throw exceptions.Single();
  2183. }
  2184. catch (CosmosException ex)
  2185. {
  2186. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/deleteStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2187. }
  2188. catch (Exception ex)
  2189. {
  2190. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/deleteStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2191. }
  2192. return sucIds;
  2193. }
  2194. /// <summary>
  2195. /// 將學生基本資料內的classId、no、groupId及groupName清為null。
  2196. /// </summary>
  2197. /// <param name="schoolId"></param>
  2198. /// <param name="students">["id1","id2",...]</param>
  2199. /// <returns></returns>
  2200. 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)
  2201. {
  2202. //紀錄輸入的學生
  2203. List<string> impStuds = new List<string>();
  2204. //紀錄更新成功的學生
  2205. List<string> sucStuds = new List<string>();
  2206. //記錄沒查到的學生
  2207. List<string> nonexistentIds = new List<string>();
  2208. //紀錄更新出錯的學生
  2209. List<string> errorIds = new List<string>();
  2210. //整理輸入的學生資訊
  2211. while (students.MoveNext())
  2212. {
  2213. JsonElement student = students.Current;
  2214. impStuds.Add(student.GetString());
  2215. }
  2216. if (impStuds.Count == 0) return (null, null, null);
  2217. string queryText = $"SELECT VALUE c FROM c WHERE c.id IN ({string.Join(",", impStuds.Select(o => $"'{o}'"))})";
  2218. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student")
  2219. .GetItemQueryStreamIteratorSql(
  2220. queryText: queryText,
  2221. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  2222. {
  2223. using var json = await JsonDocument.ParseAsync(item.Content);
  2224. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2225. {
  2226. JsonElement.ArrayEnumerator docs = json.RootElement.GetProperty("Documents").EnumerateArray();
  2227. while (docs.MoveNext())
  2228. {
  2229. JsonElement doc = docs.Current;
  2230. doc.TryGetProperty("id", out var tmpId);
  2231. var id = tmpId.GetString();
  2232. using var stream = new MemoryStream();
  2233. using var writer = new Utf8JsonWriter(stream);
  2234. writer.WriteStartObject();
  2235. foreach (var element in doc.EnumerateObject())
  2236. {
  2237. //將教室相關欄位清空
  2238. switch (true)
  2239. {
  2240. case bool _ when element.Name.Equals("classId", StringComparison.Ordinal):
  2241. writer.WriteNull("classId");
  2242. break;
  2243. case bool _ when element.Name.Equals("no", StringComparison.Ordinal):
  2244. writer.WriteNull("no");
  2245. break;
  2246. case bool _ when element.Name.Equals("groupId", StringComparison.Ordinal):
  2247. writer.WriteNull("groupId");
  2248. break;
  2249. case bool _ when element.Name.Equals("groupName", StringComparison.Ordinal):
  2250. writer.WriteNull("groupName");
  2251. break;
  2252. case bool _ when element.Name.Equals("irs", StringComparison.Ordinal):
  2253. writer.WriteNull("irs");
  2254. break;
  2255. case bool _ when element.Name.StartsWith("_", StringComparison.Ordinal):
  2256. break;
  2257. default:
  2258. element.WriteTo(writer);
  2259. break;
  2260. }
  2261. }
  2262. writer.WriteEndObject();
  2263. writer.Flush();
  2264. var ret = await _azureCosmos
  2265. .GetCosmosClient()
  2266. .GetContainer(Constant.TEAMModelOS, "Student")
  2267. .ReplaceItemStreamAsync(stream, id, new PartitionKey($"Base-{schoolId}"));
  2268. if (ret.StatusCode == HttpStatusCode.OK)
  2269. {
  2270. sucStuds.Add(id);
  2271. }
  2272. else
  2273. {
  2274. impStuds.Remove(id);
  2275. errorIds.Add(id);
  2276. await _dingDing.SendBotMsg(
  2277. $"IES5,{_option.Location},StudentController/removeStudentClassInfo(),CosmosDB response:{ret.StatusCode}\nBase-{schoolId},id:{id}",
  2278. GroupNames.醍摩豆服務運維群組);
  2279. }
  2280. }
  2281. }
  2282. }
  2283. //將impStuds內的資料移除sucStuds及errorIds,所得的結果就是不存在於資料庫的id。
  2284. sucStuds.ForEach(o => impStuds.Remove(o));
  2285. errorIds.ForEach(o => impStuds.Remove(o));
  2286. return (sucStuds, impStuds, errorIds);
  2287. }
  2288. /// <summary>
  2289. /// 取得教室資訊,使用classId進行查詢。
  2290. /// </summary>
  2291. /// <returns></returns>
  2292. private static async Task<Dictionary<string, JsonElement>> getClassInfoUseId(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, List<string> classIds)
  2293. {
  2294. try
  2295. {
  2296. if (!(classIds == null || classIds.Count == 0))
  2297. {
  2298. string queryText = $"SELECT * FROM c WHERE c.code = 'Class-{schoolId}' AND c.id IN ({string.Join(",", classIds.Select(o => $"'{o}'"))})";
  2299. Dictionary<string, JsonElement> dicClassInfo = new Dictionary<string, JsonElement>();
  2300. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
  2301. .GetItemQueryStreamIteratorSql(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  2302. {
  2303. using var json = await JsonDocument.ParseAsync(item.Content);
  2304. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2305. {
  2306. var classInfos = json.RootElement.GetProperty("Documents").EnumerateArray();
  2307. while (classInfos.MoveNext())
  2308. {
  2309. JsonElement account = classInfos.Current;
  2310. string id = account.GetProperty("id").GetString();
  2311. dicClassInfo.Add(id, account.Clone());
  2312. }
  2313. }
  2314. }
  2315. return dicClassInfo;
  2316. }
  2317. else return null;
  2318. }
  2319. catch (CosmosException ex)
  2320. {
  2321. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassInfoUseId()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2322. }
  2323. catch (Exception ex)
  2324. {
  2325. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassInfoUseId()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2326. }
  2327. return null;
  2328. }
  2329. /// <summary>
  2330. /// 取得教室資訊,使用classNo進行查詢。
  2331. /// </summary>
  2332. /// <returns></returns>
  2333. 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)
  2334. {
  2335. try
  2336. {
  2337. Dictionary<string, Class> dicClassInfo = new Dictionary<string, Class>();
  2338. if (!(classNos == null || classNos.Count == 0))
  2339. {
  2340. foreach (var key in classNos.Keys)
  2341. {
  2342. 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}' ";
  2343. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
  2344. .GetItemQueryIteratorSql<Class>(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  2345. {
  2346. dicClassInfo[item.id] = item;
  2347. item.name = classNos[key].className;
  2348. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<Class>(item, item.id, new PartitionKey(item.code));
  2349. }
  2350. }
  2351. return dicClassInfo;
  2352. }
  2353. else return null;
  2354. }
  2355. catch (CosmosException ex)
  2356. {
  2357. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassInfoUseId()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2358. }
  2359. catch (Exception ex)
  2360. {
  2361. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassInfoUseId()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2362. }
  2363. return null;
  2364. }
  2365. /// <summary>
  2366. /// 批量更新學生資訊,目前支持更新姓名、密碼、座號、性別及教室id,匯入時ClassId為必填。
  2367. /// </summary>
  2368. /// <param name="schoolId"></param>
  2369. /// <param name="students"></param>
  2370. /// <returns></returns>
  2371. public static async Task<(List<object> studs, Dictionary<string, List<string>> classDuplNos, List<string> nonexistentIds, List<string> errorIds,
  2372. Dictionary<string, List<string>> errorNos, List<string> errorClassId)>
  2373. updateStudents(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, JsonElement.ArrayEnumerator students)
  2374. {
  2375. try
  2376. {
  2377. //整理輸入的資料->檢查輸入資料有沒有重複座號->取得欲加入的教室資訊->查詢學生並將資料更新並寫入
  2378. //Key:id Value:學生基本資訊
  2379. var studentInfos
  2380. = new Dictionary<string, (string salt, string pw, string name, int year, string picture, string gender, string mail, string mobile,
  2381. string classId, string no, string periodId, string irs, string imei, List<StudentGuardian> guardians)>();
  2382. //用於進行座號是否重複查詢時使用
  2383. var classStuds
  2384. = new Dictionary<string, List<(string id, string salt, string pw, string name, int year, string picture, string gender, string mail, string mobile,
  2385. string classId, string no, string periodId)>>();
  2386. //紀錄教室"輸入"的學生座號是否有重複
  2387. var impClassDuplNo = new Dictionary<string, List<string>>();
  2388. //紀錄不存在的學生id
  2389. var nonexistentIds = new List<string>();
  2390. //紀錄跟現有雲端學生座號重複的
  2391. var errorNos = new Dictionary<string, List<string>>();
  2392. //紀錄處理錯誤的id,cosmosdb寫入時錯誤等...
  2393. var errorIds = new List<string>();
  2394. //紀錄沒找到的classId
  2395. var errorClassId = new List<string>();
  2396. //紀錄輸出結果
  2397. var retStuds = new List<object>();
  2398. //整理輸入資料
  2399. while (students.MoveNext())
  2400. {
  2401. JsonElement student = students.Current;
  2402. if (student.TryGetProperty("id", out var id))
  2403. {
  2404. //確認是否有id欄位,並且確認是否有給pw欄位,若無給或是null empty等,則使用id當密碼。
  2405. if (!string.IsNullOrWhiteSpace(id.GetString()))
  2406. {
  2407. string salt = null,
  2408. pw = null,
  2409. name = null,
  2410. gender = null,
  2411. mail = null,
  2412. mobile = null,
  2413. classId = null,
  2414. periodId = null,
  2415. irs = null,
  2416. imei = null,
  2417. no = null;
  2418. List<StudentGuardian> guardians = null;
  2419. int year = 0;
  2420. //有給pw欄位才進行處理
  2421. if (student.TryGetProperty("pw", out var tmpPw) && !"******".Equals($"{tmpPw}"))
  2422. {
  2423. var response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemStreamAsync(id.GetString(), new PartitionKey($"Base-{schoolId}"));
  2424. if (response.StatusCode == HttpStatusCode.OK)
  2425. {
  2426. var rjson = await JsonDocument.ParseAsync(response.Content);
  2427. rjson.RootElement.TryGetProperty("salt", out JsonElement _salt);
  2428. salt = $"{_salt}";
  2429. }
  2430. if (string.IsNullOrWhiteSpace(salt))
  2431. {
  2432. salt = Utils.CreatSaltString(8);
  2433. }
  2434. pw = !string.IsNullOrWhiteSpace(tmpPw.GetString())
  2435. ? Utils.HashedPassword(tmpPw.GetString(), salt)
  2436. : Utils.HashedPassword(id.GetString(), salt);
  2437. }
  2438. if (student.TryGetProperty("name", out var tmpName)) name = tmpName.GetString();
  2439. if (student.TryGetProperty("gender", out var tmpGender)) gender = tmpGender.GetString();
  2440. if (student.TryGetProperty("mail", out var tmpMail)) mail = tmpMail.GetString();
  2441. if (student.TryGetProperty("mobile", out var tmpMobile)) mobile = tmpMobile.GetString();
  2442. if (student.TryGetProperty("year", out var tmpYear)) year = tmpYear.GetInt32();
  2443. if (student.TryGetProperty("periodId", out var tmpperiodId)) periodId = tmpperiodId.GetString();
  2444. if (student.TryGetProperty("irs", out var tmpIrs)) irs = tmpIrs.GetString();
  2445. if (student.TryGetProperty("imei", out var tmpImei)) imei = tmpImei.GetString();
  2446. if (student.TryGetProperty("classId", out var tmpclassId)) classId = tmpclassId.GetString();
  2447. else
  2448. {
  2449. errorClassId.Add(id.GetString());
  2450. continue;
  2451. }
  2452. if (student.TryGetProperty("guardians", out var _guardians) && _guardians.ValueKind.Equals(JsonValueKind.Array))
  2453. {
  2454. guardians = _guardians.Deserialize<List<StudentGuardian>>();
  2455. }
  2456. //如果有給該欄位,且是給空的,代表要清空
  2457. if (student.TryGetProperty("no", out var tmpNo)) no = tmpNo.GetString();
  2458. if (!studentInfos.ContainsKey(id.GetString()))
  2459. {
  2460. //如果有給classId且是給空的,則也將no設為空,後續才能將no欄位清空。
  2461. if (classId != null && classId.Length == 0) no = string.Empty;
  2462. //classId => 沒給欄位(null) 有給欄位("") 但更新一定得給教室?
  2463. if (classId == null)
  2464. {
  2465. classId = "";
  2466. }
  2467. if (classStuds.ContainsKey(classId))
  2468. {
  2469. classStuds[classId].Add((id.GetString(), salt, pw, name, year, null, gender, null, null, classId, no, periodId));
  2470. }
  2471. else
  2472. {
  2473. classStuds.Add(
  2474. classId,
  2475. 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)>()
  2476. { (id.GetString(), salt, pw, name, year, null, gender, null, null, classId, no,periodId) });
  2477. }
  2478. //picture,mail,mobile暫不支持批量更新
  2479. studentInfos.Add(id.GetString(), (salt, pw, name, year, null, gender, null, null, classId, no, periodId, irs, imei, guardians));
  2480. //先將id加進去後面再做刪除動作
  2481. nonexistentIds.Add(id.GetString());
  2482. }
  2483. }
  2484. }
  2485. }
  2486. //檢查所有輸入的班級資料內,學生座號是否有重複。
  2487. for (int ii = 0; ii <= classStuds.Values.Count - 1; ii++)
  2488. {
  2489. var duplicateNo = classStuds.ElementAt(ii).Value.GroupBy(o => o.no).Where(o => o.Count() > 1).Select(o => o.Key).ToList();
  2490. duplicateNo.Remove("");
  2491. duplicateNo.Remove(null);
  2492. var wrongStuds = classStuds.ElementAt(ii).Value.Where(o => duplicateNo.Contains(o.no)).Select(o => o).ToList();
  2493. impClassDuplNo.Add(classStuds.ElementAt(ii).Key, wrongStuds.Select(o => o.id).ToList());
  2494. wrongStuds.ForEach(o => { classStuds.ElementAt(ii).Value.Remove(o); nonexistentIds.Remove(o.id); });
  2495. classStuds[classStuds.ElementAt(ii).Key] = classStuds.ElementAt(ii).Value;
  2496. }
  2497. //查詢欲加入的教室資訊。
  2498. var classInfo = await getClassInfoUseId(_azureCosmos, _dingDing, _option, schoolId, classStuds.Keys.ToList());
  2499. //準備查詢db資料
  2500. Container cosmosContainer = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student");
  2501. //查要移除教室或是沒加入教室的學生
  2502. foreach (var item in classStuds)
  2503. {
  2504. //如果沒有任何學生要更新,則跳過該間教室。
  2505. if (item.Value.Count == 0) continue;
  2506. string classId = null, className = null, classNo = null, gradeId = null, periodId = null;
  2507. //如果教室不存在的話(填錯教室之類的狀況),則記錄教室的id及學生id。
  2508. if (classInfo.ContainsKey(item.Key))
  2509. {
  2510. classId = item.Key;
  2511. className = classInfo[item.Key].GetProperty("name").GetString();
  2512. classNo = classInfo[item.Key].GetProperty("no").GetString();
  2513. //gradeId = classInfo[item.Key].GetProperty("gradeId").GetString(); 此欄位已不使用
  2514. periodId = classInfo[item.Key].GetProperty("periodId").GetString();
  2515. }
  2516. else if (item.Key.Length == 0)
  2517. {
  2518. }
  2519. else
  2520. {
  2521. //沒查到有該間教室的資訊,故將該間教室的ID及學生資料清單記起來,並且跳過不處理該資料。
  2522. errorClassId.Add(item.Key);
  2523. item.Value.ForEach(o => nonexistentIds.Remove(o.id));
  2524. continue;
  2525. }
  2526. //檢查座號是否有重複
  2527. //若只是改基本資料,該處還是會查到相同的座號。
  2528. var sutdNos = item.Value.Select(o => o.no).ToList();
  2529. var existNos = await checkStudNo(_azureCosmos, _dingDing, _option, schoolId, item.Key, sutdNos);
  2530. //更新並寫入學生資料
  2531. if (item.Value.Count != 0)
  2532. {
  2533. //查學生的基本資料(該間教室全部的學生)
  2534. string queryText = $"SELECT * FROM c WHERE c.id IN ({string.Join(",", item.Value.Select(o => $"'{o.id}'"))})";
  2535. List<JsonElement> listStudent = new List<JsonElement>();
  2536. await foreach (var responseItem in cosmosContainer
  2537. .GetItemQueryStreamIteratorSql(
  2538. queryText: queryText,
  2539. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  2540. {
  2541. using var json = await JsonDocument.ParseAsync(responseItem.Content);
  2542. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2543. {
  2544. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  2545. while (accounts.MoveNext())
  2546. {
  2547. JsonElement account = accounts.Current;
  2548. string id = $"{account.GetProperty("id")}";
  2549. nonexistentIds.Remove(id);
  2550. //舊的座號,基本上不會重複,但可能會是空的
  2551. string no = $"{account.GetProperty("no")}";
  2552. account.TryGetProperty("irs", out JsonElement irsjson);
  2553. string irs = $"{irsjson}";
  2554. //用來記錄最後更改完的資料
  2555. (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
  2556. = (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,
  2557. studentInfos[id].irs, studentInfos[id].imei, studentInfos[id].guardians);
  2558. bool isUpPwDone = false;
  2559. bool isWrong = false;
  2560. //開始組Json
  2561. using var memoryStream = new MemoryStream();
  2562. using var writer = new Utf8JsonWriter(memoryStream);
  2563. writer.WriteStartObject();
  2564. foreach (var element in account.EnumerateObject())
  2565. {
  2566. if (isWrong) break;
  2567. switch (true)
  2568. {
  2569. case bool _ when element.Name.Equals("name", StringComparison.Ordinal):
  2570. if (string.IsNullOrWhiteSpace(studentInfos[id].name))
  2571. {
  2572. element.WriteTo(writer);
  2573. tmpData.name = element.Value.GetString();
  2574. }
  2575. else
  2576. {
  2577. writer.WriteString("name", studentInfos[id].name);
  2578. }
  2579. break;
  2580. case bool _ when element.Name.Equals("pw", StringComparison.Ordinal):
  2581. case bool _ when element.Name.Equals("salt", StringComparison.Ordinal):
  2582. if (!isUpPwDone && !string.IsNullOrWhiteSpace(studentInfos[id].salt) && !string.IsNullOrWhiteSpace(studentInfos[id].pw))
  2583. {
  2584. writer.WriteString("salt", studentInfos[id].salt);
  2585. writer.WriteString("pw", studentInfos[id].pw);
  2586. isUpPwDone = true;
  2587. }
  2588. break;
  2589. case bool _ when element.Name.Equals("periodId", StringComparison.Ordinal):
  2590. if (string.IsNullOrWhiteSpace(studentInfos[id].periodId))
  2591. {
  2592. element.WriteTo(writer);
  2593. tmpData.periodId = element.Value.GetString();
  2594. }
  2595. else
  2596. {
  2597. writer.WriteString("periodId", studentInfos[id].periodId);
  2598. }
  2599. break;
  2600. case bool _ when element.Name.Equals("gender", StringComparison.Ordinal):
  2601. if (string.IsNullOrWhiteSpace(studentInfos[id].gender))
  2602. {
  2603. element.WriteTo(writer);
  2604. tmpData.gender = element.Value.GetString();
  2605. }
  2606. else
  2607. {
  2608. writer.WriteString("gender", studentInfos[id].gender);
  2609. }
  2610. break;
  2611. case bool _ when element.Name.Equals("year", StringComparison.Ordinal):
  2612. if (studentInfos[id].year == 0)
  2613. {
  2614. element.WriteTo(writer);
  2615. tmpData.year = element.Value.GetInt32();
  2616. }
  2617. else
  2618. {
  2619. writer.WriteNumber("year", studentInfos[id].year);
  2620. }
  2621. break;
  2622. case bool _ when element.Name.Equals("classId", StringComparison.Ordinal):
  2623. if (studentInfos[id].classId != null && studentInfos[id].classId.Length == 0)
  2624. {
  2625. writer.WriteNull("classId");
  2626. writer.WriteNull("groupId");
  2627. writer.WriteNull("groupName");
  2628. tmpData.classId = null;
  2629. }
  2630. else if (string.IsNullOrWhiteSpace(studentInfos[id].classId))
  2631. {
  2632. element.WriteTo(writer);
  2633. tmpData.classId = element.Value.GetString();
  2634. }
  2635. else
  2636. {
  2637. writer.WriteString("classId", studentInfos[id].classId);
  2638. }
  2639. break;
  2640. case bool _ when element.Name.Equals("no", StringComparison.Ordinal):
  2641. //移除座號的話會給空的
  2642. if (studentInfos[id].no != null && studentInfos[id].no.Length == 0)
  2643. {
  2644. writer.WriteNull("no");
  2645. tmpData.no = null;
  2646. }
  2647. else if (string.IsNullOrWhiteSpace(studentInfos[id].no))
  2648. {
  2649. element.WriteTo(writer);
  2650. tmpData.no = element.Value.GetString();
  2651. //#2769 C343 学生管理--导入学生名单,IRS编号默认与座号一致
  2652. tmpData.irs = element.Value.GetString();
  2653. }
  2654. else
  2655. {
  2656. //如果要更新的座號,跟已存在的座號相同,則不進行更新。
  2657. //沒有設定過舊no,或舊座號與新座號不同,則要進行重複座號的檢查。 舊no=null or 舊no!=新no
  2658. //if (string.IsNullOrWhiteSpace(no) || (!string.IsNullOrWhiteSpace(no) && !no.Equals(studentInfos[id].no)))
  2659. //{
  2660. // //如果有檢查到新座號和舊座號重複
  2661. // if (existNos.Any(o => o.Item2.Contains(studentInfos[id].no))) //.Contains(studentInfos[id].no))
  2662. // {
  2663. // if (errorNos.ContainsKey(id))
  2664. // {
  2665. // errorNos[id].Add(studentInfos[id].no);
  2666. // }
  2667. // else
  2668. // {
  2669. // errorNos.Add(id, new List<string>() { studentInfos[id].no });
  2670. // }
  2671. // isWrong = true;
  2672. // break;
  2673. // }
  2674. //}
  2675. writer.WriteString("no", studentInfos[id].no);
  2676. //#2769 C343 学生管理--导入学生名单,IRS编号默认与座号一致
  2677. writer.WriteString("irs", studentInfos[id].no);
  2678. }
  2679. break;
  2680. //case bool _ when element.Name.Equals("irs", StringComparison.Ordinal):
  2681. // //移除座號的話會給空的
  2682. // if (studentInfos[id].irs != null && studentInfos[id].irs.Length == 0)
  2683. // {
  2684. // writer.WriteNull("irs");
  2685. // tmpData.irs = null;
  2686. // }
  2687. // else if (string.IsNullOrWhiteSpace(studentInfos[id].irs))
  2688. // {
  2689. // element.WriteTo(writer);
  2690. // tmpData.irs = element.Value.GetString();
  2691. // }
  2692. // else
  2693. // {
  2694. // writer.WriteString("irs", studentInfos[id].irs);
  2695. // }
  2696. // break;
  2697. case bool _ when element.Name.StartsWith("_", StringComparison.Ordinal):
  2698. break;
  2699. default:
  2700. element.WriteTo(writer);
  2701. break;
  2702. }
  2703. }
  2704. var stu = account.Deserialize<Student>();
  2705. if (stu.guardians.IsNotEmpty() && studentInfos[id].guardians != null)
  2706. {
  2707. var mobiles = stu.guardians.Select(m => m.mobile);
  2708. var except = mobiles.Except(studentInfos[id].guardians.Select(x => x.mobile));
  2709. if (except.Any())
  2710. {
  2711. //清除移除的监护人
  2712. List<Guardian> guardians = new List<Guardian>();
  2713. string sql = $"select distinct value (c) from c where c.mobile in ({string.Join(",", except.Select(z => $"'{z}'"))} )";
  2714. await foreach (var guard in cosmosContainer.GetItemQueryIteratorSql<Guardian>(queryText: sql,
  2715. requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base-Guardian") }))
  2716. {
  2717. guard.students.RemoveAll(s => s.id.Equals(id) && s.code.Equals(schoolId));
  2718. guardians.Add(guard);
  2719. }
  2720. guardians.ForEach(async x =>
  2721. {
  2722. if (x.students.IsNotEmpty())
  2723. {
  2724. try { await cosmosContainer.ReplaceItemAsync(x, x.id, new PartitionKey(x.code)); } catch { }
  2725. }
  2726. else
  2727. {
  2728. try
  2729. {
  2730. await cosmosContainer.DeleteItemStreamAsync(x.id, new PartitionKey(x.code));
  2731. }
  2732. catch
  2733. {
  2734. }
  2735. }
  2736. });
  2737. }
  2738. }
  2739. if (studentInfos[id].guardians.IsNotEmpty())
  2740. {
  2741. foreach (var gtudentGuardian in studentInfos[id].guardians)
  2742. {
  2743. List<Guardian> guardians = new List<Guardian>();
  2744. string sql = $"select distinct value (c) from c where c.mobile='{gtudentGuardian.mobile}' ";
  2745. await foreach (var guard in cosmosContainer.GetItemQueryIteratorSql<Guardian>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base-Guardian") }))
  2746. {
  2747. guardians.Add(guard);
  2748. }
  2749. if (guardians.Any())
  2750. {
  2751. guardians.ForEach(async x =>
  2752. {
  2753. GuardianStudent guardianStudent = x.students.Find(s => s.id.Equals(id) && s.code.Equals(schoolId));
  2754. if (guardianStudent == null)
  2755. {
  2756. x.students.Add(new GuardianStudent { relation = gtudentGuardian.relation, type = 2, id = id, code = schoolId, name = studentInfos[id].name });
  2757. }
  2758. try { await cosmosContainer.ReplaceItemAsync(x, x.id, new PartitionKey(x.code)); } catch { }
  2759. });
  2760. }
  2761. else
  2762. {
  2763. Guardian guardian = new Guardian
  2764. {
  2765. id = Guid.NewGuid().ToString(),
  2766. code = "Base-Guardian",
  2767. pk = "Guardian",
  2768. mobile = gtudentGuardian.mobile,
  2769. name = gtudentGuardian.name,
  2770. students = new List<GuardianStudent> { new GuardianStudent { relation = gtudentGuardian.relation, type = 2, id = id, code = schoolId, name = studentInfos[id].name } }
  2771. };
  2772. try { await cosmosContainer.CreateItemAsync(guardian, new PartitionKey(guardian.code)); } catch { }
  2773. }
  2774. }
  2775. writer.WriteStartArray("guardians");
  2776. foreach (var guardian in studentInfos[id].guardians)
  2777. {
  2778. writer.WriteStartObject();
  2779. writer.WriteString("relation", guardian.relation);
  2780. writer.WriteString("name", guardian.name);
  2781. writer.WriteString("mobile", guardian.mobile);
  2782. writer.WriteString("mail", guardian.mail);
  2783. writer.WriteString("picture", guardian.picture);
  2784. writer.WriteString("tmdid", guardian.tmdid);
  2785. writer.WriteEndObject();
  2786. }
  2787. writer.WriteEndArray();
  2788. }
  2789. else
  2790. {
  2791. writer.WriteStartArray("guardians");
  2792. //writer.WriteStartObject();
  2793. //writer.WriteEndObject();
  2794. writer.WriteEndArray();
  2795. }
  2796. //如果有錯誤,如座號重覆等,就會跳過該次更新。
  2797. if (isWrong)
  2798. {
  2799. await writer.DisposeAsync();
  2800. continue;
  2801. }
  2802. //#2769 C343 学生管理--导入学生名单,IRS编号默认与座号一致
  2803. //if (!account.TryGetProperty("irs", out JsonElement _irs) || _irs.ValueKind.Equals(JsonValueKind.Undefined))
  2804. //{
  2805. // writer.WriteString("irs", studentInfos[id].irs);
  2806. //}
  2807. writer.WriteString("irs", studentInfos[id].no);
  2808. //若密碼和鹽沒有更新,就把舊的資料寫回去
  2809. if (!isUpPwDone)
  2810. {
  2811. writer.WriteString("salt", account.GetProperty("salt").GetString());
  2812. writer.WriteString("pw", account.GetProperty("pw").GetString());
  2813. }
  2814. writer.WriteEndObject();
  2815. writer.Flush();
  2816. //编辑是是否要明确清除电子学生证。
  2817. await upsertImei(id, studentInfos[id].imei, schoolId, "clean", _azureCosmos
  2818. .GetCosmosClient()
  2819. .GetContainer(Constant.TEAMModelOS, "Student"));
  2820. try
  2821. {
  2822. var ret = await cosmosContainer.ReplaceItemStreamAsync(memoryStream, id, new PartitionKey($"Base-{schoolId}"));
  2823. //將更新完的id從字典內移除,保留沒查到的。
  2824. if (ret.StatusCode ==HttpStatusCode.OK)
  2825. {
  2826. nonexistentIds.Remove(id);
  2827. 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 });
  2828. }
  2829. else errorIds.Add(id);
  2830. }
  2831. catch (CosmosException ex)
  2832. {
  2833. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/updateStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2834. errorIds.Add(id);
  2835. }
  2836. catch (Exception ex)
  2837. {
  2838. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/updateStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2839. errorIds.Add(id);
  2840. }
  2841. }
  2842. }
  2843. //將輸入不存在的資料移除。
  2844. // nonexistentIds.ForEach(o => studentInfos.Remove(o));
  2845. }
  2846. }
  2847. }
  2848. errorClassId.ForEach(o => impClassDuplNo.Remove(o));
  2849. return (retStuds, impClassDuplNo.Where(o => o.Value.Count != 0).ToDictionary(o => o.Key, o => o.Value), nonexistentIds, errorIds, errorNos, errorClassId);
  2850. }
  2851. catch (CosmosException ex)
  2852. {
  2853. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/updateStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2854. }
  2855. catch (Exception ex)
  2856. {
  2857. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/updateStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2858. }
  2859. return (null, null, null, null, null, null);
  2860. }
  2861. /// <summary>
  2862. /// 創建學生帳號,目前SDK4.0預覽版還不支援批量創建(TransactionalBatch),待SDK正式發行時在優化此代碼。
  2863. /// </summary>
  2864. /// <param name="userStudents"></param>
  2865. /// <returns>已存在的ID</returns>
  2866. private async Task<(bool isSuc, List<string> existId)> createStudents(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, List<Student> userStudents)
  2867. {
  2868. var existId = new List<string>();
  2869. var exceptions = new List<Exception>();
  2870. try
  2871. {
  2872. var container = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student");
  2873. Parallel.ForEach(userStudents, async item =>
  2874. {
  2875. try
  2876. {
  2877. await container.CreateItemAsync(item);
  2878. }
  2879. catch (CosmosException ex)
  2880. {
  2881. if (ex.StatusCode == HttpStatusCode.Conflict) existId.Add(item.id);
  2882. else exceptions.Add(ex);
  2883. }
  2884. catch (Exception ex)
  2885. {
  2886. exceptions.Add(ex);
  2887. }
  2888. });
  2889. if (exceptions.Count == 0) return (true, existId);
  2890. else if (exceptions.Count > 1) throw new AggregateException(exceptions);
  2891. else if (exceptions.Count == 1) throw exceptions.Single();
  2892. }
  2893. catch (AggregateException ex)
  2894. {
  2895. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2896. }
  2897. catch (Exception ex)
  2898. {
  2899. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2900. }
  2901. return (false, existId);
  2902. }
  2903. /// <summary>
  2904. /// 取得該教室的學生座號,若有給座號LIST,則座號存在才會被查到;反之,若沒給則會將該間教室所有座號抓出來。
  2905. /// </summary>
  2906. /// <param name="schoolId"></param>
  2907. /// <param name="classId"></param>
  2908. /// <param name="nos"></param>
  2909. /// <returns></returns>
  2910. public static async Task<List<(string id, string no)>> checkStudNo(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, string classId, List<string> nos = null)
  2911. {
  2912. List<(string id, string no)> ret = new List<(string id, string no)>();
  2913. string queryText = $"SELECT c.id, c.no FROM c WHERE c.classId = '{classId}' AND c.code = 'Base-{schoolId}'";
  2914. if (nos != null) queryText += $"AND c.no IN ({string.Join(",", nos.Select(o => $"'{o}'"))})";
  2915. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student")
  2916. .GetItemQueryStreamIteratorSql(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  2917. {
  2918. using var json = await JsonDocument.ParseAsync(item.Content);
  2919. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2920. {
  2921. var classInfos = json.RootElement.GetProperty("Documents").EnumerateArray();
  2922. while (classInfos.MoveNext())
  2923. {
  2924. JsonElement account = classInfos.Current;
  2925. string id = account.GetProperty("id").GetString();
  2926. string no = account.GetProperty("no").GetString();
  2927. ret.Add((id, no));
  2928. }
  2929. }
  2930. }
  2931. return ret;
  2932. }
  2933. /// <summary>
  2934. /// 取得年級資訊
  2935. /// </summary>
  2936. /// <param name="schoolId"></param>
  2937. /// <returns>Key:periodId Vaule:list gradeInfo</returns>
  2938. public static async Task<Dictionary<string, List<(int gradeId, string gradeName)>>> getGrades(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId)
  2939. {
  2940. try
  2941. {
  2942. //Key:學制 Value:年級資訊list
  2943. Dictionary<string, List<(int gradeId, string gradeName)>> dicPeriod = new Dictionary<string, List<(int gradeId, string gradeName)>>();
  2944. var response = await _azureCosmos
  2945. .GetCosmosClient()
  2946. .GetContainer(Constant.TEAMModelOS, "School")
  2947. .ReadItemStreamAsync(schoolId, new PartitionKey("Base"));
  2948. if (response.StatusCode != HttpStatusCode.OK) return null;
  2949. using Stream stream = response.Content;
  2950. var jsonDoc = await JsonDocument.ParseAsync(stream);
  2951. var emumObject = jsonDoc.RootElement.EnumerateObject();
  2952. var period = jsonDoc.RootElement.GetProperty("period").EnumerateArray();
  2953. while (period.MoveNext())
  2954. {
  2955. List<(int gradeId, string gradeName)> gradeInfos = new List<(int gradeId, string gradeName)>();
  2956. JsonElement jsonPeriod = period.Current;
  2957. var periodId = jsonPeriod.GetProperty("id").GetString();
  2958. var grades = jsonPeriod.GetProperty("grades").ToObject<List<string>>();
  2959. for (int index = 0; index < grades.Count; index++)
  2960. {
  2961. gradeInfos.Add((index, grades[index]));
  2962. }
  2963. //var grades = jsonPeriod.GetProperty("grades").EnumerateArray();
  2964. //while (grades.MoveNext())
  2965. //{
  2966. // JsonElement grade = grades.Current;
  2967. // var gradeId = grade.GetInt32();
  2968. // var gradeName = grade.GetProperty("name").GetString();
  2969. // gradeInfos.Add((gradeId, gradeName));
  2970. //}
  2971. dicPeriod.Add(periodId, gradeInfos);
  2972. }
  2973. return dicPeriod;
  2974. }
  2975. catch (Exception ex)
  2976. {
  2977. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getGrades()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2978. return null;
  2979. }
  2980. }
  2981. public struct studCreateInfo
  2982. {
  2983. public studCreateInfo(string id, string name, string gender, int year, string pw, string classId, string no, string periodId, string imei, List<StudentGuardian> guardians)
  2984. {
  2985. this.id = id;
  2986. this.name = name;
  2987. this.gender = gender;
  2988. this.year = year;
  2989. this.pw = pw;
  2990. this.classId = classId;
  2991. this.no = no;
  2992. this.periodId = periodId;
  2993. this.imei = imei;
  2994. this.guardians = guardians;
  2995. }
  2996. public string id { get; }
  2997. public string name { get; }
  2998. public string gender { get; }
  2999. public int year { get; }
  3000. public string pw { get; }
  3001. public string classId { get; }
  3002. public string no { get; }
  3003. public string periodId { get; set; }
  3004. public string imei { get; set; }
  3005. public List<StudentGuardian> guardians { get; set; }
  3006. }
  3007. }
  3008. }