StudentService.cs 168 KB

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