StudentService.cs 161 KB

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