StudentService.cs 161 KB

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