StudentService.cs 121 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216
  1. using Azure;
  2. using Azure.Cosmos;
  3. using Azure.Messaging.ServiceBus;
  4. using HTEXLib.COMM.Helpers;
  5. using Microsoft.Extensions.Configuration;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Net;
  11. using System.Text;
  12. using System.Text.Json;
  13. using System.Threading.Tasks;
  14. using TEAMModelOS.Models;
  15. using TEAMModelOS.SDK.DI;
  16. using TEAMModelOS.SDK.Extension;
  17. using TEAMModelOS.SDK.Models;
  18. namespace TEAMModelOS.SDK
  19. {
  20. public class StudentService
  21. {
  22. /// <summary>
  23. ///
  24. /// </summary>
  25. /// <param name="schoolId"></param>
  26. /// <param name="students"></param>
  27. /// <returns></returns>
  28. public static async Task<List<Student>> GeStudentData(AzureCosmosFactory _azureCosmos, string schoolId, IEnumerable<string> students)
  29. {
  30. List<Student> studentDatas = new List<Student>();
  31. if (students.Any())
  32. {
  33. string queryText = $"SELECT c.id, c.code ,c.classId FROM c WHERE c.id IN ({string.Join(",", students.Select(o => $"'{o}'"))})";
  34. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  35. {
  36. studentDatas.Add(item);
  37. }
  38. }
  39. return studentDatas;
  40. }
  41. /// <summary>
  42. ///
  43. /// </summary>
  44. /// <param name="schoolId">学校编码</param>
  45. /// <param name="students">前端要修改的学生</param>
  46. /// <param name="opt">操作</param>
  47. /// <param name="prestudents">变更前的学生</param>
  48. /// <returns></returns>
  49. public static async Task<Dictionary<string, GroupChange>> CheckStudent(AzureServiceBusFactory _serviceBus, IConfiguration _configuration, AzureCosmosFactory _azureCosmos, string schoolId, List<Student> students, List<Student> prestudents)
  50. {
  51. List<Student> aftstudents = await StudentService.GeStudentData(_azureCosmos, schoolId, students?.Select(x => x.id));
  52. Dictionary<string, GroupChange> dictChange = new Dictionary<string, GroupChange>();
  53. if (prestudents.Count >= aftstudents.Count)
  54. {
  55. foreach (var pstu in prestudents)
  56. {
  57. var afstu = aftstudents.Find(x => x.id.Equals(pstu.id));
  58. if (afstu != null)
  59. {
  60. if (string.IsNullOrEmpty(pstu.classId) && !string.IsNullOrEmpty(afstu.classId))
  61. {
  62. //则是加入的学生
  63. if (dictChange.ContainsKey(afstu.classId))
  64. {
  65. dictChange[afstu.classId].stujoin.Add(
  66. new Member
  67. {
  68. id = afstu.id,
  69. code = $"{schoolId }",
  70. type = 2
  71. });
  72. }
  73. else
  74. {
  75. GroupChange change = new GroupChange
  76. {
  77. scope = "school",
  78. school = schoolId,
  79. type = "student",
  80. originCode = schoolId,
  81. listid = afstu.classId,
  82. stujoin = new List<Member>
  83. {
  84. new Member
  85. {
  86. id= afstu.id,
  87. code= $"{schoolId}",
  88. type =2
  89. }
  90. }
  91. };
  92. dictChange.Add(afstu.classId, change);
  93. }
  94. }
  95. else if (!string.IsNullOrEmpty(pstu.classId) && string.IsNullOrEmpty(afstu.classId))
  96. {
  97. //则该学生是解除了班级状态
  98. if (dictChange.ContainsKey(pstu.classId))
  99. {
  100. dictChange[pstu.classId].stuleave.Add(
  101. new Member
  102. {
  103. id = pstu.id,
  104. code = $"{schoolId }",
  105. type = 2
  106. });
  107. }
  108. else
  109. {
  110. GroupChange change = new GroupChange
  111. {
  112. scope = "school",
  113. school = schoolId,
  114. type = "student",
  115. originCode = schoolId,
  116. listid = pstu.classId,
  117. stuleave = new List<Member>
  118. {
  119. new Member
  120. {
  121. id= pstu.id,
  122. code= $"{schoolId}",
  123. type=2
  124. }
  125. }
  126. };
  127. dictChange.Add(pstu.classId, change);
  128. }
  129. }
  130. else if (!string.IsNullOrEmpty(pstu.classId) && !string.IsNullOrEmpty(afstu.classId))
  131. {
  132. //id不同则有异动
  133. if (!pstu.classId.Equals(afstu.classId))
  134. {
  135. //则是加入的学生
  136. if (dictChange.ContainsKey(afstu.classId))
  137. {
  138. dictChange[afstu.classId].stujoin.Add(
  139. new Member
  140. {
  141. id = afstu.id,
  142. code = $"{schoolId }",
  143. type = 2
  144. });
  145. }
  146. else
  147. {
  148. GroupChange change = new GroupChange
  149. {
  150. scope = "school",
  151. school = schoolId,
  152. type = "student",
  153. originCode = schoolId,
  154. listid = afstu.classId,
  155. stujoin = new List<Member>
  156. {
  157. new Member
  158. {
  159. id= afstu.id,
  160. code= $"{schoolId}",
  161. type = 2
  162. }
  163. }
  164. };
  165. dictChange.Add(afstu.classId, change);
  166. }//则该学生是解除了班级状态
  167. if (dictChange.ContainsKey(pstu.classId))
  168. {
  169. dictChange[pstu.classId].stuleave.Add(
  170. new Member
  171. {
  172. id = pstu.id,
  173. code = $"{schoolId }",
  174. type = 2
  175. });
  176. }
  177. else
  178. {
  179. GroupChange change = new GroupChange
  180. {
  181. scope = "school",
  182. school = schoolId,
  183. type = "student",
  184. originCode = schoolId,
  185. listid = pstu.classId,
  186. stuleave = new List<Member>
  187. {
  188. new Member
  189. {
  190. id= pstu.id,
  191. code= $"{schoolId}",
  192. type= 2
  193. }
  194. }
  195. };
  196. dictChange.Add(pstu.classId, change);
  197. }
  198. }
  199. else
  200. {
  201. //相同则不管
  202. }
  203. }
  204. else
  205. {
  206. //变更前后都没绑定班级则不管。
  207. }
  208. }
  209. else
  210. {
  211. if (!string.IsNullOrEmpty(pstu.classId))
  212. {
  213. //则该学生是被删除的学生
  214. if (dictChange.ContainsKey(pstu.classId))
  215. {
  216. dictChange[pstu.classId].stuleave.Add(
  217. new Member
  218. {
  219. id = pstu.id,
  220. code = $"Base-{schoolId }",
  221. type = 2
  222. });
  223. }
  224. else
  225. {
  226. GroupChange change = new GroupChange
  227. {
  228. scope = "school",
  229. school = schoolId,
  230. type = "student",
  231. originCode = schoolId,
  232. listid = pstu.classId,
  233. stuleave = new List<Member>
  234. {
  235. new Member
  236. {
  237. id= pstu.id,
  238. code= $"{schoolId}",
  239. type = 2
  240. }
  241. }
  242. };
  243. dictChange.Add(pstu.classId, change);
  244. }
  245. }
  246. }
  247. }
  248. }
  249. else
  250. {
  251. foreach (var afstu in aftstudents)
  252. {
  253. var pstu = prestudents.Find(x => x.id.Equals(afstu.id));
  254. if (pstu != null)
  255. {
  256. if (string.IsNullOrEmpty(pstu.classId) && !string.IsNullOrEmpty(afstu.classId))
  257. {
  258. //则是加入的学生
  259. if (dictChange.ContainsKey(afstu.classId))
  260. {
  261. dictChange[afstu.classId].stujoin.Add(
  262. new Member
  263. {
  264. id = afstu.id,
  265. code = $"{schoolId }",
  266. type = 2
  267. });
  268. }
  269. else
  270. {
  271. GroupChange change = new GroupChange
  272. {
  273. scope = "school",
  274. school = schoolId,
  275. type = "student",
  276. originCode = schoolId,
  277. listid = afstu.classId,
  278. stujoin = new List<Member>
  279. {
  280. new Member
  281. {
  282. id= afstu.id,
  283. code= $"Base-{schoolId}",
  284. type = 2
  285. }
  286. }
  287. };
  288. dictChange.Add(afstu.classId, change);
  289. }
  290. }
  291. else if (!string.IsNullOrEmpty(pstu.classId) && string.IsNullOrEmpty(afstu.classId))
  292. {
  293. //则该学生是解除了班级状态
  294. if (dictChange.ContainsKey(pstu.classId))
  295. {
  296. dictChange[pstu.classId].stuleave.Add(
  297. new Member
  298. {
  299. id = pstu.id,
  300. code = $"{schoolId }",
  301. type = 2
  302. });
  303. }
  304. else
  305. {
  306. GroupChange change = new GroupChange
  307. {
  308. scope = "school",
  309. school = schoolId,
  310. type = "student",
  311. originCode = schoolId,
  312. listid = pstu.classId,
  313. stuleave = new List<Member>
  314. {
  315. new Member
  316. {
  317. id= pstu.id,
  318. code= $"{schoolId}",
  319. type= 2
  320. }
  321. }
  322. };
  323. dictChange.Add(pstu.classId, change);
  324. }
  325. }
  326. else if (!string.IsNullOrEmpty(pstu.classId) && !string.IsNullOrEmpty(afstu.classId))
  327. {
  328. //id不同则有异动
  329. if (!pstu.classId.Equals(afstu.classId))
  330. {
  331. //则是加入的学生
  332. if (dictChange.ContainsKey(afstu.classId))
  333. {
  334. dictChange[afstu.classId].stujoin.Add(
  335. new Member
  336. {
  337. id = afstu.id,
  338. code = $"{schoolId }",
  339. type = 2
  340. });
  341. }
  342. else
  343. {
  344. GroupChange change = new GroupChange
  345. {
  346. scope = "school",
  347. school = schoolId,
  348. type = "student",
  349. originCode = schoolId,
  350. listid = afstu.classId,
  351. stujoin = new List<Member>
  352. {
  353. new Member
  354. {
  355. id= afstu.id,
  356. code= $"{schoolId}",
  357. type = 2
  358. }
  359. }
  360. };
  361. dictChange.Add(afstu.classId, change);
  362. }//则该学生是解除了班级状态
  363. if (dictChange.ContainsKey(pstu.classId))
  364. {
  365. dictChange[pstu.classId].stuleave.Add(
  366. new Member
  367. {
  368. id = pstu.id,
  369. code = $"{schoolId }",
  370. type = 2
  371. });
  372. }
  373. else
  374. {
  375. GroupChange change = new GroupChange
  376. {
  377. scope = "school",
  378. school = schoolId,
  379. type = "student",
  380. originCode = schoolId,
  381. listid = pstu.classId,
  382. stuleave = new List<Member>
  383. {
  384. new Member
  385. {
  386. id= pstu.id,
  387. code= $"{schoolId}",
  388. type=2
  389. }
  390. }
  391. };
  392. dictChange.Add(pstu.classId, change);
  393. }
  394. }
  395. else
  396. {
  397. //相同则不管
  398. }
  399. }
  400. else
  401. {
  402. //变更前后都没绑定班级则不管。
  403. }
  404. }
  405. else
  406. {
  407. if (!string.IsNullOrEmpty(afstu.classId))
  408. {
  409. //代表学生是新增的
  410. if (dictChange.ContainsKey(afstu.classId))
  411. {
  412. dictChange[afstu.classId].stujoin.Add(
  413. new Member
  414. {
  415. id = afstu.id,
  416. code = $"{schoolId }",
  417. type = 2
  418. });
  419. }
  420. else
  421. {
  422. GroupChange change = new GroupChange
  423. {
  424. scope = "school",
  425. school = schoolId,
  426. type = "student",
  427. originCode = schoolId,
  428. listid = afstu.classId,
  429. stujoin = new List<Member>
  430. {
  431. new Member
  432. {
  433. id= afstu.id,
  434. code= $"{schoolId}",
  435. type = 2
  436. }
  437. }
  438. };
  439. dictChange.Add(afstu.classId, change);
  440. }
  441. }
  442. }
  443. }
  444. }
  445. foreach (var changed in dictChange.Keys)
  446. {
  447. var change = dictChange[changed];
  448. if (change.stujoin.Count != 0 || change.stuleave.Count != 0)
  449. {
  450. var messageChange = new ServiceBusMessage(change.ToJsonString());
  451. messageChange.ApplicationProperties.Add("name", "GroupChange");
  452. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  453. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
  454. }
  455. }
  456. return dictChange;
  457. }
  458. public record StudentInfo
  459. {
  460. public string studentId { get; set; }
  461. public string picture { get; set; }
  462. public string name { get; set; }
  463. public string mobile { get; set; }
  464. public string mail { get; set; }
  465. /// <summary>
  466. /// f女性 m男性 n 保密
  467. /// </summary>
  468. public string gender { get; set; }
  469. }
  470. /// <summary>
  471. /// 整理前端匯入的學生資訊
  472. /// </summary>
  473. /// <param name="schoolId"></param>
  474. /// <param name="students"></param>
  475. /// <returns></returns>
  476. private static (Dictionary<string, (string name, string no, int year, string salt, string pw, string classNo, string className, string periodId, int classYear)> studs,
  477. Dictionary<string, (string className, string periodId, int year, string no)> classInfo,
  478. Dictionary<string, List<(string id, string no)>> classStudNo,
  479. List<string> errorYear,
  480. List<string> duplId) doSortImpStuds(string schoolId, JsonElement.ArrayEnumerator students)
  481. {
  482. //批量匯入 檢查輸入數據 確認座號 確認教室(創建教室) 確認學生存不存在或是要不要更新
  483. //存放輸入的學生資訊 key:stud id value:學生詳細資料
  484. Dictionary<string, (string name, string no, int year, string salt, string pw, string classNo, string className, string periodId, int classYear)> dicStuds =
  485. new Dictionary<string, (string name, string no, int year, string salt, string pw, string classNo, string className, string periodId, int classYear)>();
  486. //存放教室資訊用 key:classNo value:className
  487. Dictionary<string, (string className, string periodId, int year, string classNo)> dicClassInfo = new Dictionary<string, (string className, string periodId, int year, string classNo)>();
  488. //存放欲加入該間教室的學生座號清單 key:classNo value:no list
  489. Dictionary<string, List<(string id, string no)>> dicClassStudNo = new Dictionary<string, List<(string id, string no)>>();
  490. //存放輸入id重複
  491. List<string> duplId = new List<string>();
  492. List<string> errorYear = new List<string>();
  493. while (students.MoveNext())
  494. {
  495. //string id = null, no = null, name = null, year = null, pw = null, classNo = null, className = null;
  496. JsonElement student = students.Current;
  497. //ClassNo內的座號
  498. //欲加入的教室
  499. //查學生
  500. //該間教室的座號與目前欲更新的是否有重複 有些可能是同教室換座號 反正都要將學生讀出來
  501. //舊學生完整資料+新學生資料
  502. //進行輸入資料的整理
  503. if (student.TryGetProperty("id", out var tmpId))
  504. {
  505. string id = tmpId.GetString();
  506. //如果id欄位是空的,則跳過該筆資料
  507. if (string.IsNullOrWhiteSpace(id)) continue;
  508. //輸入的id不應有重複
  509. if (dicStuds.ContainsKey(id))
  510. {
  511. //如果id重複,則將之從整理清單內清除
  512. duplId.Add(id);
  513. dicStuds.Remove(id);
  514. }
  515. (string name, string no, int year, string salt, string pw, string classNo, string className, string periodId, int classYear) studentInfo = (null, null, 0, null, null, null, null, null, 0);
  516. if (student.TryGetProperty("name", out var tmpName) && !string.IsNullOrWhiteSpace(tmpName.GetString())) studentInfo.name = tmpName.GetString();
  517. //入學學年為必須,故若是無給值則將之紀錄並跳過該筆資料
  518. if (student.TryGetProperty("year", out var tmpYear) && !string.IsNullOrWhiteSpace(Convert.ToString(tmpYear))) studentInfo.year = tmpYear.GetInt32();
  519. else
  520. {
  521. errorYear.Add(id);
  522. continue;
  523. }
  524. //Password,若沒給則使用學號當密碼
  525. studentInfo.salt = Utils.CreatSaltString(8);
  526. studentInfo.pw = student.TryGetProperty("pw", out var tmpPw) && !string.IsNullOrWhiteSpace(tmpPw.GetString())
  527. ? Utils.HashedPassword(tmpPw.GetString(), studentInfo.salt)
  528. : Utils.HashedPassword(id, studentInfo.salt);
  529. if (student.TryGetProperty("periodId", out var tmpPeriodId) && !string.IsNullOrWhiteSpace(tmpPeriodId.GetString())) studentInfo.periodId = tmpPeriodId.GetString();
  530. // if (student.TryGetProperty("gradeIndex", out var tmpGradeIndex)) studentInfo.gradeIndex = tmpGradeIndex.GetInt32();
  531. if (student.TryGetProperty("classNo", out var tmpClassNo) && !string.IsNullOrWhiteSpace(tmpClassNo.GetString()))
  532. {
  533. studentInfo.classNo = tmpClassNo.GetString();
  534. //在新建帳號上,應要給classNo才能設定no,但是若只是已存在的帳號要進行座號更新呢? 為避免使用者出錯,故已存在的帳號也應當給classNo。
  535. if (student.TryGetProperty("no", out var tmpNo) && !string.IsNullOrWhiteSpace(tmpNo.GetString()))
  536. {
  537. studentInfo.no = tmpNo.GetString();
  538. //這邊先將該間教室欲使用到的no整理出來
  539. if (dicClassStudNo.ContainsKey(tmpClassNo.GetString())) dicClassStudNo[tmpClassNo.GetString()].Add((id, tmpNo.GetString()));
  540. else dicClassStudNo.Add(tmpClassNo.GetString(), new List<(string id, string no)>() { (id, tmpNo.GetString()) });
  541. }
  542. //有給classNo才會紀錄className,classNo屬於實體教室門牌號,全校理當只會有一個。
  543. int year = 0;
  544. if (student.TryGetProperty("classYear", out var tmpClassYear) && tmpClassYear.TryGetInt32(out int syear))
  545. {
  546. year = syear;
  547. studentInfo.classYear = syear;
  548. }
  549. if (student.TryGetProperty("className", out var tmpClassName) && !string.IsNullOrWhiteSpace(tmpClassName.GetString()))
  550. {
  551. studentInfo.className = tmpClassName.GetString();
  552. if (!dicClassInfo.ContainsKey($"{studentInfo.periodId}_{year}_{tmpClassNo.GetString()}"))
  553. { dicClassInfo.Add($"{studentInfo.periodId}_{year}_{tmpClassNo.GetString()}", (tmpClassName.GetString(), studentInfo.periodId, year, tmpClassNo.GetString())); }
  554. }
  555. }
  556. //將最後結果加到字典內
  557. dicStuds.Add(id, studentInfo);
  558. }
  559. }
  560. return (dicStuds, dicClassInfo, dicClassStudNo, errorYear, duplId);
  561. }
  562. /// <summary>
  563. /// 更新或是新增學生
  564. /// </summary>
  565. /// <param name="schoolId"></param>
  566. /// <param name="students"></param>
  567. /// <returns></returns>
  568. public static async Task<(List<object> studs, Dictionary<string, List<string>> classDuplNos, List<string> errorIds)> upsertStudents(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option,
  569. string schoolId,
  570. JsonElement.ArrayEnumerator students)
  571. {
  572. try
  573. {
  574. var sortedImpData = doSortImpStuds(schoolId, students);
  575. //var classNos = sortedImpData.classInfo.Select(o => new {key= o.Key, periodId=o.Value.periodId,index= o.Value.gradeIndex,year = o.Value.year }).ToList();
  576. //抓到教室資訊
  577. var classInfos = await getClassInfoUseNo(_azureCosmos, _dingDing, _option, schoolId, sortedImpData.classInfo);
  578. //取出已存在教室的classId,後面查座號要用。
  579. List<Task> tasks = new List<Task>();
  580. //Key:ClassNo Value:No 匯入時只有ClassNo
  581. Dictionary<string, List<(string id, string no)>> classStudNos = new Dictionary<string, List<(string id, string no)>>();
  582. //Key:ClassNo_gradeId Value:ClassId 存放教室no及id的變數
  583. 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)>();
  584. foreach (var classInfo in classInfos)
  585. {
  586. string classGradeId = classInfo.Value.gradeId;
  587. int classYear = classInfo.Value.year;
  588. classNoId.Add(classInfo.Value.no + "_" + classYear,
  589. (classInfo.Value.id, classInfo.Value.name, classInfo.Value.periodId, classGradeId, classYear));
  590. tasks.Add(
  591. Task.Run(
  592. async () =>
  593. {
  594. //(id,no)
  595. var studNo = await checkStudNo(_azureCosmos, _dingDing, _option, schoolId, classInfo.Value.id);
  596. classStudNos.Add(classInfo.Value.no + "_" + classInfo.Value.year, studNo);
  597. }));
  598. }
  599. //這邊整理出不存在的教室,之後創建新教室用(比對classNo)。
  600. //var nonexistentClassNo = classNos.Except(classInfos.Select(o => o.Key).ToList());
  601. List<string> exsitkey = new List<string>();
  602. foreach (var classInfo in classInfos)
  603. {
  604. //$"{studentInfo.periodId}_{year}_{tmpClassNo.GetString()}"
  605. var key = $"{classInfo.Value.periodId}_{classInfo.Value.year}_{classInfo.Value.no}";
  606. exsitkey.Add(key);
  607. }
  608. List<KeyValuePair<string, (string className, string periodId, int year, string no)>> nonexistentClassNo = new List<KeyValuePair<string, (string className, string periodId, int year, string no)>>();
  609. foreach (var key in sortedImpData.classInfo.Keys)
  610. {
  611. if (!exsitkey.Contains(key))
  612. {
  613. nonexistentClassNo.Add(new KeyValuePair<string, (string className, string periodId, int year, string no)>(key, sortedImpData.classInfo[key]));
  614. }
  615. }
  616. // var nonexistentClassNo = exsitkey.Except(sortedImpData.classInfo.Select(o => o.Key).ToList());
  617. if (nonexistentClassNo.Count() != 0)
  618. {
  619. var gradesInfo = await getGrades(_azureCosmos, _dingDing, _option, schoolId);
  620. foreach (var item in nonexistentClassNo)
  621. {
  622. string gradeId = string.Empty;
  623. string periodId = periodId = sortedImpData.classInfo[item.Key].periodId;
  624. int year = sortedImpData.classInfo[item.Key].year;
  625. //確認該學段存在及輸入的年級index正確(-1後大於等於0)
  626. //if (gradesInfo.ContainsKey(sortedImpData.classInfo[item].periodId) && sortedImpData.classInfo[item].gradeIndex - 1>=0)
  627. // {
  628. // periodId = sortedImpData.classInfo[item].periodId;
  629. //gradeId = gradesInfo[sortedImpData.classInfo[item].periodId][sortedImpData.classInfo[item].gradeIndex - 1].gradeId;
  630. //}
  631. //建立新教室
  632. (string classId, string classNo, string className, string periodId, string gradeId, int classYear) retCreateClassInfo =
  633. await createClassInfo(_azureCosmos, _dingDing, _option,
  634. schoolId,
  635. null,
  636. sortedImpData.classInfo[item.Key].className,
  637. sortedImpData.classInfo[item.Key].no,
  638. periodId,
  639. gradeId,
  640. year);
  641. classStudNos.Add(retCreateClassInfo.classNo + "_" + retCreateClassInfo.classYear, new List<(string id, string no)>());
  642. classNoId.Add(retCreateClassInfo.classNo + "_" + retCreateClassInfo.classYear, (retCreateClassInfo.classId, retCreateClassInfo.className, periodId, gradeId, year));
  643. }
  644. }
  645. var taskWhenAll = Task.WhenAll(tasks);
  646. taskWhenAll.Wait();
  647. //-------------------------------------------------------------------------
  648. //建立學生或是更新學生,並且要確認座號是否重複
  649. //每間教室的全部座號 欲更新的教室座號
  650. //先新建帳號若出現409則進行資料更新
  651. //紀錄有重複做號的id
  652. Dictionary<string, List<string>> duplNos = new Dictionary<string, List<string>>();
  653. List<string> errorIds = new List<string>();
  654. List<object> retStuds = new List<object>();
  655. CosmosContainer cosmosContainer = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student");
  656. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  657. //並行處理
  658. foreach (var stud in sortedImpData.studs)
  659. {
  660. //這邊一樣要確認已存在和欲加入還有欲修改的座號。
  661. //欲修改的不會有重複
  662. string classId = null;
  663. bool isContinue = false;
  664. if (!string.IsNullOrWhiteSpace(stud.Value.no) && !string.IsNullOrWhiteSpace(stud.Value.classNo))
  665. {
  666. classId = classNoId[stud.Value.classNo + "_" + stud.Value.classYear].classId;
  667. (string id, string no) existNoInfo = (null, null);
  668. //檢查要更新的座號是否已存在於雲端座號(已被其他同學使用)
  669. classStudNos[stud.Value.classNo + "_" + stud.Value.classYear].ForEach(
  670. o =>
  671. {
  672. if (o.no.Equals(stud.Value.no) && !o.id.Equals(stud.Key))
  673. {
  674. existNoInfo = (o.id, o.no);
  675. if (duplNos.ContainsKey(stud.Value.classNo)) duplNos[stud.Value.classNo].Add(stud.Key);
  676. else duplNos.Add(stud.Value.classNo, new List<string>() { stud.Key });
  677. }
  678. });
  679. //如果不是空的代表有座號重覆到,此時要再確認這個重複座號的id,是否存在於這次的更新,而且是要更新座號的。
  680. if (!string.IsNullOrWhiteSpace(existNoInfo.id))
  681. {
  682. isContinue = true;
  683. //輪巡所有匯入的學生資料,並檢查匯入的座號。
  684. sortedImpData.classStudNo[stud.Value.classNo].ForEach(
  685. o =>
  686. {
  687. if (o.id.Equals(existNoInfo.id) && !o.no.Equals(existNoInfo.no))
  688. {
  689. //可以更新該座號
  690. isContinue = false;
  691. duplNos[stud.Value.classNo].Remove(stud.Key);
  692. return;
  693. }
  694. });
  695. }
  696. }
  697. if (isContinue) continue;
  698. (string id, string name, string picture, int year, string no, string classId, string classNo, string className, string gradeId, string periodId) tmpStudInfo
  699. = (stud.Key, stud.Value.name, null, stud.Value.year, stud.Value.no, null, stud.Value.classNo, null, null, null);
  700. using var memoryStream = new MemoryStream();
  701. using var writerNew = new Utf8JsonWriter(memoryStream);
  702. writerNew.WriteStartObject();
  703. writerNew.WriteString("id", stud.Key);
  704. writerNew.WriteString("pk", $"Base");
  705. writerNew.WriteString("code", $"Base-{schoolId}");
  706. writerNew.WriteString("schoolId", schoolId);
  707. writerNew.WriteNumber("year", stud.Value.year);
  708. writerNew.WriteNumber("createTime", now);
  709. writerNew.WriteString("salt", stud.Value.salt);
  710. writerNew.WriteString("pw", stud.Value.pw);
  711. if (string.IsNullOrWhiteSpace(stud.Value.name)) writerNew.WriteNull("name");
  712. else writerNew.WriteString("name", stud.Value.name);
  713. writerNew.WriteString("gender", "M");
  714. writerNew.WriteNull("picture");
  715. writerNew.WriteNull("mail");
  716. writerNew.WriteNull("mobile");
  717. writerNew.WriteNull("country");
  718. if (!string.IsNullOrWhiteSpace(stud.Value.periodId))
  719. {
  720. writerNew.WriteString("periodId", stud.Value.periodId);
  721. }
  722. if (string.IsNullOrWhiteSpace(stud.Value.classNo)) writerNew.WriteNull("classId");
  723. else
  724. {
  725. writerNew.WriteString("classId", classId);
  726. tmpStudInfo.classId = classId;
  727. tmpStudInfo.className = classNoId[stud.Value.classNo + "_" + stud.Value.classYear].className;
  728. tmpStudInfo.gradeId = classNoId[stud.Value.classNo + "_" + stud.Value.classYear].gradeId;
  729. tmpStudInfo.periodId = classNoId[stud.Value.classNo + "_" + stud.Value.classYear].periodId;
  730. }
  731. if (string.IsNullOrWhiteSpace(stud.Value.no))
  732. {
  733. writerNew.WriteNull("no");
  734. writerNew.WriteNull("irs");
  735. }
  736. else
  737. {
  738. writerNew.WriteString("irs", stud.Value.no);
  739. writerNew.WriteString("no", stud.Value.no);
  740. };
  741. writerNew.WriteNull("groupId");
  742. writerNew.WriteNull("groupName");
  743. writerNew.WriteEndObject();
  744. writerNew.Flush();
  745. var response = await cosmosContainer.CreateItemStreamAsync(memoryStream, new PartitionKey($"Base-{schoolId}"));
  746. if (response.Status == (int)HttpStatusCode.Created)
  747. {
  748. //如果是Created則啥都不做,讓他去下面進行資料的彙整。
  749. }
  750. //查到已存在的id,則進行基本資料更新。
  751. else if (response.Status == (int)HttpStatusCode.Conflict)
  752. {
  753. try
  754. {
  755. bool isUpPwDone = false;
  756. Student student = await _azureCosmos
  757. .GetCosmosClient()
  758. .GetContainer(Constant.TEAMModelOS, "Student")
  759. .ReadItemAsync<Student>(stud.Key, new PartitionKey($"Base-{schoolId}"));
  760. if (!string.IsNullOrWhiteSpace(stud.Value.name))
  761. {
  762. student.name = stud.Value.name;
  763. }
  764. if (stud.Value.year > 0)
  765. {
  766. student.year = stud.Value.year;
  767. }
  768. if (!string.IsNullOrWhiteSpace(stud.Value.no))
  769. {
  770. student.no = stud.Value.no;
  771. }
  772. if (!string.IsNullOrWhiteSpace(stud.Value.classNo))
  773. {
  774. student.classId = classId;
  775. }
  776. if (!string.IsNullOrWhiteSpace(stud.Value.periodId))
  777. {
  778. student.periodId = stud.Value.periodId;
  779. }
  780. if (!isUpPwDone)
  781. {
  782. student.pw = stud.Value.pw;
  783. student.salt = stud.Value.salt;
  784. isUpPwDone = true;
  785. }
  786. tmpStudInfo.picture = student.picture;
  787. await cosmosContainer.ReplaceItemAsync(student, stud.Key, new PartitionKey($"Base-{schoolId}"));
  788. }
  789. catch (CosmosException ex)
  790. {
  791. errorIds.Add(stud.Key);
  792. continue;
  793. }
  794. }
  795. else
  796. {
  797. errorIds.Add(stud.Key);
  798. continue;
  799. }
  800. //整理輸出用資料
  801. retStuds.Add(
  802. new
  803. {
  804. tmpStudInfo.id,
  805. tmpStudInfo.name,
  806. tmpStudInfo.picture,
  807. tmpStudInfo.year,
  808. tmpStudInfo.no,
  809. tmpStudInfo.classId,
  810. tmpStudInfo.classNo,
  811. tmpStudInfo.className,
  812. // tmpStudInfo.gradeId,
  813. // tmpStudInfo.periodId
  814. });
  815. }
  816. return (retStuds, duplNos.Where(o => o.Value.Count != 0).ToDictionary(o => o.Key, o => o.Value), errorIds);
  817. }
  818. catch (Exception ex)
  819. {
  820. await _dingDing.SendBotMsg(
  821. $"IES5,{_option.Location},StudentController/upsertStudents()\nex:{ex.Message}\n{ex.StackTrace}",
  822. GroupNames.醍摩豆服務運維群組);
  823. }
  824. return (null, null, null);
  825. }
  826. /// <summary>
  827. /// 單純建立單一學生
  828. /// </summary>
  829. /// <param name="schoolId"></param>
  830. /// <param name="studCreateInfo"></param>
  831. public static async Task<bool> createStudent(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, studCreateInfo studCreateInfo)
  832. {
  833. try
  834. {
  835. using var stream = new MemoryStream();
  836. using var writer = new Utf8JsonWriter(stream);
  837. writer.WriteStartObject();
  838. writer.WriteString("pk", $"Base");
  839. writer.WriteString("code", $"Base-{schoolId}");
  840. writer.WriteString("id", studCreateInfo.id);
  841. if (string.IsNullOrWhiteSpace(studCreateInfo.name)) writer.WriteNull("name");
  842. else writer.WriteString("name", studCreateInfo.name);
  843. if (string.IsNullOrWhiteSpace(studCreateInfo.gender)) writer.WriteNull("gender");
  844. else writer.WriteString("gender", studCreateInfo.gender);
  845. writer.WriteString("schoolId", schoolId);
  846. //20210713 huanghb add 增加学段
  847. if (string.IsNullOrWhiteSpace(studCreateInfo.periodId)) writer.WriteNull("periodId");
  848. else writer.WriteString("periodId", studCreateInfo.periodId);
  849. writer.WriteNumber("year", studCreateInfo.year);
  850. writer.WriteNumber("createTime", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
  851. writer.WriteNull("picture");
  852. writer.WriteNull("mail");
  853. writer.WriteNull("mobile");
  854. writer.WriteNull("country");
  855. //Password,若沒給則使用學號當密碼
  856. string salt = Utils.CreatSaltString(8);
  857. string hashPw = string.IsNullOrWhiteSpace(studCreateInfo.pw)
  858. ? Utils.HashedPassword(studCreateInfo.id, salt)
  859. : Utils.HashedPassword(studCreateInfo.pw, salt);
  860. writer.WriteString("salt", salt);
  861. writer.WriteString("pw", hashPw);
  862. if (string.IsNullOrWhiteSpace(studCreateInfo.classId)) writer.WriteNull("classId");
  863. else writer.WriteString("classId", studCreateInfo.classId);
  864. if (string.IsNullOrWhiteSpace(studCreateInfo.no))
  865. {
  866. writer.WriteNull("no");
  867. writer.WriteNull("irs");
  868. }
  869. else
  870. {
  871. writer.WriteString("no", studCreateInfo.no);
  872. writer.WriteString("irs", studCreateInfo.no);
  873. }
  874. writer.WriteNull("groupId");
  875. writer.WriteNull("groupName");
  876. writer.WriteEndObject();
  877. writer.Flush();
  878. var response = await _azureCosmos
  879. .GetCosmosClient()
  880. .GetContainer(Constant.TEAMModelOS, "Student")
  881. .CreateItemStreamAsync(stream, new PartitionKey($"Base-{schoolId}"));
  882. if (response.Status == (int)HttpStatusCode.Created || response.Status == (int)HttpStatusCode.OK) return true;
  883. if (response.Status == (int)HttpStatusCode.Conflict) return false;
  884. else
  885. {
  886. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createStudent()\nCosmosDB Create response status = {response.Status}\nID:{studCreateInfo.id}", GroupNames.醍摩豆服務運維群組);
  887. return false;
  888. }
  889. }
  890. catch (Exception ex)
  891. {
  892. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createStudent()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  893. return false;
  894. }
  895. }
  896. /// <summary>
  897. /// 生成Class資料
  898. /// </summary>
  899. /// <param name="schoolId"></param>
  900. /// <param name="classId"></param>
  901. /// <param name="className"></param>
  902. /// <param name="students"></param>
  903. /// <returns></returns>
  904. private static async Task<(string classId, string classNo, string className, string periodId, string gradeId, int classYear)> createClassInfo(
  905. AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option,
  906. string schoolId, string classId, string className, string classNo, string periodId, string gradeId, int classYear)
  907. {
  908. //組Class JSON
  909. try
  910. {
  911. string cId = classId;
  912. using var memoryStream = new MemoryStream();
  913. using var writer = new Utf8JsonWriter(memoryStream);
  914. writer.WriteStartObject();
  915. writer.WriteString("pk", "Class");
  916. writer.WriteString("code", $"Class-{schoolId}");
  917. //如果classId是空的,則生成一組GUID。
  918. if (string.IsNullOrWhiteSpace(classId))
  919. {
  920. cId = Guid.NewGuid().ToString();
  921. writer.WriteString("id", cId);
  922. }
  923. else writer.WriteString("id", classId);
  924. if (string.IsNullOrWhiteSpace(classNo)) writer.WriteNull("no");
  925. else writer.WriteString("no", classNo);
  926. writer.WriteNull("x");
  927. writer.WriteNull("y");
  928. if (string.IsNullOrWhiteSpace(className)) writer.WriteNull("name");
  929. else writer.WriteString("name", className);
  930. writer.WritePropertyName("teacher");
  931. writer.WriteStartObject();
  932. writer.WriteNull("id");
  933. writer.WriteNull("name");
  934. writer.WriteEndObject();
  935. //if (string.IsNullOrWhiteSpace(gradeId)) writer.WriteNull("gradeId");
  936. //else writer.WriteString("gradeId", gradeId);
  937. if (string.IsNullOrWhiteSpace(periodId)) writer.WriteNull("periodId");
  938. else writer.WriteString("periodId", periodId);
  939. writer.WriteNumber("year", classYear);
  940. writer.WriteNumber("createTime", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
  941. writer.WriteNull("sn");
  942. writer.WriteString("style", "smart");
  943. writer.WriteString("openType", "1");
  944. writer.WriteString("scope", "school");
  945. writer.WriteEndObject();
  946. writer.Flush();
  947. var ret = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").CreateItemStreamAsync(memoryStream, new PartitionKey($"Class-{schoolId}"));
  948. if (ret.Status != (int)HttpStatusCode.Created)
  949. {
  950. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createClassInfo()\nStatus:{ret.Status}\nSchoolId:{schoolId},ClassId:{classId}", GroupNames.醍摩豆服務運維群組);
  951. }
  952. return (cId, classNo, className, periodId, gradeId, classYear);
  953. }
  954. catch (CosmosException ex)
  955. {
  956. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createClassInfo()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  957. }
  958. catch (Exception ex)
  959. {
  960. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createClassInfo()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  961. }
  962. return (null, null, null, null, null, 0);
  963. }
  964. /// <summary>
  965. /// 使用學校代碼查詢該校所有學生,並且在查詢該學生所屬的教室及座號,支援offset和limit操作已及ContinuationToken,若有ContinuationToken,則會優先使用ContinuationToken。
  966. /// </summary>
  967. /// <param name="schoolId"></param>
  968. /// <param name="byNameOrId">透過Name或Id來查,所以不會管學制、學級和教室</param>
  969. /// <param name="byPeriod"></param>
  970. /// <param name="byGrade"></param>
  971. /// <param name="byClassId"></param>
  972. /// <param name="offset"></param>
  973. /// <param name="limit"></param>
  974. /// <param name="token"></param>
  975. /// <returns></returns>
  976. private async Task<(List<object> students, string continuationToken)> getStudents(
  977. AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option,
  978. string schoolId, string byNameOrId = null, string byPeriod = null, string byGrade = null, string byClassId = null, int offset = -1, int limit = -1, string token = default)
  979. {
  980. try
  981. {
  982. //以學校學生角度去抓資料
  983. List<(string id, string name, string picture, int year)> listStudent = new List<(string id, string name, string picture, int year)>();
  984. string queryText = $"SELECT c.id, c.name, c.picture, c.year FROM c WHERE c.code = 'Base-{schoolId}'";
  985. //如果有選擇ClassId的話,則先取得該教室內的學生。
  986. List<string> searchId = new List<string>();
  987. if (!string.IsNullOrWhiteSpace(byClassId))
  988. {
  989. var classInfos = await getClassInfoUseId(_azureCosmos, _dingDing, _option, schoolId, new List<string>() { byClassId });
  990. foreach (var classInfo in classInfos)
  991. {
  992. var students = classInfo.Value.GetProperty("students").EnumerateArray();
  993. while (students.MoveNext())
  994. {
  995. JsonElement stud = students.Current;
  996. string id = stud.GetProperty("id").GetString();
  997. searchId.Add(id);
  998. }
  999. }
  1000. //將使用者過濾classId所取得的學生ID加入sql字串內
  1001. if (searchId.Count != 0)
  1002. {
  1003. queryText = $"{queryText} AND c.id IN ({string.Join(",", searchId.Select(o => $"'{o}'"))})";
  1004. }
  1005. }
  1006. //檢查是否有接續token及是否要在sql語法內多增加offset及limit
  1007. if (string.IsNullOrWhiteSpace(token))
  1008. {
  1009. token = default;
  1010. if (offset != -1 && limit != -1) queryText = $"{queryText} OFFSET {offset} LIMIT {limit}";
  1011. }
  1012. //回傳用ContinuationToken
  1013. string continuationToken = string.Empty;
  1014. //進行學生資料的查詢
  1015. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student")
  1016. .GetItemQueryStreamIterator(
  1017. queryText: queryText,
  1018. continuationToken: token,
  1019. requestOptions: new QueryRequestOptions()
  1020. { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  1021. {
  1022. continuationToken = item.GetContinuationToken();
  1023. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1024. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1025. {
  1026. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1027. while (accounts.MoveNext())
  1028. {
  1029. JsonElement account = accounts.Current;
  1030. listStudent.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString(), account.GetProperty("picture").GetString(), account.GetProperty("year").GetInt32()));
  1031. }
  1032. }
  1033. //單筆查詢上限為100條,所以查完一次即返回,並且給接續token。
  1034. break;
  1035. }
  1036. //查學生所屬的教室及座號
  1037. List<object> ret = new List<object>();
  1038. //查教室資訊,使用上面的學生id並透過子查詢查詢。
  1039. 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}'"))}))";
  1040. await foreach (Response item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
  1041. .GetItemQueryStreamIterator(
  1042. queryText: queryText,
  1043. //continuationToken: token,
  1044. requestOptions: new QueryRequestOptions()
  1045. { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  1046. {
  1047. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1048. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1049. {
  1050. var classrooms = json.RootElement.GetProperty("Documents").EnumerateArray();
  1051. while (classrooms.MoveNext())
  1052. {
  1053. JsonElement classroom = classrooms.Current;
  1054. var studs = classroom.GetProperty("students").EnumerateArray();
  1055. while (studs.MoveNext())
  1056. {
  1057. JsonElement stud = studs.Current;
  1058. string id = stud.GetProperty("id").GetString();
  1059. //整理出前端所需的資訊
  1060. var tmp = listStudent
  1061. .Where(o => o.id.Equals(id, StringComparison.Ordinal))
  1062. .Select(o =>
  1063. new
  1064. {
  1065. o.id,
  1066. o.name,
  1067. o.picture,
  1068. o.year,
  1069. no = stud.GetProperty("no").GetString(),
  1070. gradeId = classroom.GetProperty("gradeId").GetString(),
  1071. className = classroom.GetProperty("name").GetString()
  1072. });
  1073. ret.AddRange(tmp);
  1074. //刪除已整理完的ID
  1075. listStudent.RemoveAll(o => o.id.Equals(id, StringComparison.Ordinal));
  1076. }
  1077. }
  1078. }
  1079. }
  1080. var notJoinClassStuds = listStudent.Select(o =>
  1081. new
  1082. {
  1083. o.id,
  1084. o.name,
  1085. o.picture,
  1086. o.year,
  1087. no = (string)null,
  1088. gradeId = (string)null,
  1089. className = (string)null
  1090. });
  1091. ret.AddRange(notJoinClassStuds);
  1092. return (ret, continuationToken);
  1093. }
  1094. catch (CosmosException ex)
  1095. {
  1096. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1097. }
  1098. catch (Exception ex)
  1099. {
  1100. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1101. }
  1102. return (null, null);
  1103. }
  1104. /// <summary>
  1105. /// 取得該學校的所有學生。
  1106. /// </summary>
  1107. /// <param name="schoolId"></param>
  1108. /// <returns> [{id,name,picture,year,no,classId,classNo,className,gradeId,periodId},{id,name,picture,..}..]</returns>
  1109. public static async Task<List<object>> getAllStudent(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId)
  1110. {
  1111. try
  1112. {
  1113. //TODO : 進階查詢選項調整、部分地方可用並行處理
  1114. //以學校學生角度去抓資料
  1115. Dictionary<string, List<(string id, string name, string picture, int year, string no, string periodId, string irs)>> dicClassStuds = new Dictionary<string, List<(string id, string name, string picture, int year, string no, string periodId, string irs)>>();
  1116. List<(string id, string name, string picture, int year, string no, string periodId, string irs)> notJoinClassStuds = new List<(string id, string name, string picture, int year, string no, string periodId, string irs)>();
  1117. string queryText = $"SELECT c.id, c.name, c.picture, c.year, c.classId, c.no,c.irs ,c.periodId FROM c WHERE c.code = 'Base-{schoolId}'";
  1118. //回傳用ContinuationToken
  1119. string continuationToken = string.Empty;
  1120. var container = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student");
  1121. //進行學生資料的查詢 TEAMModelOS-Student
  1122. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student")
  1123. .GetItemQueryStreamIterator(
  1124. queryText: queryText,
  1125. requestOptions: new QueryRequestOptions()
  1126. { PartitionKey = new PartitionKey($"Base-{schoolId}"), MaxItemCount = -1 }))
  1127. {
  1128. continuationToken = item.GetContinuationToken();
  1129. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1130. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1131. {
  1132. List<(string id, string name, string picture, int year, string no)> students = new List<(string id, string name, string picture, int year, string no)>();
  1133. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1134. while (accounts.MoveNext())
  1135. {
  1136. JsonElement acc = accounts.Current;
  1137. string classId = acc.GetProperty("classId").GetString();
  1138. acc.TryGetProperty("irs", out JsonElement irs);
  1139. if (string.IsNullOrWhiteSpace(classId))
  1140. {
  1141. notJoinClassStuds.Add(
  1142. (
  1143. acc.GetProperty("id").GetString(),
  1144. acc.GetProperty("name").GetString(),
  1145. acc.GetProperty("picture").GetString(),
  1146. acc.GetProperty("year").GetInt32(),
  1147. acc.GetProperty("no").GetString(),
  1148. acc.TryGetProperty("periodId", out JsonElement _periodId) && _periodId.ValueKind.Equals(JsonValueKind.String) ? _periodId.GetString() : null,
  1149. $"{irs}"
  1150. )
  1151. );
  1152. }
  1153. else
  1154. {
  1155. if (dicClassStuds.ContainsKey(classId))
  1156. {
  1157. dicClassStuds[classId].Add(
  1158. (
  1159. acc.GetProperty("id").GetString(),
  1160. acc.GetProperty("name").GetString(),
  1161. acc.GetProperty("picture").GetString(),
  1162. acc.GetProperty("year").GetInt32(),
  1163. acc.GetProperty("no").GetString(), acc.TryGetProperty("periodId", out JsonElement _periodId) && _periodId.ValueKind.Equals(JsonValueKind.String) ? _periodId.GetString() : null,
  1164. $"{irs}"
  1165. )
  1166. );
  1167. }
  1168. else
  1169. {
  1170. dicClassStuds.Add(classId,
  1171. new List<(string id, string name, string picture, int year, string no, string periodId, string irs)>()
  1172. {
  1173. (
  1174. acc.GetProperty("id").GetString(),
  1175. acc.GetProperty("name").GetString(),
  1176. acc.GetProperty("picture").GetString(),
  1177. acc.GetProperty("year").GetInt32(),
  1178. acc.GetProperty("no").GetString(), acc.TryGetProperty("periodId",out JsonElement _periodId)&& _periodId.ValueKind.Equals(JsonValueKind.String) ? _periodId.GetString() : null,$"{irs}"
  1179. )
  1180. }
  1181. );
  1182. }
  1183. }
  1184. }
  1185. }
  1186. }
  1187. //查學生所屬的教室及座號
  1188. List<object> ret = new List<object>();
  1189. //查教室的資訊,用以取得gradeId,periodId資訊。
  1190. var classInfos = await getClassInfoUseId(_azureCosmos, _dingDing, _option, schoolId, dicClassStuds.Keys.ToList());
  1191. //輪循所有教室學生的資料
  1192. foreach (var classStud in dicClassStuds)
  1193. {
  1194. string classId = null, classNo = null, className = null, gradeId = null, periodId = null;
  1195. int classYear = -1;
  1196. if (classInfos.ContainsKey(classStud.Key))
  1197. {
  1198. classId = classInfos[classStud.Key].GetProperty("id").GetString();
  1199. classNo = classInfos[classStud.Key].GetProperty("no").GetString();
  1200. className = classInfos[classStud.Key].GetProperty("name").GetString();
  1201. periodId = classInfos[classStud.Key].TryGetProperty("periodId", out JsonElement _periodId) && _periodId.ValueKind.Equals(JsonValueKind.String) ? _periodId.GetString() : null;
  1202. if (classInfos[classStud.Key].TryGetProperty("year", out JsonElement year))
  1203. {
  1204. if (year.ValueKind.Equals(JsonValueKind.Number))
  1205. {
  1206. classYear = classInfos[classStud.Key].GetProperty("year").GetInt32();
  1207. }
  1208. }
  1209. }
  1210. var tmp = classStud.Value.Select(o =>
  1211. new
  1212. {
  1213. o.id,
  1214. o.name,
  1215. o.picture,
  1216. o.year,
  1217. o.no,
  1218. classId,
  1219. classNo,
  1220. className,
  1221. gradeId,
  1222. periodId = string.IsNullOrEmpty(periodId) ? o.periodId : periodId,
  1223. classYear,
  1224. irs = o.irs
  1225. });
  1226. ret.AddRange(tmp);
  1227. }
  1228. //彙整沒有加入教室的學生
  1229. notJoinClassStuds.ForEach(o => ret.Add(
  1230. new
  1231. {
  1232. o.id,
  1233. o.name,
  1234. o.picture,
  1235. o.year,
  1236. o.no,
  1237. classId = (string)null,
  1238. classNo = (string)null,
  1239. className = (string)null,
  1240. gradeId = (string)null,
  1241. o.periodId,
  1242. classYear = -1,
  1243. irs = o.irs
  1244. }));
  1245. return ret;
  1246. }
  1247. catch (Exception ex)
  1248. {
  1249. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getStudents()\n{ex.Message}\n{ex.StackTrace},", GroupNames.醍摩豆服務運維群組);
  1250. }
  1251. return null;
  1252. }
  1253. /// <summary>
  1254. /// 取得該校所有教室內的名單
  1255. /// </summary>
  1256. /// <param name="schoolId"></param>
  1257. /// <returns></returns>
  1258. public async Task<Dictionary<string, JsonElement>> getClassStudent(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, string classId = null)
  1259. {
  1260. try
  1261. {
  1262. string queryText = $"SELECT VALUE FROM c WHERE c.";
  1263. //if (!string.IsNullOrWhiteSpace(classId)) queryText += $" AND c.id = '{classId}'";
  1264. Dictionary<string, JsonElement> listStudent = new Dictionary<string, JsonElement>();
  1265. await foreach (Response item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
  1266. .GetItemQueryStreamIterator(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  1267. {
  1268. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1269. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1270. {
  1271. JsonElement.ArrayEnumerator accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1272. while (accounts.MoveNext())
  1273. {
  1274. JsonElement account = accounts.Current;
  1275. string cId = account.GetProperty("id").GetString();
  1276. var students = account.GetProperty("students").Clone();
  1277. listStudent.Add(cId, students);
  1278. }
  1279. }
  1280. }
  1281. return listStudent;
  1282. }
  1283. catch (Exception ex)
  1284. {
  1285. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassStudentAsync()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1286. }
  1287. return null;
  1288. }
  1289. /// <summary>
  1290. /// 刪除學生,非透過批量刪除方法。
  1291. /// </summary>
  1292. /// <param name="schoolId"></param>
  1293. /// <param name="students"></param>
  1294. /// <returns></returns>
  1295. public static async Task<List<string>> deleteStudents(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, JsonElement.ArrayEnumerator students)
  1296. {
  1297. List<string> sucIds = new List<string>();
  1298. try
  1299. {
  1300. var exceptions = new List<Exception>();
  1301. List<GroupList> scGroupLists = new List<GroupList>();
  1302. List<GroupList> teGroupLists = new List<GroupList>();
  1303. var container = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student");
  1304. while (students.MoveNext())
  1305. {
  1306. string id = string.Empty;
  1307. try
  1308. {
  1309. JsonElement student = students.Current;
  1310. id = student.GetProperty("id").GetString();
  1311. var ret = await container.DeleteItemStreamAsync(id, new PartitionKey($"Base-{schoolId}"));
  1312. if (ret.Status == (int)HttpStatusCode.NoContent) sucIds.Add(id);
  1313. 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}") }))
  1314. {
  1315. scGroupLists.Add(item);
  1316. }
  1317. 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") }))
  1318. {
  1319. teGroupLists.Add(item);
  1320. }
  1321. if (scGroupLists.Count > 0)
  1322. {
  1323. foreach (GroupList stuList in scGroupLists)
  1324. {
  1325. for (int j = 0; j < stuList.members.Count; j++)
  1326. {
  1327. if (id.Equals(stuList.members[j].id) && stuList.members[j].code.Equals(schoolId))
  1328. {
  1329. stuList.members.RemoveAt(j);
  1330. stuList.scount -= 1;
  1331. break;
  1332. }
  1333. }
  1334. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(stuList, stuList.id, new PartitionKey(stuList.code));
  1335. }
  1336. }
  1337. if (teGroupLists.Count > 0)
  1338. {
  1339. foreach (GroupList stuList in teGroupLists)
  1340. {
  1341. for (int j = 0; j < stuList.members.Count; j++)
  1342. {
  1343. if (id.Equals(stuList.members[j].id) && stuList.members[j].code.Equals(schoolId))
  1344. {
  1345. stuList.members.RemoveAt(j);
  1346. stuList.scount -= 1;
  1347. break;
  1348. }
  1349. }
  1350. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(stuList, stuList.id, new PartitionKey(stuList.code));
  1351. }
  1352. }
  1353. }
  1354. catch (CosmosException ex)
  1355. {
  1356. exceptions.Add(ex);
  1357. }
  1358. catch (Exception ex)
  1359. {
  1360. exceptions.Add(ex);
  1361. }
  1362. }
  1363. if (exceptions.Count == 0) return sucIds;
  1364. else if (exceptions.Count > 1) throw new AggregateException(exceptions);
  1365. else if (exceptions.Count == 1) throw exceptions.Single();
  1366. }
  1367. catch (CosmosException ex)
  1368. {
  1369. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/deleteStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1370. }
  1371. catch (Exception ex)
  1372. {
  1373. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/deleteStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1374. }
  1375. return sucIds;
  1376. }
  1377. /// <summary>
  1378. /// 將學生基本資料內的classId、no、groupId及groupName清為null。
  1379. /// </summary>
  1380. /// <param name="schoolId"></param>
  1381. /// <param name="students">["id1","id2",...]</param>
  1382. /// <returns></returns>
  1383. 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)
  1384. {
  1385. //紀錄輸入的學生
  1386. List<string> impStuds = new List<string>();
  1387. //紀錄更新成功的學生
  1388. List<string> sucStuds = new List<string>();
  1389. //記錄沒查到的學生
  1390. List<string> nonexistentIds = new List<string>();
  1391. //紀錄更新出錯的學生
  1392. List<string> errorIds = new List<string>();
  1393. //整理輸入的學生資訊
  1394. while (students.MoveNext())
  1395. {
  1396. JsonElement student = students.Current;
  1397. impStuds.Add(student.GetString());
  1398. }
  1399. if (impStuds.Count == 0) return (null, null, null);
  1400. string queryText = $"SELECT VALUE c FROM c WHERE c.id IN ({string.Join(",", impStuds.Select(o => $"'{o}'"))})";
  1401. await foreach (Response item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student")
  1402. .GetItemQueryStreamIterator(
  1403. queryText: queryText,
  1404. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  1405. {
  1406. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1407. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1408. {
  1409. JsonElement.ArrayEnumerator docs = json.RootElement.GetProperty("Documents").EnumerateArray();
  1410. while (docs.MoveNext())
  1411. {
  1412. JsonElement doc = docs.Current;
  1413. doc.TryGetProperty("id", out var tmpId);
  1414. var id = tmpId.GetString();
  1415. using var stream = new MemoryStream();
  1416. using var writer = new Utf8JsonWriter(stream);
  1417. writer.WriteStartObject();
  1418. foreach (var element in doc.EnumerateObject())
  1419. {
  1420. //將教室相關欄位清空
  1421. switch (true)
  1422. {
  1423. case bool _ when element.Name.Equals("classId", StringComparison.Ordinal):
  1424. writer.WriteNull("classId");
  1425. break;
  1426. case bool _ when element.Name.Equals("no", StringComparison.Ordinal):
  1427. writer.WriteNull("no");
  1428. break;
  1429. case bool _ when element.Name.Equals("groupId", StringComparison.Ordinal):
  1430. writer.WriteNull("groupId");
  1431. break;
  1432. case bool _ when element.Name.Equals("groupName", StringComparison.Ordinal):
  1433. writer.WriteNull("groupName");
  1434. break;
  1435. case bool _ when element.Name.Equals("irs", StringComparison.Ordinal):
  1436. writer.WriteNull("irs");
  1437. break;
  1438. case bool _ when element.Name.StartsWith("_", StringComparison.Ordinal):
  1439. break;
  1440. default:
  1441. element.WriteTo(writer);
  1442. break;
  1443. }
  1444. }
  1445. writer.WriteEndObject();
  1446. writer.Flush();
  1447. var ret = await _azureCosmos
  1448. .GetCosmosClient()
  1449. .GetContainer(Constant.TEAMModelOS, "Student")
  1450. .ReplaceItemStreamAsync(stream, id, new PartitionKey($"Base-{schoolId}"));
  1451. if (ret.Status == (int)HttpStatusCode.OK)
  1452. {
  1453. sucStuds.Add(id);
  1454. }
  1455. else
  1456. {
  1457. impStuds.Remove(id);
  1458. errorIds.Add(id);
  1459. await _dingDing.SendBotMsg(
  1460. $"IES5,{_option.Location},StudentController/removeStudentClassInfo(),CosmosDB response:{ret.Status}\nBase-{schoolId},id:{id}",
  1461. GroupNames.醍摩豆服務運維群組);
  1462. }
  1463. }
  1464. }
  1465. }
  1466. //將impStuds內的資料移除sucStuds及errorIds,所得的結果就是不存在於資料庫的id。
  1467. sucStuds.ForEach(o => impStuds.Remove(o));
  1468. errorIds.ForEach(o => impStuds.Remove(o));
  1469. return (sucStuds, impStuds, errorIds);
  1470. }
  1471. /// <summary>
  1472. /// 取得教室資訊,使用classId進行查詢。
  1473. /// </summary>
  1474. /// <returns></returns>
  1475. private static async Task<Dictionary<string, JsonElement>> getClassInfoUseId(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, List<string> classIds)
  1476. {
  1477. try
  1478. {
  1479. if (!(classIds == null || classIds.Count == 0))
  1480. {
  1481. string queryText = $"SELECT * FROM c WHERE c.code = 'Class-{schoolId}' AND c.id IN ({string.Join(",", classIds.Select(o => $"'{o}'"))})";
  1482. Dictionary<string, JsonElement> dicClassInfo = new Dictionary<string, JsonElement>();
  1483. await foreach (Response item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
  1484. .GetItemQueryStreamIterator(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  1485. {
  1486. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1487. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1488. {
  1489. var classInfos = json.RootElement.GetProperty("Documents").EnumerateArray();
  1490. while (classInfos.MoveNext())
  1491. {
  1492. JsonElement account = classInfos.Current;
  1493. string id = account.GetProperty("id").GetString();
  1494. dicClassInfo.Add(id, account.Clone());
  1495. }
  1496. }
  1497. }
  1498. return dicClassInfo;
  1499. }
  1500. else return null;
  1501. }
  1502. catch (CosmosException ex)
  1503. {
  1504. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassInfoUseId()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1505. }
  1506. catch (Exception ex)
  1507. {
  1508. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassInfoUseId()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1509. }
  1510. return null;
  1511. }
  1512. /// <summary>
  1513. /// 取得教室資訊,使用classNo進行查詢。
  1514. /// </summary>
  1515. /// <returns></returns>
  1516. 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)
  1517. {
  1518. try
  1519. {
  1520. Dictionary<string, Class> dicClassInfo = new Dictionary<string, Class>();
  1521. if (!(classNos == null || classNos.Count == 0))
  1522. {
  1523. foreach (var key in classNos.Keys)
  1524. {
  1525. 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}' ";
  1526. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
  1527. .GetItemQueryIterator<Class>(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  1528. {
  1529. dicClassInfo[item.id] = item;
  1530. item.name = classNos[key].className;
  1531. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<Class>(item, item.id, new PartitionKey(item.code));
  1532. }
  1533. }
  1534. return dicClassInfo;
  1535. }
  1536. else return null;
  1537. }
  1538. catch (CosmosException ex)
  1539. {
  1540. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassInfoUseId()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1541. }
  1542. catch (Exception ex)
  1543. {
  1544. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassInfoUseId()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1545. }
  1546. return null;
  1547. }
  1548. /// <summary>
  1549. /// 批量更新學生資訊,目前支持更新姓名、密碼、座號、性別及教室id,匯入時ClassId為必填。
  1550. /// </summary>
  1551. /// <param name="schoolId"></param>
  1552. /// <param name="students"></param>
  1553. /// <returns></returns>
  1554. public static async Task<(List<object> studs, Dictionary<string, List<string>> classDuplNos, List<string> nonexistentIds, List<string> errorIds, Dictionary<string, List<string>> errorNos, List<string> errorClassId)>
  1555. updateStudents(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, JsonElement.ArrayEnumerator students)
  1556. {
  1557. try
  1558. {
  1559. //整理輸入的資料->檢查輸入資料有沒有重複座號->取得欲加入的教室資訊->查詢學生並將資料更新並寫入
  1560. //Key:id Value:學生基本資訊
  1561. var studentInfos
  1562. = new Dictionary<string, (string salt, string pw, string name, int year, string picture, string gender, string mail, string mobile, string classId, string no, string periodId, string irs)>();
  1563. //用於進行座號是否重複查詢時使用
  1564. var classStuds
  1565. = new Dictionary<string, 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)>>();
  1566. //紀錄教室"輸入"的學生座號是否有重複
  1567. var impClassDuplNo = new Dictionary<string, List<string>>();
  1568. //紀錄不存在的學生id
  1569. var nonexistentIds = new List<string>();
  1570. //紀錄跟現有雲端學生座號重複的
  1571. var errorNos = new Dictionary<string, List<string>>();
  1572. //紀錄處理錯誤的id,cosmosdb寫入時錯誤等...
  1573. var errorIds = new List<string>();
  1574. //紀錄沒找到的classId
  1575. var errorClassId = new List<string>();
  1576. //紀錄輸出結果
  1577. var retStuds = new List<object>();
  1578. //整理輸入資料
  1579. while (students.MoveNext())
  1580. {
  1581. JsonElement student = students.Current;
  1582. if (student.TryGetProperty("id", out var id))
  1583. {
  1584. //確認是否有id欄位,並且確認是否有給pw欄位,若無給或是null empty等,則使用id當密碼。
  1585. if (!string.IsNullOrWhiteSpace(id.GetString()))
  1586. {
  1587. string salt = null,
  1588. pw = null,
  1589. name = null,
  1590. gender = null,
  1591. mail = null,
  1592. mobile = null,
  1593. classId = null,
  1594. periodId = null,
  1595. irs = null,
  1596. no = null;
  1597. int year = 0;
  1598. //有給pw欄位才進行處理
  1599. if (student.TryGetProperty("pw", out var tmpPw))
  1600. {
  1601. var response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemStreamAsync(id.GetString(), new PartitionKey($"Base-{schoolId}"));
  1602. if (response.Status == 200)
  1603. {
  1604. var rjson = await JsonDocument.ParseAsync(response.ContentStream);
  1605. rjson.RootElement.TryGetProperty("salt", out JsonElement _salt);
  1606. salt = $"{_salt}";
  1607. }
  1608. if (string.IsNullOrWhiteSpace(salt))
  1609. {
  1610. salt = Utils.CreatSaltString(8);
  1611. }
  1612. pw = !string.IsNullOrWhiteSpace(tmpPw.GetString())
  1613. ? Utils.HashedPassword(tmpPw.GetString(), salt)
  1614. : Utils.HashedPassword(id.GetString(), salt);
  1615. }
  1616. if (student.TryGetProperty("name", out var tmpName)) name = tmpName.GetString();
  1617. if (student.TryGetProperty("gender", out var tmpGender)) gender = tmpGender.GetString();
  1618. if (student.TryGetProperty("mail", out var tmpMail)) mail = tmpMail.GetString();
  1619. if (student.TryGetProperty("mobile", out var tmpMobile)) mobile = tmpMobile.GetString();
  1620. if (student.TryGetProperty("year", out var tmpYear)) year = tmpYear.GetInt32();
  1621. if (student.TryGetProperty("periodId", out var tmpperiodId)) periodId = tmpperiodId.GetString();
  1622. if (student.TryGetProperty("irs", out var tmpIrs)) irs = tmpIrs.GetString();
  1623. if (student.TryGetProperty("classId", out var tmpclassId)) classId = tmpclassId.GetString();
  1624. else
  1625. {
  1626. errorClassId.Add(id.GetString());
  1627. continue;
  1628. }
  1629. //如果有給該欄位,且是給空的,代表要清空
  1630. if (student.TryGetProperty("no", out var tmpNo)) no = tmpNo.GetString();
  1631. if (!studentInfos.ContainsKey(id.GetString()))
  1632. {
  1633. //如果有給classId且是給空的,則也將no設為空,後續才能將no欄位清空。
  1634. if (classId != null && classId.Length == 0) no = string.Empty;
  1635. //classId => 沒給欄位(null) 有給欄位("") 但更新一定得給教室?
  1636. if (classId == null)
  1637. {
  1638. classId = "";
  1639. }
  1640. if (classStuds.ContainsKey(classId))
  1641. {
  1642. classStuds[classId].Add((id.GetString(), salt, pw, name, year, null, gender, null, null, classId, no, periodId));
  1643. }
  1644. else
  1645. {
  1646. classStuds.Add(
  1647. classId,
  1648. 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)>()
  1649. { (id.GetString(), salt, pw, name, year, null, gender, null, null, classId, no,periodId) });
  1650. }
  1651. //picture,mail,mobile暫不支持批量更新
  1652. studentInfos.Add(id.GetString(), (salt, pw, name, year, null, gender, null, null, classId, no, periodId, irs));
  1653. //先將id加進去後面再做刪除動作
  1654. nonexistentIds.Add(id.GetString());
  1655. }
  1656. }
  1657. }
  1658. }
  1659. //檢查所有輸入的班級資料內,學生座號是否有重複。
  1660. for (int ii = 0; ii <= classStuds.Values.Count - 1; ii++)
  1661. {
  1662. var duplicateNo = classStuds.ElementAt(ii).Value.GroupBy(o => o.no).Where(o => o.Count() > 1).Select(o => o.Key).ToList();
  1663. duplicateNo.Remove("");
  1664. duplicateNo.Remove(null);
  1665. var wrongStuds = classStuds.ElementAt(ii).Value.Where(o => duplicateNo.Contains(o.no)).Select(o => o).ToList();
  1666. impClassDuplNo.Add(classStuds.ElementAt(ii).Key, wrongStuds.Select(o => o.id).ToList());
  1667. wrongStuds.ForEach(o => { classStuds.ElementAt(ii).Value.Remove(o); nonexistentIds.Remove(o.id); });
  1668. classStuds[classStuds.ElementAt(ii).Key] = classStuds.ElementAt(ii).Value;
  1669. }
  1670. //查詢欲加入的教室資訊。
  1671. var classInfo = await getClassInfoUseId(_azureCosmos, _dingDing, _option, schoolId, classStuds.Keys.ToList());
  1672. //準備查詢db資料
  1673. CosmosContainer cosmosContainer = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student");
  1674. //查要移除教室或是沒加入教室的學生
  1675. foreach (var item in classStuds)
  1676. {
  1677. //如果沒有任何學生要更新,則跳過該間教室。
  1678. if (item.Value.Count == 0) continue;
  1679. string classId = null, className = null, classNo = null, gradeId = null, periodId = null;
  1680. //如果教室不存在的話(填錯教室之類的狀況),則記錄教室的id及學生id。
  1681. if (classInfo.ContainsKey(item.Key))
  1682. {
  1683. classId = item.Key;
  1684. className = classInfo[item.Key].GetProperty("name").GetString();
  1685. classNo = classInfo[item.Key].GetProperty("no").GetString();
  1686. //gradeId = classInfo[item.Key].GetProperty("gradeId").GetString(); 此欄位已不使用
  1687. periodId = classInfo[item.Key].GetProperty("periodId").GetString();
  1688. }
  1689. else if (item.Key.Length == 0)
  1690. {
  1691. }
  1692. else
  1693. {
  1694. //沒查到有該間教室的資訊,故將該間教室的ID及學生資料清單記起來,並且跳過不處理該資料。
  1695. errorClassId.Add(item.Key);
  1696. item.Value.ForEach(o => nonexistentIds.Remove(o.id));
  1697. continue;
  1698. }
  1699. //檢查座號是否有重複
  1700. //若只是改基本資料,該處還是會查到相同的座號。
  1701. var sutdNos = item.Value.Select(o => o.no).ToList();
  1702. var existNos = await checkStudNo(_azureCosmos, _dingDing, _option, schoolId, item.Key, sutdNos);
  1703. //更新並寫入學生資料
  1704. if (item.Value.Count != 0)
  1705. {
  1706. //查學生的基本資料(該間教室全部的學生)
  1707. string queryText = $"SELECT * FROM c WHERE c.id IN ({string.Join(",", item.Value.Select(o => $"'{o.id}'"))})";
  1708. List<JsonElement> listStudent = new List<JsonElement>();
  1709. await foreach (Response responseItem in cosmosContainer
  1710. .GetItemQueryStreamIterator(
  1711. queryText: queryText,
  1712. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  1713. {
  1714. using var json = await JsonDocument.ParseAsync(responseItem.ContentStream);
  1715. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1716. {
  1717. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1718. while (accounts.MoveNext())
  1719. {
  1720. JsonElement account = accounts.Current;
  1721. string id = $"{ account.GetProperty("id")}";
  1722. nonexistentIds.Remove(id);
  1723. //舊的座號,基本上不會重複,但可能會是空的
  1724. string no = $"{account.GetProperty("no")}";
  1725. account.TryGetProperty("irs", out JsonElement irsjson);
  1726. string irs = $"{irsjson}";
  1727. //用來記錄最後更改完的資料
  1728. (string salt, string pw, string name, int year, string picture, string gender, string mail, string mobile, string classId, string no, string periodId, string irs) tmpData
  1729. = (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, studentInfos[id].irs);
  1730. bool isUpPwDone = false;
  1731. bool isWrong = false;
  1732. //開始組Json
  1733. using var memoryStream = new MemoryStream();
  1734. using var writer = new Utf8JsonWriter(memoryStream);
  1735. writer.WriteStartObject();
  1736. foreach (var element in account.EnumerateObject())
  1737. {
  1738. if (isWrong) break;
  1739. switch (true)
  1740. {
  1741. case bool _ when element.Name.Equals("name", StringComparison.Ordinal):
  1742. if (string.IsNullOrWhiteSpace(studentInfos[id].name))
  1743. {
  1744. element.WriteTo(writer);
  1745. tmpData.name = element.Value.GetString();
  1746. }
  1747. else
  1748. {
  1749. writer.WriteString("name", studentInfos[id].name);
  1750. }
  1751. break;
  1752. case bool _ when element.Name.Equals("pw", StringComparison.Ordinal):
  1753. case bool _ when element.Name.Equals("salt", StringComparison.Ordinal):
  1754. if (!isUpPwDone && !string.IsNullOrWhiteSpace(studentInfos[id].salt) && !string.IsNullOrWhiteSpace(studentInfos[id].pw))
  1755. {
  1756. writer.WriteString("salt", studentInfos[id].salt);
  1757. writer.WriteString("pw", studentInfos[id].pw);
  1758. isUpPwDone = true;
  1759. }
  1760. break;
  1761. case bool _ when element.Name.Equals("periodId", StringComparison.Ordinal):
  1762. if (string.IsNullOrWhiteSpace(studentInfos[id].periodId))
  1763. {
  1764. element.WriteTo(writer);
  1765. tmpData.periodId = element.Value.GetString();
  1766. }
  1767. else
  1768. {
  1769. writer.WriteString("periodId", studentInfos[id].periodId);
  1770. }
  1771. break;
  1772. case bool _ when element.Name.Equals("gender", StringComparison.Ordinal):
  1773. if (string.IsNullOrWhiteSpace(studentInfos[id].gender))
  1774. {
  1775. element.WriteTo(writer);
  1776. tmpData.gender = element.Value.GetString();
  1777. }
  1778. else
  1779. {
  1780. writer.WriteString("gender", studentInfos[id].gender);
  1781. }
  1782. break;
  1783. case bool _ when element.Name.Equals("year", StringComparison.Ordinal):
  1784. if (studentInfos[id].year == 0)
  1785. {
  1786. element.WriteTo(writer);
  1787. tmpData.year = element.Value.GetInt32();
  1788. }
  1789. else
  1790. {
  1791. writer.WriteNumber("year", studentInfos[id].year);
  1792. }
  1793. break;
  1794. case bool _ when element.Name.Equals("classId", StringComparison.Ordinal):
  1795. if (studentInfos[id].classId != null && studentInfos[id].classId.Length == 0)
  1796. {
  1797. writer.WriteNull("classId");
  1798. writer.WriteNull("groupId");
  1799. writer.WriteNull("groupName");
  1800. tmpData.classId = null;
  1801. }
  1802. else if (string.IsNullOrWhiteSpace(studentInfos[id].classId))
  1803. {
  1804. element.WriteTo(writer);
  1805. tmpData.classId = element.Value.GetString();
  1806. }
  1807. else
  1808. {
  1809. writer.WriteString("classId", studentInfos[id].classId);
  1810. }
  1811. break;
  1812. case bool _ when element.Name.Equals("no", StringComparison.Ordinal):
  1813. //移除座號的話會給空的
  1814. if (studentInfos[id].no != null && studentInfos[id].no.Length == 0)
  1815. {
  1816. writer.WriteNull("no");
  1817. tmpData.no = null;
  1818. }
  1819. else if (string.IsNullOrWhiteSpace(studentInfos[id].no))
  1820. {
  1821. element.WriteTo(writer);
  1822. tmpData.no = element.Value.GetString();
  1823. }
  1824. else
  1825. {
  1826. //如果要更新的座號,跟已存在的座號相同,則不進行更新。
  1827. //沒有設定過舊no,或舊座號與新座號不同,則要進行重複座號的檢查。 舊no=null or 舊no!=新no
  1828. //if (string.IsNullOrWhiteSpace(no) || (!string.IsNullOrWhiteSpace(no) && !no.Equals(studentInfos[id].no)))
  1829. //{
  1830. // //如果有檢查到新座號和舊座號重複
  1831. // if (existNos.Any(o => o.Item2.Contains(studentInfos[id].no))) //.Contains(studentInfos[id].no))
  1832. // {
  1833. // if (errorNos.ContainsKey(id))
  1834. // {
  1835. // errorNos[id].Add(studentInfos[id].no);
  1836. // }
  1837. // else
  1838. // {
  1839. // errorNos.Add(id, new List<string>() { studentInfos[id].no });
  1840. // }
  1841. // isWrong = true;
  1842. // break;
  1843. // }
  1844. //}
  1845. writer.WriteString("no", studentInfos[id].no);
  1846. }
  1847. break;
  1848. case bool _ when element.Name.Equals("irs", StringComparison.Ordinal):
  1849. //移除座號的話會給空的
  1850. if (studentInfos[id].irs != null && studentInfos[id].irs.Length == 0)
  1851. {
  1852. writer.WriteNull("irs");
  1853. tmpData.irs = null;
  1854. }
  1855. else if (string.IsNullOrWhiteSpace(studentInfos[id].irs))
  1856. {
  1857. element.WriteTo(writer);
  1858. tmpData.irs = element.Value.GetString();
  1859. }
  1860. else
  1861. {
  1862. writer.WriteString("irs", studentInfos[id].irs);
  1863. }
  1864. break;
  1865. case bool _ when element.Name.StartsWith("_", StringComparison.Ordinal):
  1866. break;
  1867. default:
  1868. element.WriteTo(writer);
  1869. break;
  1870. }
  1871. }
  1872. //如果有錯誤,如座號重覆等,就會跳過該次更新。
  1873. if (isWrong)
  1874. {
  1875. await writer.DisposeAsync();
  1876. continue;
  1877. }
  1878. if (!account.TryGetProperty("irs", out JsonElement _irs) || _irs.ValueKind.Equals(JsonValueKind.Undefined))
  1879. {
  1880. writer.WriteString("irs", studentInfos[id].irs);
  1881. }
  1882. //若密碼和鹽沒有更新,就把舊的資料寫回去
  1883. if (!isUpPwDone)
  1884. {
  1885. writer.WriteString("salt", account.GetProperty("salt").GetString());
  1886. writer.WriteString("pw", account.GetProperty("pw").GetString());
  1887. }
  1888. writer.WriteEndObject();
  1889. writer.Flush();
  1890. try
  1891. {
  1892. var ret = await cosmosContainer.ReplaceItemStreamAsync(memoryStream, id, new PartitionKey($"Base-{schoolId}"));
  1893. //將更新完的id從字典內移除,保留沒查到的。
  1894. if (ret.Status == (int)HttpStatusCode.OK)
  1895. {
  1896. nonexistentIds.Remove(id);
  1897. retStuds.Add(new { id, tmpData.name, tmpData.picture, tmpData.year, tmpData.no, classId, classNo, className, gradeId, periodId, tmpData.irs });
  1898. }
  1899. else errorIds.Add(id);
  1900. }
  1901. catch (CosmosException ex)
  1902. {
  1903. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/updateStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1904. errorIds.Add(id);
  1905. }
  1906. catch (Exception ex)
  1907. {
  1908. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/updateStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1909. errorIds.Add(id);
  1910. }
  1911. }
  1912. }
  1913. //將輸入不存在的資料移除。
  1914. // nonexistentIds.ForEach(o => studentInfos.Remove(o));
  1915. }
  1916. }
  1917. }
  1918. errorClassId.ForEach(o => impClassDuplNo.Remove(o));
  1919. return (retStuds, impClassDuplNo.Where(o => o.Value.Count != 0).ToDictionary(o => o.Key, o => o.Value), nonexistentIds, errorIds, errorNos, errorClassId);
  1920. }
  1921. catch (CosmosException ex)
  1922. {
  1923. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/updateStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1924. }
  1925. catch (Exception ex)
  1926. {
  1927. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/updateStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1928. }
  1929. return (null, null, null, null, null, null);
  1930. }
  1931. /// <summary>
  1932. /// 創建學生帳號,目前SDK4.0預覽版還不支援批量創建(TransactionalBatch),待SDK正式發行時在優化此代碼。
  1933. /// </summary>
  1934. /// <param name="userStudents"></param>
  1935. /// <returns>已存在的ID</returns>
  1936. private async Task<(bool isSuc, List<string> existId)> createStudents(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, List<Student> userStudents)
  1937. {
  1938. var existId = new List<string>();
  1939. var exceptions = new List<Exception>();
  1940. try
  1941. {
  1942. var container = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student");
  1943. Parallel.ForEach(userStudents, async item =>
  1944. {
  1945. try
  1946. {
  1947. await container.CreateItemAsync(item);
  1948. }
  1949. catch (CosmosException ex)
  1950. {
  1951. if (ex.Status == (int)HttpStatusCode.Conflict) existId.Add(item.id);
  1952. else exceptions.Add(ex);
  1953. }
  1954. catch (Exception ex)
  1955. {
  1956. exceptions.Add(ex);
  1957. }
  1958. });
  1959. if (exceptions.Count == 0) return (true, existId);
  1960. else if (exceptions.Count > 1) throw new AggregateException(exceptions);
  1961. else if (exceptions.Count == 1) throw exceptions.Single();
  1962. }
  1963. catch (AggregateException ex)
  1964. {
  1965. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1966. }
  1967. catch (Exception ex)
  1968. {
  1969. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createStudents()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1970. }
  1971. return (false, existId);
  1972. }
  1973. /// <summary>
  1974. /// 取得該教室的學生座號,若有給座號LIST,則座號存在才會被查到;反之,若沒給則會將該間教室所有座號抓出來。
  1975. /// </summary>
  1976. /// <param name="schoolId"></param>
  1977. /// <param name="classId"></param>
  1978. /// <param name="nos"></param>
  1979. /// <returns></returns>
  1980. public static async Task<List<(string id, string no)>> checkStudNo(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, string classId, List<string> nos = null)
  1981. {
  1982. List<(string id, string no)> ret = new List<(string id, string no)>();
  1983. string queryText = $"SELECT c.id, c.no FROM c WHERE c.classId = '{classId}' AND c.code = 'Base-{schoolId}'";
  1984. if (nos != null) queryText += $"AND c.no IN ({string.Join(",", nos.Select(o => $"'{o}'"))})";
  1985. await foreach (Response item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student")
  1986. .GetItemQueryStreamIterator(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  1987. {
  1988. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1989. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1990. {
  1991. var classInfos = json.RootElement.GetProperty("Documents").EnumerateArray();
  1992. while (classInfos.MoveNext())
  1993. {
  1994. JsonElement account = classInfos.Current;
  1995. string id = account.GetProperty("id").GetString();
  1996. string no = account.GetProperty("no").GetString();
  1997. ret.Add((id, no));
  1998. }
  1999. }
  2000. }
  2001. return ret;
  2002. }
  2003. /// <summary>
  2004. /// 取得年級資訊
  2005. /// </summary>
  2006. /// <param name="schoolId"></param>
  2007. /// <returns>Key:periodId Vaule:list gradeInfo</returns>
  2008. public static async Task<Dictionary<string, List<(int gradeId, string gradeName)>>> getGrades(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId)
  2009. {
  2010. try
  2011. {
  2012. //Key:學制 Value:年級資訊list
  2013. Dictionary<string, List<(int gradeId, string gradeName)>> dicPeriod = new Dictionary<string, List<(int gradeId, string gradeName)>>();
  2014. var response = await _azureCosmos
  2015. .GetCosmosClient()
  2016. .GetContainer(Constant.TEAMModelOS, "School")
  2017. .ReadItemStreamAsync(schoolId, new PartitionKey("Base"));
  2018. if (response.Status != (int)HttpStatusCode.OK) return null;
  2019. using Stream stream = response.ContentStream;
  2020. var jsonDoc = await JsonDocument.ParseAsync(stream);
  2021. var emumObject = jsonDoc.RootElement.EnumerateObject();
  2022. var period = jsonDoc.RootElement.GetProperty("period").EnumerateArray();
  2023. while (period.MoveNext())
  2024. {
  2025. List<(int gradeId, string gradeName)> gradeInfos = new List<(int gradeId, string gradeName)>();
  2026. JsonElement jsonPeriod = period.Current;
  2027. var periodId = jsonPeriod.GetProperty("id").GetString();
  2028. var grades = jsonPeriod.GetProperty("grades").ToObject<List<string>>();
  2029. for (int index = 0; index < grades.Count; index++)
  2030. {
  2031. gradeInfos.Add((index, grades[index]));
  2032. }
  2033. //var grades = jsonPeriod.GetProperty("grades").EnumerateArray();
  2034. //while (grades.MoveNext())
  2035. //{
  2036. // JsonElement grade = grades.Current;
  2037. // var gradeId = grade.GetInt32();
  2038. // var gradeName = grade.GetProperty("name").GetString();
  2039. // gradeInfos.Add((gradeId, gradeName));
  2040. //}
  2041. dicPeriod.Add(periodId, gradeInfos);
  2042. }
  2043. return dicPeriod;
  2044. }
  2045. catch (Exception ex)
  2046. {
  2047. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getGrades()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2048. return null;
  2049. }
  2050. }
  2051. public struct studCreateInfo
  2052. {
  2053. public studCreateInfo(string id, string name, string gender, int year, string pw, string classId, string no, string periodId)
  2054. {
  2055. this.id = id;
  2056. this.name = name;
  2057. this.gender = gender;
  2058. this.year = year;
  2059. this.pw = pw;
  2060. this.classId = classId;
  2061. this.no = no;
  2062. this.periodId = periodId;
  2063. }
  2064. public string id { get; }
  2065. public string name { get; }
  2066. public string gender { get; }
  2067. public int year { get; }
  2068. public string pw { get; }
  2069. public string classId { get; }
  2070. public string no { get; }
  2071. public string periodId { get; set; }
  2072. }
  2073. }
  2074. }