StudentService.cs 178 KB

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