StudentService.cs 177 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197
  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.WriteEndObject();
  1666. writer.Flush();
  1667. var ret = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").CreateItemStreamAsync(memoryStream, new PartitionKey($"Class-{schoolId}"));
  1668. if (ret.StatusCode !=HttpStatusCode.Created)
  1669. {
  1670. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createClassInfo()\nStatus:{ret.StatusCode}\nSchoolId:{schoolId},ClassId:{classId}", GroupNames.醍摩豆服務運維群組);
  1671. }
  1672. return (cId, classNo, className, periodId, gradeId, classYear);
  1673. }
  1674. catch (CosmosException ex)
  1675. {
  1676. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createClassInfo()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1677. }
  1678. catch (Exception ex)
  1679. {
  1680. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createClassInfo()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1681. }
  1682. return (null, null, null, null, null, 0);
  1683. }
  1684. /// <summary>
  1685. /// 使用學校代碼查詢該校所有學生,並且在查詢該學生所屬的教室及座號,支援offset和limit操作已及ContinuationToken,若有ContinuationToken,則會優先使用ContinuationToken。
  1686. /// </summary>
  1687. /// <param name="schoolId"></param>
  1688. /// <param name="byNameOrId">透過Name或Id來查,所以不會管學制、學級和教室</param>
  1689. /// <param name="byPeriod"></param>
  1690. /// <param name="byGrade"></param>
  1691. /// <param name="byClassId"></param>
  1692. /// <param name="offset"></param>
  1693. /// <param name="limit"></param>
  1694. /// <param name="token"></param>
  1695. /// <returns></returns>
  1696. private async Task<(List<object> students, string continuationToken)> getStudents(
  1697. AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option,
  1698. string schoolId, string byNameOrId = null, string byPeriod = null, string byGrade = null, string byClassId = null, int offset = -1, int limit = -1, string token = default)
  1699. {
  1700. try
  1701. {
  1702. //以學校學生角度去抓資料
  1703. List<(string id, string name, string picture, int year)> listStudent = new List<(string id, string name, string picture, int year)>();
  1704. string queryText = $"SELECT c.id, c.name, c.picture, c.year FROM c WHERE c.code = 'Base-{schoolId}'";
  1705. //如果有選擇ClassId的話,則先取得該教室內的學生。
  1706. List<string> searchId = new List<string>();
  1707. if (!string.IsNullOrWhiteSpace(byClassId))
  1708. {
  1709. var classInfos = await getClassInfoUseId(_azureCosmos, _dingDing, _option, schoolId, new List<string>() { byClassId });
  1710. foreach (var classInfo in classInfos)
  1711. {
  1712. var students = classInfo.Value.GetProperty("students").EnumerateArray();
  1713. while (students.MoveNext())
  1714. {
  1715. JsonElement stud = students.Current;
  1716. string id = stud.GetProperty("id").GetString();
  1717. searchId.Add(id);
  1718. }
  1719. }
  1720. //將使用者過濾classId所取得的學生ID加入sql字串內
  1721. if (searchId.Count != 0)
  1722. {
  1723. queryText = $"{queryText} AND c.id IN ({string.Join(",", searchId.Select(o => $"'{o}'"))})";
  1724. }
  1725. }
  1726. //檢查是否有接續token及是否要在sql語法內多增加offset及limit
  1727. if (string.IsNullOrWhiteSpace(token))
  1728. {
  1729. token = default;
  1730. if (offset != -1 && limit != -1) queryText = $"{queryText} OFFSET {offset} LIMIT {limit}";
  1731. }
  1732. //回傳用ContinuationToken
  1733. string continuationToken = string.Empty;
  1734. //進行學生資料的查詢
  1735. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student")
  1736. .GetItemQueryStreamIteratorSql(
  1737. queryText: queryText,
  1738. continuationToken: token,
  1739. requestOptions: new QueryRequestOptions()
  1740. { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  1741. {
  1742. continuationToken = item.ContinuationToken;
  1743. using var json = await JsonDocument.ParseAsync(item.Content);
  1744. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1745. {
  1746. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1747. while (accounts.MoveNext())
  1748. {
  1749. JsonElement account = accounts.Current;
  1750. listStudent.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString(), account.GetProperty("picture").GetString(), account.GetProperty("year").GetInt32()));
  1751. }
  1752. }
  1753. //單筆查詢上限為100條,所以查完一次即返回,並且給接續token。
  1754. break;
  1755. }
  1756. //查學生所屬的教室及座號
  1757. List<object> ret = new List<object>();
  1758. //查教室資訊,使用上面的學生id並透過子查詢查詢。
  1759. 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}'"))}))";
  1760. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
  1761. .GetItemQueryStreamIteratorSql(
  1762. queryText: queryText,
  1763. //continuationToken: token,
  1764. requestOptions: new QueryRequestOptions()
  1765. { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  1766. {
  1767. using var json = await JsonDocument.ParseAsync(item.Content);
  1768. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1769. {
  1770. var classrooms = json.RootElement.GetProperty("Documents").EnumerateArray();
  1771. while (classrooms.MoveNext())
  1772. {
  1773. JsonElement classroom = classrooms.Current;
  1774. var studs = classroom.GetProperty("students").EnumerateArray();
  1775. while (studs.MoveNext())
  1776. {
  1777. JsonElement stud = studs.Current;
  1778. string id = stud.GetProperty("id").GetString();
  1779. //整理出前端所需的資訊
  1780. var tmp = listStudent
  1781. .Where(o => o.id.Equals(id, StringComparison.Ordinal))
  1782. .Select(o =>
  1783. new
  1784. {
  1785. o.id,
  1786. o.name,
  1787. o.picture,
  1788. o.year,
  1789. no = stud.GetProperty("no").GetString(),
  1790. gradeId = classroom.GetProperty("gradeId").GetString(),
  1791. className = classroom.GetProperty("name").GetString()
  1792. });
  1793. ret.AddRange(tmp);
  1794. //刪除已整理完的ID
  1795. listStudent.RemoveAll(o => o.id.Equals(id, StringComparison.Ordinal));
  1796. }
  1797. }
  1798. }
  1799. }
  1800. var notJoinClassStuds = listStudent.Select(o =>
  1801. new
  1802. {
  1803. o.id,
  1804. o.name,
  1805. o.picture,
  1806. o.year,
  1807. no = (string)null,
  1808. gradeId = (string)null,
  1809. className = (string)null
  1810. });
  1811. ret.AddRange(notJoinClassStuds);
  1812. return (ret, continuationToken);
  1813. }
  1814. catch (CosmosException ex)
  1815. {
  1816. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1817. }
  1818. catch (Exception ex)
  1819. {
  1820. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1821. }
  1822. return (null, null);
  1823. }
  1824. /// <summary>
  1825. /// 取得該學校的所有學生。
  1826. /// </summary>
  1827. /// <param name="schoolId"></param>
  1828. /// <returns> [{id,name,picture,year,no,classId,classNo,className,gradeId,periodId},{id,name,picture,..}..]</returns>
  1829. public static async Task<List<object>> getAllStudent(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, int inyear, int graduate = 0)
  1830. {
  1831. try
  1832. {
  1833. //TODO : 進階查詢選項調整、部分地方可用並行處理
  1834. //以學校學生角度去抓資料
  1835. Dictionary<string, List<(string id, string name, string picture, int year, string no, string periodId, string irs, string imei, string gender, int graduate, bool hasEduOpenId, List<StudentGuardian> guardians)>> dicClassStuds =
  1836. new Dictionary<string, List<(string id, string name, string picture, int year, string no, string periodId, string irs, string imei, string gender, int graduate, bool hasEduOpenId, List<StudentGuardian> guardians)>>();
  1837. List<(string id, string name, string picture, int year, string no, string periodId, string irs, string imei, string gender, int graduate, bool hasEduOpenId, List<StudentGuardian> guardians)> notJoinClassStuds =
  1838. 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)>();
  1839. List<Imei> imeis = new List<Imei>();
  1840. string imeiQueryText = $"SELECT * FROM c WHERE c.school = '{schoolId}'";
  1841. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student")
  1842. .GetItemQueryIteratorSql<Imei>(queryText: imeiQueryText, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Imei") }))
  1843. {
  1844. imeis.Add(item);
  1845. }
  1846. List<Student> graduate_students = new List<Student>();
  1847. List<Class> school_classes = new List<Class>();
  1848. string queryText = "";
  1849. if (graduate == 0)
  1850. {
  1851. queryText = $"SELECT * FROM c WHERE c.code = 'Base-{schoolId}' and (c.graduate = 0 or IS_DEFINED(c.graduate) = false )";
  1852. }
  1853. else
  1854. {
  1855. queryText = $"SELECT * FROM c WHERE c.code = 'Base-{schoolId}' and c.graduate = 1 and c.year ={inyear} ";
  1856. ///查询当年的毕业班
  1857. string sql = sql = $"SELECT value c FROM c where c.graduate =1 and c.year ={inyear}"; ;
  1858. var client = _azureCosmos.GetCosmosClient();
  1859. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<Class>
  1860. (queryText: sql,
  1861. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  1862. {
  1863. school_classes.Add(item);
  1864. }
  1865. //如果已经毕业的班级不为空。
  1866. if (school_classes.IsNotEmpty())
  1867. {
  1868. string classSql = $"SELECT value c FROM c WHERE c.code = 'Base-{schoolId}' and c.graduate = 1 and c.classId in( {string.Join(",", school_classes.Select(x => $"'{x.id}'"))} )";
  1869. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIteratorSql<Student>(queryText: classSql,
  1870. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  1871. {
  1872. graduate_students.Add(item);
  1873. }
  1874. }
  1875. }
  1876. //回傳用ContinuationToken
  1877. string continuationToken = string.Empty;
  1878. var container = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student");
  1879. //進行學生資料的查詢 TEAMModelOS-Student
  1880. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student")
  1881. .GetItemQueryStreamIteratorSql(
  1882. queryText: queryText,
  1883. requestOptions: new QueryRequestOptions()
  1884. { PartitionKey = new PartitionKey($"Base-{schoolId}"), MaxItemCount = -1 }))
  1885. {
  1886. continuationToken = item.ContinuationToken;
  1887. using var json = await JsonDocument.ParseAsync(item.Content);
  1888. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1889. {
  1890. List<(string id, string name, string picture, int year, string no, List<StudentGuardian> guardians)> students = new List<(string id, string name, string picture, int year, string no, List<StudentGuardian> guardians)>();
  1891. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1892. while (accounts.MoveNext())
  1893. {
  1894. JsonElement acc = accounts.Current;
  1895. string classId = acc.GetProperty("classId").GetString();
  1896. acc.TryGetProperty("irs", out JsonElement irs);
  1897. acc.TryGetProperty("guardians", out JsonElement _guardians);
  1898. List<StudentGuardian> guardians = new List<StudentGuardian>();
  1899. if (_guardians.ValueKind.Equals(JsonValueKind.Array))
  1900. {
  1901. guardians = _guardians.Deserialize<List<StudentGuardian>>();
  1902. if (guardians.Any())
  1903. {
  1904. guardians = guardians.FindAll(x => !string.IsNullOrWhiteSpace(x.mobile));
  1905. }
  1906. }
  1907. var imeiObj = imeis.Find(x => x.stuid.Equals(acc.GetProperty("id").GetString()));
  1908. if (string.IsNullOrWhiteSpace(classId))
  1909. {
  1910. notJoinClassStuds.Add(
  1911. (
  1912. acc.GetProperty("id").GetString(),
  1913. acc.GetProperty("name").GetString(),
  1914. acc.GetProperty("picture").GetString(),
  1915. acc.GetProperty("year").GetInt32(),
  1916. acc.GetProperty("no").GetString(),
  1917. acc.TryGetProperty("periodId", out JsonElement _periodId) && _periodId.ValueKind.Equals(JsonValueKind.String) ? _periodId.GetString() : null,
  1918. $"{irs}",
  1919. imeiObj?.id,//imei
  1920. acc.TryGetProperty("gender", out JsonElement _gender) && _gender.ValueKind.Equals(JsonValueKind.String) ? _gender.GetString() : null,
  1921. acc.TryGetProperty("graduate", out JsonElement _graduate) && _graduate.ValueKind.Equals(JsonValueKind.Number) ? int.Parse($"{_graduate}") : 0,
  1922. acc.TryGetProperty("openId", out JsonElement _openId) && !string.IsNullOrWhiteSpace(_openId.GetString()) ? true : false,
  1923. guardians
  1924. )
  1925. );
  1926. }
  1927. else
  1928. {
  1929. if (dicClassStuds.ContainsKey(classId))
  1930. {
  1931. dicClassStuds[classId].Add(
  1932. (
  1933. acc.GetProperty("id").GetString(),
  1934. acc.GetProperty("name").GetString(),
  1935. acc.GetProperty("picture").GetString(),
  1936. acc.GetProperty("year").GetInt32(),
  1937. acc.GetProperty("no").GetString(), acc.TryGetProperty("periodId", out JsonElement _periodId) && _periodId.ValueKind.Equals(JsonValueKind.String) ? _periodId.GetString() : null,
  1938. $"{irs}",
  1939. imeiObj?.id,//imei
  1940. acc.TryGetProperty("gender", out JsonElement _gender) && _gender.ValueKind.Equals(JsonValueKind.String) ? _gender.GetString() : null,
  1941. acc.TryGetProperty("graduate", out JsonElement _graduate) && _graduate.ValueKind.Equals(JsonValueKind.Number) ? int.Parse($"{_graduate}") : 0,
  1942. acc.TryGetProperty("openId", out JsonElement _openId) && !string.IsNullOrWhiteSpace(_openId.GetString()) ? true : false,
  1943. guardians
  1944. )
  1945. );
  1946. }
  1947. else
  1948. {
  1949. dicClassStuds.Add(classId,
  1950. 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)>()
  1951. {
  1952. (
  1953. acc.GetProperty("id").GetString(),
  1954. acc.GetProperty("name").GetString(),
  1955. acc.GetProperty("picture").GetString(),
  1956. acc.GetProperty("year").GetInt32(),
  1957. acc.GetProperty("no").GetString(), acc.TryGetProperty("periodId",out JsonElement _periodId)&& _periodId.ValueKind.Equals(JsonValueKind.String) ? _periodId.GetString() : null,
  1958. $"{irs}" ,
  1959. imeiObj?.id,//imei
  1960. acc.TryGetProperty("gender", out JsonElement _gender) && _gender.ValueKind.Equals(JsonValueKind.String) ? _gender.GetString() : null,
  1961. acc.TryGetProperty("graduate", out JsonElement _graduate) && _graduate.ValueKind.Equals(JsonValueKind.Number) ? int.Parse($"{_graduate}"): 0,
  1962. acc.TryGetProperty("openId", out JsonElement _openId) && !string.IsNullOrWhiteSpace(_openId.GetString()) ? true : false,
  1963. guardians
  1964. )
  1965. }
  1966. );
  1967. }
  1968. }
  1969. }
  1970. }
  1971. }
  1972. //查學生所屬的教室及座號
  1973. List<object> ret = new List<object>();
  1974. //查教室的資訊,用以取得gradeId,periodId資訊。
  1975. var classInfos = await getClassInfoUseId(_azureCosmos, _dingDing, _option, schoolId, dicClassStuds.Keys.ToList());
  1976. //輪循所有教室學生的資料
  1977. foreach (var classStud in dicClassStuds)
  1978. {
  1979. string classId = null, classNo = null, className = null, gradeId = null, periodId = null;
  1980. int classYear = -1;
  1981. if (classInfos.ContainsKey(classStud.Key))
  1982. {
  1983. classId = classInfos[classStud.Key].GetProperty("id").GetString();
  1984. classNo = classInfos[classStud.Key].GetProperty("no").GetString();
  1985. className = classInfos[classStud.Key].GetProperty("name").GetString();
  1986. periodId = classInfos[classStud.Key].TryGetProperty("periodId", out JsonElement _periodId) && _periodId.ValueKind.Equals(JsonValueKind.String) ? _periodId.GetString() : null;
  1987. if (classInfos[classStud.Key].TryGetProperty("year", out JsonElement year))
  1988. {
  1989. if (year.ValueKind.Equals(JsonValueKind.Number))
  1990. {
  1991. classYear = classInfos[classStud.Key].GetProperty("year").GetInt32();
  1992. }
  1993. }
  1994. }
  1995. var tmp = classStud.Value.Select(o =>
  1996. new
  1997. {
  1998. o.id,
  1999. o.name,
  2000. o.picture,
  2001. o.year,
  2002. o.no,
  2003. classId,
  2004. classNo,
  2005. className,
  2006. gradeId,
  2007. periodId = string.IsNullOrEmpty(periodId) ? o.periodId : periodId,
  2008. classYear,
  2009. irs = o.irs,
  2010. imei = o.imei,
  2011. gender = o.gender,
  2012. graduate = o.graduate,
  2013. hasEduOpenId = o.hasEduOpenId,
  2014. guardians = o.guardians,
  2015. });
  2016. ret.AddRange(tmp);
  2017. }
  2018. //彙整沒有加入教室的學生
  2019. notJoinClassStuds.ForEach(o => ret.Add(
  2020. new
  2021. {
  2022. o.id,
  2023. o.name,
  2024. o.picture,
  2025. o.year,
  2026. o.no,
  2027. classId = (string)null,
  2028. classNo = (string)null,
  2029. className = (string)null,
  2030. gradeId = (string)null,
  2031. o.periodId,
  2032. classYear = -1,
  2033. irs = o.irs,
  2034. imei = o.imei,
  2035. gender = o.gender,
  2036. hasEduOpenId = o.hasEduOpenId,
  2037. guardians = o.guardians,
  2038. }));
  2039. graduate_students.ForEach(o =>
  2040. {
  2041. var imeiObj = imeis.Find(x => x.stuid.Equals(o.id));
  2042. Class stuClass = school_classes.Find(x => x.id.Equals(o.classId));
  2043. ret.Add(
  2044. new
  2045. {
  2046. o.id,
  2047. o.name,
  2048. o.picture,
  2049. o.year,
  2050. o.no,
  2051. classId = stuClass?.id,
  2052. classNo = stuClass?.no,
  2053. className = stuClass?.name,
  2054. gradeId = stuClass?.gradeId,
  2055. o.periodId,
  2056. classYear = stuClass?.year,
  2057. irs = o.irs,
  2058. imei = imeiObj?.id,
  2059. gender = o.gender,
  2060. hasEduOpenId = (!string.IsNullOrWhiteSpace(o.openId)) ? true : false,
  2061. guardians = o.guardians,
  2062. });
  2063. });
  2064. return ret;
  2065. }
  2066. catch (Exception ex)
  2067. {
  2068. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getStudents()\n{ex.Message}\n{ex.StackTrace},", GroupNames.醍摩豆服務運維群組);
  2069. }
  2070. return null;
  2071. }
  2072. /// <summary>
  2073. /// 取得該校所有教室內的名單
  2074. /// </summary>
  2075. /// <param name="schoolId"></param>
  2076. /// <returns></returns>
  2077. public async Task<Dictionary<string, JsonElement>> getClassStudent(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, string classId = null)
  2078. {
  2079. try
  2080. {
  2081. string queryText = $"SELECT VALUE FROM c WHERE c.";
  2082. //if (!string.IsNullOrWhiteSpace(classId)) queryText += $" AND c.id = '{classId}'";
  2083. Dictionary<string, JsonElement> listStudent = new Dictionary<string, JsonElement>();
  2084. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
  2085. .GetItemQueryStreamIteratorSql(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  2086. {
  2087. using var json = await JsonDocument.ParseAsync(item.Content);
  2088. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2089. {
  2090. JsonElement.ArrayEnumerator accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  2091. while (accounts.MoveNext())
  2092. {
  2093. JsonElement account = accounts.Current;
  2094. string cId = account.GetProperty("id").GetString();
  2095. var students = account.GetProperty("students").Clone();
  2096. listStudent.Add(cId, students);
  2097. }
  2098. }
  2099. }
  2100. return listStudent;
  2101. }
  2102. catch (Exception ex)
  2103. {
  2104. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassStudentAsync()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2105. }
  2106. return null;
  2107. }
  2108. /// <summary>
  2109. /// 刪除學生,非透過批量刪除方法。
  2110. /// </summary>
  2111. /// <param name="schoolId"></param>
  2112. /// <param name="students"></param>
  2113. /// <returns></returns>
  2114. public static async Task<List<string>> deleteStudents(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, JsonElement.ArrayEnumerator students)
  2115. {
  2116. List<string> sucIds = new List<string>();
  2117. try
  2118. {
  2119. var exceptions = new List<Exception>();
  2120. List<GroupList> scGroupLists = new List<GroupList>();
  2121. List<GroupList> teGroupLists = new List<GroupList>();
  2122. var container = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student");
  2123. while (students.MoveNext())
  2124. {
  2125. string id = string.Empty;
  2126. try
  2127. {
  2128. JsonElement student = students.Current;
  2129. id = student.GetProperty("id").GetString();
  2130. var ret = await container.DeleteItemStreamAsync(id, new PartitionKey($"Base-{schoolId}"));
  2131. await upsertImei(id, null, schoolId, "delete", container);
  2132. if (ret.StatusCode == HttpStatusCode.NoContent) sucIds.Add(id);
  2133. 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}") }))
  2134. {
  2135. scGroupLists.Add(item);
  2136. }
  2137. 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") }))
  2138. {
  2139. teGroupLists.Add(item);
  2140. }
  2141. if (scGroupLists.Count > 0)
  2142. {
  2143. foreach (GroupList stuList in scGroupLists)
  2144. {
  2145. for (int j = 0; j < stuList.members.Count; j++)
  2146. {
  2147. if (id.Equals(stuList.members[j].id) && stuList.members[j].code.Equals(schoolId))
  2148. {
  2149. stuList.members.RemoveAt(j);
  2150. stuList.scount -= 1;
  2151. break;
  2152. }
  2153. }
  2154. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(stuList, stuList.id, new PartitionKey(stuList.code));
  2155. }
  2156. }
  2157. if (teGroupLists.Count > 0)
  2158. {
  2159. foreach (GroupList stuList in teGroupLists)
  2160. {
  2161. for (int j = 0; j < stuList.members.Count; j++)
  2162. {
  2163. if (id.Equals(stuList.members[j].id) && stuList.members[j].code.Equals(schoolId))
  2164. {
  2165. stuList.members.RemoveAt(j);
  2166. stuList.scount -= 1;
  2167. break;
  2168. }
  2169. }
  2170. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(stuList, stuList.id, new PartitionKey(stuList.code));
  2171. }
  2172. }
  2173. }
  2174. catch (CosmosException ex)
  2175. {
  2176. exceptions.Add(ex);
  2177. }
  2178. catch (Exception ex)
  2179. {
  2180. exceptions.Add(ex);
  2181. }
  2182. }
  2183. if (exceptions.Count == 0) return sucIds;
  2184. else if (exceptions.Count > 1) throw new AggregateException(exceptions);
  2185. else if (exceptions.Count == 1) throw exceptions.Single();
  2186. }
  2187. catch (CosmosException ex)
  2188. {
  2189. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/deleteStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2190. }
  2191. catch (Exception ex)
  2192. {
  2193. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/deleteStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2194. }
  2195. return sucIds;
  2196. }
  2197. /// <summary>
  2198. /// 將學生基本資料內的classId、no、groupId及groupName清為null。
  2199. /// </summary>
  2200. /// <param name="schoolId"></param>
  2201. /// <param name="students">["id1","id2",...]</param>
  2202. /// <returns></returns>
  2203. 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)
  2204. {
  2205. //紀錄輸入的學生
  2206. List<string> impStuds = new List<string>();
  2207. //紀錄更新成功的學生
  2208. List<string> sucStuds = new List<string>();
  2209. //記錄沒查到的學生
  2210. List<string> nonexistentIds = new List<string>();
  2211. //紀錄更新出錯的學生
  2212. List<string> errorIds = new List<string>();
  2213. //整理輸入的學生資訊
  2214. while (students.MoveNext())
  2215. {
  2216. JsonElement student = students.Current;
  2217. impStuds.Add(student.GetString());
  2218. }
  2219. if (impStuds.Count == 0) return (null, null, null);
  2220. string queryText = $"SELECT VALUE c FROM c WHERE c.id IN ({string.Join(",", impStuds.Select(o => $"'{o}'"))})";
  2221. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student")
  2222. .GetItemQueryStreamIteratorSql(
  2223. queryText: queryText,
  2224. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  2225. {
  2226. using var json = await JsonDocument.ParseAsync(item.Content);
  2227. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2228. {
  2229. JsonElement.ArrayEnumerator docs = json.RootElement.GetProperty("Documents").EnumerateArray();
  2230. while (docs.MoveNext())
  2231. {
  2232. JsonElement doc = docs.Current;
  2233. doc.TryGetProperty("id", out var tmpId);
  2234. var id = tmpId.GetString();
  2235. using var stream = new MemoryStream();
  2236. using var writer = new Utf8JsonWriter(stream);
  2237. writer.WriteStartObject();
  2238. foreach (var element in doc.EnumerateObject())
  2239. {
  2240. //將教室相關欄位清空
  2241. switch (true)
  2242. {
  2243. case bool _ when element.Name.Equals("classId", StringComparison.Ordinal):
  2244. writer.WriteNull("classId");
  2245. break;
  2246. case bool _ when element.Name.Equals("no", StringComparison.Ordinal):
  2247. writer.WriteNull("no");
  2248. break;
  2249. case bool _ when element.Name.Equals("groupId", StringComparison.Ordinal):
  2250. writer.WriteNull("groupId");
  2251. break;
  2252. case bool _ when element.Name.Equals("groupName", StringComparison.Ordinal):
  2253. writer.WriteNull("groupName");
  2254. break;
  2255. case bool _ when element.Name.Equals("irs", StringComparison.Ordinal):
  2256. writer.WriteNull("irs");
  2257. break;
  2258. case bool _ when element.Name.StartsWith("_", StringComparison.Ordinal):
  2259. break;
  2260. default:
  2261. element.WriteTo(writer);
  2262. break;
  2263. }
  2264. }
  2265. writer.WriteEndObject();
  2266. writer.Flush();
  2267. var ret = await _azureCosmos
  2268. .GetCosmosClient()
  2269. .GetContainer(Constant.TEAMModelOS, "Student")
  2270. .ReplaceItemStreamAsync(stream, id, new PartitionKey($"Base-{schoolId}"));
  2271. if (ret.StatusCode == HttpStatusCode.OK)
  2272. {
  2273. sucStuds.Add(id);
  2274. }
  2275. else
  2276. {
  2277. impStuds.Remove(id);
  2278. errorIds.Add(id);
  2279. await _dingDing.SendBotMsg(
  2280. $"IES5,{_option.Location},StudentController/removeStudentClassInfo(),CosmosDB response:{ret.StatusCode}\nBase-{schoolId},id:{id}",
  2281. GroupNames.醍摩豆服務運維群組);
  2282. }
  2283. }
  2284. }
  2285. }
  2286. //將impStuds內的資料移除sucStuds及errorIds,所得的結果就是不存在於資料庫的id。
  2287. sucStuds.ForEach(o => impStuds.Remove(o));
  2288. errorIds.ForEach(o => impStuds.Remove(o));
  2289. return (sucStuds, impStuds, errorIds);
  2290. }
  2291. /// <summary>
  2292. /// 取得教室資訊,使用classId進行查詢。
  2293. /// </summary>
  2294. /// <returns></returns>
  2295. private static async Task<Dictionary<string, JsonElement>> getClassInfoUseId(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, List<string> classIds)
  2296. {
  2297. try
  2298. {
  2299. if (!(classIds == null || classIds.Count == 0))
  2300. {
  2301. string queryText = $"SELECT * FROM c WHERE c.code = 'Class-{schoolId}' AND c.id IN ({string.Join(",", classIds.Select(o => $"'{o}'"))})";
  2302. Dictionary<string, JsonElement> dicClassInfo = new Dictionary<string, JsonElement>();
  2303. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
  2304. .GetItemQueryStreamIteratorSql(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  2305. {
  2306. using var json = await JsonDocument.ParseAsync(item.Content);
  2307. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2308. {
  2309. var classInfos = json.RootElement.GetProperty("Documents").EnumerateArray();
  2310. while (classInfos.MoveNext())
  2311. {
  2312. JsonElement account = classInfos.Current;
  2313. string id = account.GetProperty("id").GetString();
  2314. dicClassInfo.Add(id, account.Clone());
  2315. }
  2316. }
  2317. }
  2318. return dicClassInfo;
  2319. }
  2320. else return null;
  2321. }
  2322. catch (CosmosException ex)
  2323. {
  2324. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassInfoUseId()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2325. }
  2326. catch (Exception ex)
  2327. {
  2328. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassInfoUseId()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2329. }
  2330. return null;
  2331. }
  2332. /// <summary>
  2333. /// 取得教室資訊,使用classNo進行查詢。
  2334. /// </summary>
  2335. /// <returns></returns>
  2336. 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)
  2337. {
  2338. Dictionary<string, Class> dicClassInfo = new Dictionary<string, Class>();
  2339. try
  2340. {
  2341. if (!(classNos == null || classNos.Count == 0))
  2342. {
  2343. foreach (var key in classNos.Keys)
  2344. {
  2345. 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}' ";
  2346. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
  2347. .GetItemQueryIteratorSql<Class>(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  2348. {
  2349. dicClassInfo[item.id] = item;
  2350. item.name = classNos[key].className;
  2351. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<Class>(item, item.id, new PartitionKey(item.code));
  2352. }
  2353. }
  2354. return dicClassInfo;
  2355. }
  2356. else return dicClassInfo;
  2357. }
  2358. catch (CosmosException ex)
  2359. {
  2360. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassInfoUseId()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2361. }
  2362. catch (Exception ex)
  2363. {
  2364. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassInfoUseId()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2365. }
  2366. return dicClassInfo;
  2367. }
  2368. /// <summary>
  2369. /// 批量更新學生資訊,目前支持更新姓名、密碼、座號、性別及教室id,匯入時ClassId為必填。
  2370. /// </summary>
  2371. /// <param name="schoolId"></param>
  2372. /// <param name="students"></param>
  2373. /// <returns></returns>
  2374. public static async Task<(List<object> studs, Dictionary<string, List<string>> classDuplNos, List<string> nonexistentIds, List<string> errorIds,
  2375. Dictionary<string, List<string>> errorNos, List<string> errorClassId)>
  2376. updateStudents(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, JsonElement.ArrayEnumerator students)
  2377. {
  2378. try
  2379. {
  2380. //整理輸入的資料->檢查輸入資料有沒有重複座號->取得欲加入的教室資訊->查詢學生並將資料更新並寫入
  2381. //Key:id Value:學生基本資訊
  2382. var studentInfos
  2383. = new Dictionary<string, (string salt, string pw, string name, int year, string picture, string gender, string mail, string mobile,
  2384. string classId, string no, string periodId, string irs, string imei, List<StudentGuardian> guardians)>();
  2385. //用於進行座號是否重複查詢時使用
  2386. var classStuds
  2387. = new Dictionary<string, List<(string id, string salt, string pw, string name, int year, string picture, string gender, string mail, string mobile,
  2388. string classId, string no, string periodId)>>();
  2389. //紀錄教室"輸入"的學生座號是否有重複
  2390. var impClassDuplNo = new Dictionary<string, List<string>>();
  2391. //紀錄不存在的學生id
  2392. var nonexistentIds = new List<string>();
  2393. //紀錄跟現有雲端學生座號重複的
  2394. var errorNos = new Dictionary<string, List<string>>();
  2395. //紀錄處理錯誤的id,cosmosdb寫入時錯誤等...
  2396. var errorIds = new List<string>();
  2397. //紀錄沒找到的classId
  2398. var errorClassId = new List<string>();
  2399. //紀錄輸出結果
  2400. var retStuds = new List<object>();
  2401. //整理輸入資料
  2402. while (students.MoveNext())
  2403. {
  2404. JsonElement student = students.Current;
  2405. if (student.TryGetProperty("id", out var id))
  2406. {
  2407. //確認是否有id欄位,並且確認是否有給pw欄位,若無給或是null empty等,則使用id當密碼。
  2408. if (!string.IsNullOrWhiteSpace(id.GetString()))
  2409. {
  2410. string salt = null,
  2411. pw = null,
  2412. name = null,
  2413. gender = null,
  2414. mail = null,
  2415. mobile = null,
  2416. classId = null,
  2417. periodId = null,
  2418. irs = null,
  2419. imei = null,
  2420. no = null;
  2421. List<StudentGuardian> guardians = null;
  2422. int year = 0;
  2423. //有給pw欄位才進行處理
  2424. if (student.TryGetProperty("pw", out var tmpPw) && !"******".Equals($"{tmpPw}"))
  2425. {
  2426. var response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemStreamAsync(id.GetString(), new PartitionKey($"Base-{schoolId}"));
  2427. if (response.StatusCode == HttpStatusCode.OK)
  2428. {
  2429. var rjson = await JsonDocument.ParseAsync(response.Content);
  2430. rjson.RootElement.TryGetProperty("salt", out JsonElement _salt);
  2431. salt = $"{_salt}";
  2432. }
  2433. if (string.IsNullOrWhiteSpace(salt))
  2434. {
  2435. salt = Utils.CreatSaltString(8);
  2436. }
  2437. pw = !string.IsNullOrWhiteSpace(tmpPw.GetString())
  2438. ? Utils.HashedPassword(tmpPw.GetString(), salt)
  2439. : Utils.HashedPassword(id.GetString(), salt);
  2440. }
  2441. if (student.TryGetProperty("name", out var tmpName)) name = tmpName.GetString();
  2442. if (student.TryGetProperty("gender", out var tmpGender)) gender = tmpGender.GetString();
  2443. if (student.TryGetProperty("mail", out var tmpMail)) mail = tmpMail.GetString();
  2444. if (student.TryGetProperty("mobile", out var tmpMobile)) mobile = tmpMobile.GetString();
  2445. if (student.TryGetProperty("year", out var tmpYear)) year = tmpYear.GetInt32();
  2446. if (student.TryGetProperty("periodId", out var tmpperiodId)) periodId = tmpperiodId.GetString();
  2447. if (student.TryGetProperty("irs", out var tmpIrs)) irs = tmpIrs.GetString();
  2448. if (student.TryGetProperty("imei", out var tmpImei)) imei = tmpImei.GetString();
  2449. if (student.TryGetProperty("classId", out var tmpclassId)) classId = tmpclassId.GetString();
  2450. else
  2451. {
  2452. errorClassId.Add(id.GetString());
  2453. continue;
  2454. }
  2455. if (student.TryGetProperty("guardians", out var _guardians) && _guardians.ValueKind.Equals(JsonValueKind.Array))
  2456. {
  2457. guardians = _guardians.Deserialize<List<StudentGuardian>>();
  2458. }
  2459. //如果有給該欄位,且是給空的,代表要清空
  2460. if (student.TryGetProperty("no", out var tmpNo)) no = tmpNo.GetString();
  2461. if (!studentInfos.ContainsKey(id.GetString()))
  2462. {
  2463. //如果有給classId且是給空的,則也將no設為空,後續才能將no欄位清空。
  2464. if (classId != null && classId.Length == 0) no = string.Empty;
  2465. //classId => 沒給欄位(null) 有給欄位("") 但更新一定得給教室?
  2466. if (classId == null)
  2467. {
  2468. classId = "";
  2469. }
  2470. if (classStuds.ContainsKey(classId))
  2471. {
  2472. classStuds[classId].Add((id.GetString(), salt, pw, name, year, null, gender, null, null, classId, no, periodId));
  2473. }
  2474. else
  2475. {
  2476. classStuds.Add(
  2477. classId,
  2478. 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)>()
  2479. { (id.GetString(), salt, pw, name, year, null, gender, null, null, classId, no,periodId) });
  2480. }
  2481. //picture,mail,mobile暫不支持批量更新
  2482. studentInfos.Add(id.GetString(), (salt, pw, name, year, null, gender, null, null, classId, no, periodId, irs, imei, guardians));
  2483. //先將id加進去後面再做刪除動作
  2484. nonexistentIds.Add(id.GetString());
  2485. }
  2486. }
  2487. }
  2488. }
  2489. //檢查所有輸入的班級資料內,學生座號是否有重複。
  2490. for (int ii = 0; ii <= classStuds.Values.Count - 1; ii++)
  2491. {
  2492. var duplicateNo = classStuds.ElementAt(ii).Value.GroupBy(o => o.no).Where(o => o.Count() > 1).Select(o => o.Key).ToList();
  2493. duplicateNo.Remove("");
  2494. duplicateNo.Remove(null);
  2495. var wrongStuds = classStuds.ElementAt(ii).Value.Where(o => duplicateNo.Contains(o.no)).Select(o => o).ToList();
  2496. impClassDuplNo.Add(classStuds.ElementAt(ii).Key, wrongStuds.Select(o => o.id).ToList());
  2497. wrongStuds.ForEach(o => { classStuds.ElementAt(ii).Value.Remove(o); nonexistentIds.Remove(o.id); });
  2498. classStuds[classStuds.ElementAt(ii).Key] = classStuds.ElementAt(ii).Value;
  2499. }
  2500. //查詢欲加入的教室資訊。
  2501. var classInfo = await getClassInfoUseId(_azureCosmos, _dingDing, _option, schoolId, classStuds.Keys.ToList());
  2502. //準備查詢db資料
  2503. Container cosmosContainer = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student");
  2504. //查要移除教室或是沒加入教室的學生
  2505. foreach (var item in classStuds)
  2506. {
  2507. //如果沒有任何學生要更新,則跳過該間教室。
  2508. if (item.Value.Count == 0) continue;
  2509. string classId = null, className = null, classNo = null, gradeId = null, periodId = null;
  2510. //如果教室不存在的話(填錯教室之類的狀況),則記錄教室的id及學生id。
  2511. if (classInfo.ContainsKey(item.Key))
  2512. {
  2513. classId = item.Key;
  2514. className = classInfo[item.Key].GetProperty("name").GetString();
  2515. classNo = classInfo[item.Key].GetProperty("no").GetString();
  2516. //gradeId = classInfo[item.Key].GetProperty("gradeId").GetString(); 此欄位已不使用
  2517. periodId = classInfo[item.Key].GetProperty("periodId").GetString();
  2518. }
  2519. else if (item.Key.Length == 0)
  2520. {
  2521. }
  2522. else
  2523. {
  2524. //沒查到有該間教室的資訊,故將該間教室的ID及學生資料清單記起來,並且跳過不處理該資料。
  2525. errorClassId.Add(item.Key);
  2526. item.Value.ForEach(o => nonexistentIds.Remove(o.id));
  2527. continue;
  2528. }
  2529. //檢查座號是否有重複
  2530. //若只是改基本資料,該處還是會查到相同的座號。
  2531. var sutdNos = item.Value.Select(o => o.no).ToList();
  2532. var existNos = await checkStudNo(_azureCosmos, _dingDing, _option, schoolId, item.Key, sutdNos);
  2533. //更新並寫入學生資料
  2534. if (item.Value.Count != 0)
  2535. {
  2536. //查學生的基本資料(該間教室全部的學生)
  2537. string queryText = $"SELECT * FROM c WHERE c.id IN ({string.Join(",", item.Value.Select(o => $"'{o.id}'"))})";
  2538. List<JsonElement> listStudent = new List<JsonElement>();
  2539. await foreach (var responseItem in cosmosContainer
  2540. .GetItemQueryStreamIteratorSql(
  2541. queryText: queryText,
  2542. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  2543. {
  2544. using var json = await JsonDocument.ParseAsync(responseItem.Content);
  2545. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2546. {
  2547. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  2548. while (accounts.MoveNext())
  2549. {
  2550. JsonElement account = accounts.Current;
  2551. string id = $"{account.GetProperty("id")}";
  2552. nonexistentIds.Remove(id);
  2553. //舊的座號,基本上不會重複,但可能會是空的
  2554. string no = $"{account.GetProperty("no")}";
  2555. account.TryGetProperty("irs", out JsonElement irsjson);
  2556. string irs = $"{irsjson}";
  2557. //用來記錄最後更改完的資料
  2558. (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
  2559. = (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,
  2560. studentInfos[id].irs, studentInfos[id].imei, studentInfos[id].guardians);
  2561. bool isUpPwDone = false;
  2562. bool isWrong = false;
  2563. //開始組Json
  2564. using var memoryStream = new MemoryStream();
  2565. using var writer = new Utf8JsonWriter(memoryStream);
  2566. writer.WriteStartObject();
  2567. foreach (var element in account.EnumerateObject())
  2568. {
  2569. if (isWrong) break;
  2570. switch (true)
  2571. {
  2572. case bool _ when element.Name.Equals("name", StringComparison.Ordinal):
  2573. if (string.IsNullOrWhiteSpace(studentInfos[id].name))
  2574. {
  2575. element.WriteTo(writer);
  2576. tmpData.name = element.Value.GetString();
  2577. }
  2578. else
  2579. {
  2580. writer.WriteString("name", studentInfos[id].name);
  2581. }
  2582. break;
  2583. case bool _ when element.Name.Equals("pw", StringComparison.Ordinal):
  2584. case bool _ when element.Name.Equals("salt", StringComparison.Ordinal):
  2585. if (!isUpPwDone && !string.IsNullOrWhiteSpace(studentInfos[id].salt) && !string.IsNullOrWhiteSpace(studentInfos[id].pw))
  2586. {
  2587. writer.WriteString("salt", studentInfos[id].salt);
  2588. writer.WriteString("pw", studentInfos[id].pw);
  2589. isUpPwDone = true;
  2590. }
  2591. break;
  2592. case bool _ when element.Name.Equals("periodId", StringComparison.Ordinal):
  2593. if (string.IsNullOrWhiteSpace(studentInfos[id].periodId))
  2594. {
  2595. element.WriteTo(writer);
  2596. tmpData.periodId = element.Value.GetString();
  2597. }
  2598. else
  2599. {
  2600. writer.WriteString("periodId", studentInfos[id].periodId);
  2601. }
  2602. break;
  2603. case bool _ when element.Name.Equals("gender", StringComparison.Ordinal):
  2604. if (string.IsNullOrWhiteSpace(studentInfos[id].gender))
  2605. {
  2606. element.WriteTo(writer);
  2607. tmpData.gender = element.Value.GetString();
  2608. }
  2609. else
  2610. {
  2611. writer.WriteString("gender", studentInfos[id].gender);
  2612. }
  2613. break;
  2614. case bool _ when element.Name.Equals("year", StringComparison.Ordinal):
  2615. if (studentInfos[id].year == 0)
  2616. {
  2617. element.WriteTo(writer);
  2618. tmpData.year = element.Value.GetInt32();
  2619. }
  2620. else
  2621. {
  2622. writer.WriteNumber("year", studentInfos[id].year);
  2623. }
  2624. break;
  2625. case bool _ when element.Name.Equals("classId", StringComparison.Ordinal):
  2626. if (studentInfos[id].classId != null && studentInfos[id].classId.Length == 0)
  2627. {
  2628. writer.WriteNull("classId");
  2629. writer.WriteNull("groupId");
  2630. writer.WriteNull("groupName");
  2631. tmpData.classId = null;
  2632. }
  2633. else if (string.IsNullOrWhiteSpace(studentInfos[id].classId))
  2634. {
  2635. element.WriteTo(writer);
  2636. tmpData.classId = element.Value.GetString();
  2637. }
  2638. else
  2639. {
  2640. writer.WriteString("classId", studentInfos[id].classId);
  2641. }
  2642. break;
  2643. case bool _ when element.Name.Equals("no", StringComparison.Ordinal):
  2644. //移除座號的話會給空的
  2645. if (studentInfos[id].no != null && studentInfos[id].no.Length == 0)
  2646. {
  2647. writer.WriteNull("no");
  2648. tmpData.no = null;
  2649. }
  2650. else if (string.IsNullOrWhiteSpace(studentInfos[id].no))
  2651. {
  2652. element.WriteTo(writer);
  2653. tmpData.no = element.Value.GetString();
  2654. //#2769 C343 学生管理--导入学生名单,IRS编号默认与座号一致
  2655. tmpData.irs = element.Value.GetString();
  2656. }
  2657. else
  2658. {
  2659. //如果要更新的座號,跟已存在的座號相同,則不進行更新。
  2660. //沒有設定過舊no,或舊座號與新座號不同,則要進行重複座號的檢查。 舊no=null or 舊no!=新no
  2661. //if (string.IsNullOrWhiteSpace(no) || (!string.IsNullOrWhiteSpace(no) && !no.Equals(studentInfos[id].no)))
  2662. //{
  2663. // //如果有檢查到新座號和舊座號重複
  2664. // if (existNos.Any(o => o.Item2.Contains(studentInfos[id].no))) //.Contains(studentInfos[id].no))
  2665. // {
  2666. // if (errorNos.ContainsKey(id))
  2667. // {
  2668. // errorNos[id].Add(studentInfos[id].no);
  2669. // }
  2670. // else
  2671. // {
  2672. // errorNos.Add(id, new List<string>() { studentInfos[id].no });
  2673. // }
  2674. // isWrong = true;
  2675. // break;
  2676. // }
  2677. //}
  2678. writer.WriteString("no", studentInfos[id].no);
  2679. //#2769 C343 学生管理--导入学生名单,IRS编号默认与座号一致
  2680. writer.WriteString("irs", studentInfos[id].no);
  2681. }
  2682. break;
  2683. //case bool _ when element.Name.Equals("irs", StringComparison.Ordinal):
  2684. // //移除座號的話會給空的
  2685. // if (studentInfos[id].irs != null && studentInfos[id].irs.Length == 0)
  2686. // {
  2687. // writer.WriteNull("irs");
  2688. // tmpData.irs = null;
  2689. // }
  2690. // else if (string.IsNullOrWhiteSpace(studentInfos[id].irs))
  2691. // {
  2692. // element.WriteTo(writer);
  2693. // tmpData.irs = element.Value.GetString();
  2694. // }
  2695. // else
  2696. // {
  2697. // writer.WriteString("irs", studentInfos[id].irs);
  2698. // }
  2699. // break;
  2700. case bool _ when element.Name.StartsWith("_", StringComparison.Ordinal):
  2701. break;
  2702. default:
  2703. element.WriteTo(writer);
  2704. break;
  2705. }
  2706. }
  2707. var stu = account.Deserialize<Student>();
  2708. if (stu.guardians.IsNotEmpty() && studentInfos[id].guardians != null)
  2709. {
  2710. var mobiles = stu.guardians.Select(m => m.mobile);
  2711. var except = mobiles.Except(studentInfos[id].guardians.Select(x => x.mobile));
  2712. if (except.Any())
  2713. {
  2714. //清除移除的监护人
  2715. List<Guardian> guardians = new List<Guardian>();
  2716. string sql = $"select distinct value (c) from c where c.mobile in ({string.Join(",", except.Select(z => $"'{z}'"))} )";
  2717. await foreach (var guard in cosmosContainer.GetItemQueryIteratorSql<Guardian>(queryText: sql,
  2718. requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base-Guardian") }))
  2719. {
  2720. guard.students.RemoveAll(s => s.id.Equals(id) && s.code.Equals(schoolId));
  2721. guardians.Add(guard);
  2722. }
  2723. guardians.ForEach(async x =>
  2724. {
  2725. if (x.students.IsNotEmpty())
  2726. {
  2727. try { await cosmosContainer.ReplaceItemAsync(x, x.id, new PartitionKey(x.code)); } catch { }
  2728. }
  2729. else
  2730. {
  2731. try
  2732. {
  2733. await cosmosContainer.DeleteItemStreamAsync(x.id, new PartitionKey(x.code));
  2734. }
  2735. catch
  2736. {
  2737. }
  2738. }
  2739. });
  2740. }
  2741. }
  2742. if (studentInfos[id].guardians.IsNotEmpty())
  2743. {
  2744. foreach (var gtudentGuardian in studentInfos[id].guardians)
  2745. {
  2746. List<Guardian> guardians = new List<Guardian>();
  2747. string sql = $"select distinct value (c) from c where c.mobile='{gtudentGuardian.mobile}' ";
  2748. await foreach (var guard in cosmosContainer.GetItemQueryIteratorSql<Guardian>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base-Guardian") }))
  2749. {
  2750. guardians.Add(guard);
  2751. }
  2752. if (guardians.Any())
  2753. {
  2754. guardians.ForEach(async x =>
  2755. {
  2756. GuardianStudent guardianStudent = x.students.Find(s => s.id.Equals(id) && s.code.Equals(schoolId));
  2757. if (guardianStudent == null)
  2758. {
  2759. x.students.Add(new GuardianStudent { relation = gtudentGuardian.relation, type = 2, id = id, code = schoolId, name = studentInfos[id].name });
  2760. }
  2761. try { await cosmosContainer.ReplaceItemAsync(x, x.id, new PartitionKey(x.code)); } catch { }
  2762. });
  2763. }
  2764. else
  2765. {
  2766. Guardian guardian = new Guardian
  2767. {
  2768. id = Guid.NewGuid().ToString(),
  2769. code = "Base-Guardian",
  2770. pk = "Guardian",
  2771. mobile = gtudentGuardian.mobile,
  2772. name = gtudentGuardian.name,
  2773. students = new List<GuardianStudent> { new GuardianStudent { relation = gtudentGuardian.relation, type = 2, id = id, code = schoolId, name = studentInfos[id].name } }
  2774. };
  2775. try { await cosmosContainer.CreateItemAsync(guardian, new PartitionKey(guardian.code)); } catch { }
  2776. }
  2777. }
  2778. writer.WriteStartArray("guardians");
  2779. foreach (var guardian in studentInfos[id].guardians)
  2780. {
  2781. writer.WriteStartObject();
  2782. writer.WriteString("relation", guardian.relation);
  2783. writer.WriteString("name", guardian.name);
  2784. writer.WriteString("mobile", guardian.mobile);
  2785. writer.WriteString("mail", guardian.mail);
  2786. writer.WriteString("picture", guardian.picture);
  2787. writer.WriteString("tmdid", guardian.tmdid);
  2788. writer.WriteEndObject();
  2789. }
  2790. writer.WriteEndArray();
  2791. }
  2792. else
  2793. {
  2794. writer.WriteStartArray("guardians");
  2795. //writer.WriteStartObject();
  2796. //writer.WriteEndObject();
  2797. writer.WriteEndArray();
  2798. }
  2799. //如果有錯誤,如座號重覆等,就會跳過該次更新。
  2800. if (isWrong)
  2801. {
  2802. await writer.DisposeAsync();
  2803. continue;
  2804. }
  2805. //#2769 C343 学生管理--导入学生名单,IRS编号默认与座号一致
  2806. //if (!account.TryGetProperty("irs", out JsonElement _irs) || _irs.ValueKind.Equals(JsonValueKind.Undefined))
  2807. //{
  2808. // writer.WriteString("irs", studentInfos[id].irs);
  2809. //}
  2810. writer.WriteString("irs", studentInfos[id].no);
  2811. //若密碼和鹽沒有更新,就把舊的資料寫回去
  2812. if (!isUpPwDone)
  2813. {
  2814. writer.WriteString("salt", account.GetProperty("salt").GetString());
  2815. writer.WriteString("pw", account.GetProperty("pw").GetString());
  2816. }
  2817. writer.WriteEndObject();
  2818. writer.Flush();
  2819. //编辑是是否要明确清除电子学生证。
  2820. await upsertImei(id, studentInfos[id].imei, schoolId, "clean", _azureCosmos
  2821. .GetCosmosClient()
  2822. .GetContainer(Constant.TEAMModelOS, "Student"));
  2823. try
  2824. {
  2825. var ret = await cosmosContainer.ReplaceItemStreamAsync(memoryStream, id, new PartitionKey($"Base-{schoolId}"));
  2826. //將更新完的id從字典內移除,保留沒查到的。
  2827. if (ret.StatusCode ==HttpStatusCode.OK)
  2828. {
  2829. nonexistentIds.Remove(id);
  2830. 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 });
  2831. }
  2832. else errorIds.Add(id);
  2833. }
  2834. catch (CosmosException ex)
  2835. {
  2836. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/updateStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2837. errorIds.Add(id);
  2838. }
  2839. catch (Exception ex)
  2840. {
  2841. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/updateStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2842. errorIds.Add(id);
  2843. }
  2844. }
  2845. }
  2846. //將輸入不存在的資料移除。
  2847. // nonexistentIds.ForEach(o => studentInfos.Remove(o));
  2848. }
  2849. }
  2850. }
  2851. errorClassId.ForEach(o => impClassDuplNo.Remove(o));
  2852. return (retStuds, impClassDuplNo.Where(o => o.Value.Count != 0).ToDictionary(o => o.Key, o => o.Value), nonexistentIds, errorIds, errorNos, errorClassId);
  2853. }
  2854. catch (CosmosException ex)
  2855. {
  2856. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/updateStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2857. }
  2858. catch (Exception ex)
  2859. {
  2860. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/updateStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2861. }
  2862. return (null, null, null, null, null, null);
  2863. }
  2864. /// <summary>
  2865. /// 創建學生帳號,目前SDK4.0預覽版還不支援批量創建(TransactionalBatch),待SDK正式發行時在優化此代碼。
  2866. /// </summary>
  2867. /// <param name="userStudents"></param>
  2868. /// <returns>已存在的ID</returns>
  2869. private async Task<(bool isSuc, List<string> existId)> createStudents(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, List<Student> userStudents)
  2870. {
  2871. var existId = new List<string>();
  2872. var exceptions = new List<Exception>();
  2873. try
  2874. {
  2875. var container = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student");
  2876. Parallel.ForEach(userStudents, async item =>
  2877. {
  2878. try
  2879. {
  2880. await container.CreateItemAsync(item);
  2881. }
  2882. catch (CosmosException ex)
  2883. {
  2884. if (ex.StatusCode == HttpStatusCode.Conflict) existId.Add(item.id);
  2885. else exceptions.Add(ex);
  2886. }
  2887. catch (Exception ex)
  2888. {
  2889. exceptions.Add(ex);
  2890. }
  2891. });
  2892. if (exceptions.Count == 0) return (true, existId);
  2893. else if (exceptions.Count > 1) throw new AggregateException(exceptions);
  2894. else if (exceptions.Count == 1) throw exceptions.Single();
  2895. }
  2896. catch (AggregateException ex)
  2897. {
  2898. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2899. }
  2900. catch (Exception ex)
  2901. {
  2902. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2903. }
  2904. return (false, existId);
  2905. }
  2906. /// <summary>
  2907. /// 取得該教室的學生座號,若有給座號LIST,則座號存在才會被查到;反之,若沒給則會將該間教室所有座號抓出來。
  2908. /// </summary>
  2909. /// <param name="schoolId"></param>
  2910. /// <param name="classId"></param>
  2911. /// <param name="nos"></param>
  2912. /// <returns></returns>
  2913. public static async Task<List<(string id, string no)>> checkStudNo(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, string classId, List<string> nos = null)
  2914. {
  2915. List<(string id, string no)> ret = new List<(string id, string no)>();
  2916. string queryText = $"SELECT c.id, c.no FROM c WHERE c.classId = '{classId}' AND c.code = 'Base-{schoolId}'";
  2917. if (nos != null) queryText += $"AND c.no IN ({string.Join(",", nos.Select(o => $"'{o}'"))})";
  2918. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student")
  2919. .GetItemQueryStreamIteratorSql(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  2920. {
  2921. using var json = await JsonDocument.ParseAsync(item.Content);
  2922. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2923. {
  2924. var classInfos = json.RootElement.GetProperty("Documents").EnumerateArray();
  2925. while (classInfos.MoveNext())
  2926. {
  2927. JsonElement account = classInfos.Current;
  2928. string id = account.GetProperty("id").GetString();
  2929. string no = account.GetProperty("no").GetString();
  2930. ret.Add((id, no));
  2931. }
  2932. }
  2933. }
  2934. return ret;
  2935. }
  2936. /// <summary>
  2937. /// 取得年級資訊
  2938. /// </summary>
  2939. /// <param name="schoolId"></param>
  2940. /// <returns>Key:periodId Vaule:list gradeInfo</returns>
  2941. public static async Task<Dictionary<string, List<(int gradeId, string gradeName)>>> getGrades(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId)
  2942. {
  2943. try
  2944. {
  2945. //Key:學制 Value:年級資訊list
  2946. Dictionary<string, List<(int gradeId, string gradeName)>> dicPeriod = new Dictionary<string, List<(int gradeId, string gradeName)>>();
  2947. var response = await _azureCosmos
  2948. .GetCosmosClient()
  2949. .GetContainer(Constant.TEAMModelOS, "School")
  2950. .ReadItemStreamAsync(schoolId, new PartitionKey("Base"));
  2951. if (response.StatusCode != HttpStatusCode.OK) return null;
  2952. using Stream stream = response.Content;
  2953. var jsonDoc = await JsonDocument.ParseAsync(stream);
  2954. var emumObject = jsonDoc.RootElement.EnumerateObject();
  2955. var period = jsonDoc.RootElement.GetProperty("period").EnumerateArray();
  2956. while (period.MoveNext())
  2957. {
  2958. List<(int gradeId, string gradeName)> gradeInfos = new List<(int gradeId, string gradeName)>();
  2959. JsonElement jsonPeriod = period.Current;
  2960. var periodId = jsonPeriod.GetProperty("id").GetString();
  2961. var grades = jsonPeriod.GetProperty("grades").ToObject<List<string>>();
  2962. for (int index = 0; index < grades.Count; index++)
  2963. {
  2964. gradeInfos.Add((index, grades[index]));
  2965. }
  2966. //var grades = jsonPeriod.GetProperty("grades").EnumerateArray();
  2967. //while (grades.MoveNext())
  2968. //{
  2969. // JsonElement grade = grades.Current;
  2970. // var gradeId = grade.GetInt32();
  2971. // var gradeName = grade.GetProperty("name").GetString();
  2972. // gradeInfos.Add((gradeId, gradeName));
  2973. //}
  2974. dicPeriod.Add(periodId, gradeInfos);
  2975. }
  2976. return dicPeriod;
  2977. }
  2978. catch (Exception ex)
  2979. {
  2980. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getGrades()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2981. return null;
  2982. }
  2983. }
  2984. public struct studCreateInfo
  2985. {
  2986. public studCreateInfo(string id, string name, string gender, int year, string pw, string classId, string no, string periodId, string imei, List<StudentGuardian> guardians)
  2987. {
  2988. this.id = id;
  2989. this.name = name;
  2990. this.gender = gender;
  2991. this.year = year;
  2992. this.pw = pw;
  2993. this.classId = classId;
  2994. this.no = no;
  2995. this.periodId = periodId;
  2996. this.imei = imei;
  2997. this.guardians = guardians;
  2998. }
  2999. public string id { get; }
  3000. public string name { get; }
  3001. public string gender { get; }
  3002. public int year { get; }
  3003. public string pw { get; }
  3004. public string classId { get; }
  3005. public string no { get; }
  3006. public string periodId { get; set; }
  3007. public string imei { get; set; }
  3008. public List<StudentGuardian> guardians { get; set; }
  3009. }
  3010. }
  3011. }