StudentService.cs 177 KB

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