StudentService.cs 120 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210
  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. //並行處理
  657. foreach (var stud in sortedImpData.studs)
  658. {
  659. //這邊一樣要確認已存在和欲加入還有欲修改的座號。
  660. //欲修改的不會有重複
  661. string classId = null;
  662. bool isContinue = false;
  663. if (!string.IsNullOrWhiteSpace(stud.Value.no) && !string.IsNullOrWhiteSpace(stud.Value.classNo))
  664. {
  665. classId = classNoId[stud.Value.classNo + "_" + stud.Value.classYear].classId;
  666. (string id, string no) existNoInfo = (null, null);
  667. //檢查要更新的座號是否已存在於雲端座號(已被其他同學使用)
  668. classStudNos[stud.Value.classNo + "_" + stud.Value.classYear].ForEach(
  669. o =>
  670. {
  671. if (o.no.Equals(stud.Value.no) && !o.id.Equals(stud.Key))
  672. {
  673. existNoInfo = (o.id, o.no);
  674. if (duplNos.ContainsKey(stud.Value.classNo)) duplNos[stud.Value.classNo].Add(stud.Key);
  675. else duplNos.Add(stud.Value.classNo, new List<string>() { stud.Key });
  676. }
  677. });
  678. //如果不是空的代表有座號重覆到,此時要再確認這個重複座號的id,是否存在於這次的更新,而且是要更新座號的。
  679. if (!string.IsNullOrWhiteSpace(existNoInfo.id))
  680. {
  681. isContinue = true;
  682. //輪巡所有匯入的學生資料,並檢查匯入的座號。
  683. sortedImpData.classStudNo[stud.Value.classNo].ForEach(
  684. o =>
  685. {
  686. if (o.id.Equals(existNoInfo.id) && !o.no.Equals(existNoInfo.no))
  687. {
  688. //可以更新該座號
  689. isContinue = false;
  690. duplNos[stud.Value.classNo].Remove(stud.Key);
  691. return;
  692. }
  693. });
  694. }
  695. }
  696. if (isContinue) continue;
  697. (string id, string name, string picture, int year, string no, string classId, string classNo, string className, string gradeId, string periodId) tmpStudInfo
  698. = (stud.Key, stud.Value.name, null, stud.Value.year, stud.Value.no, null, stud.Value.classNo, null, null, null);
  699. using var memoryStream = new MemoryStream();
  700. using var writerNew = new Utf8JsonWriter(memoryStream);
  701. writerNew.WriteStartObject();
  702. writerNew.WriteString("id", stud.Key);
  703. writerNew.WriteString("pk", $"Base");
  704. writerNew.WriteString("code", $"Base-{schoolId}");
  705. writerNew.WriteString("schoolId", schoolId);
  706. writerNew.WriteNumber("year", stud.Value.year);
  707. writerNew.WriteString("salt", stud.Value.salt);
  708. writerNew.WriteString("pw", stud.Value.pw);
  709. if (string.IsNullOrWhiteSpace(stud.Value.name)) writerNew.WriteNull("name");
  710. else writerNew.WriteString("name", stud.Value.name);
  711. writerNew.WriteString("gender", "M");
  712. writerNew.WriteNull("picture");
  713. writerNew.WriteNull("mail");
  714. writerNew.WriteNull("mobile");
  715. writerNew.WriteNull("country");
  716. if (!string.IsNullOrWhiteSpace(stud.Value.periodId))
  717. {
  718. writerNew.WriteString("periodId", stud.Value.periodId);
  719. }
  720. if (string.IsNullOrWhiteSpace(stud.Value.classNo)) writerNew.WriteNull("classId");
  721. else
  722. {
  723. writerNew.WriteString("classId", classId);
  724. tmpStudInfo.classId = classId;
  725. tmpStudInfo.className = classNoId[stud.Value.classNo + "_" + stud.Value.classYear].className;
  726. tmpStudInfo.gradeId = classNoId[stud.Value.classNo + "_" + stud.Value.classYear].gradeId;
  727. tmpStudInfo.periodId = classNoId[stud.Value.classNo + "_" + stud.Value.classYear].periodId;
  728. }
  729. if (string.IsNullOrWhiteSpace(stud.Value.no))
  730. {
  731. writerNew.WriteNull("no");
  732. writerNew.WriteNull("irs");
  733. }
  734. else
  735. {
  736. writerNew.WriteString("irs", stud.Value.no);
  737. writerNew.WriteString("no", stud.Value.no);
  738. };
  739. writerNew.WriteNull("groupId");
  740. writerNew.WriteNull("groupName");
  741. writerNew.WriteEndObject();
  742. writerNew.Flush();
  743. var response = await cosmosContainer.CreateItemStreamAsync(memoryStream, new PartitionKey($"Base-{schoolId}"));
  744. if (response.Status == (int)HttpStatusCode.Created)
  745. {
  746. //如果是Created則啥都不做,讓他去下面進行資料的彙整。
  747. }
  748. //查到已存在的id,則進行基本資料更新。
  749. else if (response.Status == (int)HttpStatusCode.Conflict)
  750. {
  751. try
  752. {
  753. bool isUpPwDone = false;
  754. Student student = await _azureCosmos
  755. .GetCosmosClient()
  756. .GetContainer(Constant.TEAMModelOS, "Student")
  757. .ReadItemAsync<Student>(stud.Key, new PartitionKey($"Base-{schoolId}"));
  758. if (!string.IsNullOrWhiteSpace(stud.Value.name))
  759. {
  760. student.name = stud.Value.name;
  761. }
  762. if (stud.Value.year > 0)
  763. {
  764. student.year = stud.Value.year;
  765. }
  766. if (!string.IsNullOrWhiteSpace(stud.Value.no))
  767. {
  768. student.no = stud.Value.no;
  769. }
  770. if (!string.IsNullOrWhiteSpace(stud.Value.classNo))
  771. {
  772. student.classId = classId;
  773. }
  774. if (!string.IsNullOrWhiteSpace(stud.Value.periodId))
  775. {
  776. student.periodId = stud.Value.periodId;
  777. }
  778. if (!isUpPwDone)
  779. {
  780. student.pw = stud.Value.pw;
  781. student.salt = stud.Value.salt;
  782. isUpPwDone = true;
  783. }
  784. tmpStudInfo.picture = student.picture;
  785. await cosmosContainer.ReplaceItemAsync(student, stud.Key, new PartitionKey($"Base-{schoolId}"));
  786. }
  787. catch (CosmosException ex)
  788. {
  789. errorIds.Add(stud.Key);
  790. continue;
  791. }
  792. }
  793. else
  794. {
  795. errorIds.Add(stud.Key);
  796. continue;
  797. }
  798. //整理輸出用資料
  799. retStuds.Add(
  800. new
  801. {
  802. tmpStudInfo.id,
  803. tmpStudInfo.name,
  804. tmpStudInfo.picture,
  805. tmpStudInfo.year,
  806. tmpStudInfo.no,
  807. tmpStudInfo.classId,
  808. tmpStudInfo.classNo,
  809. tmpStudInfo.className,
  810. // tmpStudInfo.gradeId,
  811. // tmpStudInfo.periodId
  812. });
  813. }
  814. return (retStuds, duplNos.Where(o => o.Value.Count != 0).ToDictionary(o => o.Key, o => o.Value), errorIds);
  815. }
  816. catch (Exception ex)
  817. {
  818. await _dingDing.SendBotMsg(
  819. $"IES5,{_option.Location},StudentController/upsertStudents()\nex:{ex.Message}{ex.StackTrace}",
  820. GroupNames.醍摩豆服務運維群組);
  821. }
  822. return (null, null, null);
  823. }
  824. /// <summary>
  825. /// 單純建立單一學生
  826. /// </summary>
  827. /// <param name="schoolId"></param>
  828. /// <param name="studCreateInfo"></param>
  829. public static async Task<bool> createStudent(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, studCreateInfo studCreateInfo)
  830. {
  831. try
  832. {
  833. using var stream = new MemoryStream();
  834. using var writer = new Utf8JsonWriter(stream);
  835. writer.WriteStartObject();
  836. writer.WriteString("pk", $"Base");
  837. writer.WriteString("code", $"Base-{schoolId}");
  838. writer.WriteString("id", studCreateInfo.id);
  839. if (string.IsNullOrWhiteSpace(studCreateInfo.name)) writer.WriteNull("name");
  840. else writer.WriteString("name", studCreateInfo.name);
  841. if (string.IsNullOrWhiteSpace(studCreateInfo.gender)) writer.WriteNull("gender");
  842. else writer.WriteString("gender", studCreateInfo.gender);
  843. writer.WriteString("schoolId", schoolId);
  844. //20210713 huanghb add 增加学段
  845. if (string.IsNullOrWhiteSpace(studCreateInfo.periodId)) writer.WriteNull("periodId");
  846. else writer.WriteString("periodId", studCreateInfo.periodId);
  847. writer.WriteNumber("year", studCreateInfo.year);
  848. writer.WriteNull("picture");
  849. writer.WriteNull("mail");
  850. writer.WriteNull("mobile");
  851. writer.WriteNull("country");
  852. //Password,若沒給則使用學號當密碼
  853. string salt = Utils.CreatSaltString(8);
  854. string hashPw = string.IsNullOrWhiteSpace(studCreateInfo.pw)
  855. ? Utils.HashedPassword(studCreateInfo.id, salt)
  856. : Utils.HashedPassword(studCreateInfo.pw, salt);
  857. writer.WriteString("salt", salt);
  858. writer.WriteString("pw", hashPw);
  859. if (string.IsNullOrWhiteSpace(studCreateInfo.classId)) writer.WriteNull("classId");
  860. else writer.WriteString("classId", studCreateInfo.classId);
  861. if (string.IsNullOrWhiteSpace(studCreateInfo.no))
  862. {
  863. writer.WriteNull("no");
  864. writer.WriteNull("irs");
  865. }
  866. else
  867. {
  868. writer.WriteString("no", studCreateInfo.no);
  869. writer.WriteString("irs", studCreateInfo.no);
  870. }
  871. writer.WriteNull("groupId");
  872. writer.WriteNull("groupName");
  873. writer.WriteEndObject();
  874. writer.Flush();
  875. var response = await _azureCosmos
  876. .GetCosmosClient()
  877. .GetContainer(Constant.TEAMModelOS, "Student")
  878. .CreateItemStreamAsync(stream, new PartitionKey($"Base-{schoolId}"));
  879. if (response.Status == (int)HttpStatusCode.Created || response.Status == (int)HttpStatusCode.OK) return true;
  880. if (response.Status == (int)HttpStatusCode.Conflict) return false;
  881. else
  882. {
  883. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createStudent()\nCosmosDB Create response status = {response.Status}\nID:{studCreateInfo.id}", GroupNames.醍摩豆服務運維群組);
  884. return false;
  885. }
  886. }
  887. catch (Exception ex)
  888. {
  889. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createStudent()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  890. return false;
  891. }
  892. }
  893. /// <summary>
  894. /// 生成Class資料
  895. /// </summary>
  896. /// <param name="schoolId"></param>
  897. /// <param name="classId"></param>
  898. /// <param name="className"></param>
  899. /// <param name="students"></param>
  900. /// <returns></returns>
  901. private static async Task<(string classId, string classNo, string className, string periodId, string gradeId, int classYear)> createClassInfo(
  902. AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option,
  903. string schoolId, string classId, string className, string classNo, string periodId, string gradeId, int classYear)
  904. {
  905. //組Class JSON
  906. try
  907. {
  908. string cId = classId;
  909. using var memoryStream = new MemoryStream();
  910. using var writer = new Utf8JsonWriter(memoryStream);
  911. writer.WriteStartObject();
  912. writer.WriteString("pk", "Class");
  913. writer.WriteString("code", $"Class-{schoolId}");
  914. //如果classId是空的,則生成一組GUID。
  915. if (string.IsNullOrWhiteSpace(classId))
  916. {
  917. cId = Guid.NewGuid().ToString();
  918. writer.WriteString("id", cId);
  919. }
  920. else writer.WriteString("id", classId);
  921. if (string.IsNullOrWhiteSpace(classNo)) writer.WriteNull("no");
  922. else writer.WriteString("no", classNo);
  923. writer.WriteNull("x");
  924. writer.WriteNull("y");
  925. if (string.IsNullOrWhiteSpace(className)) writer.WriteNull("name");
  926. else writer.WriteString("name", className);
  927. writer.WritePropertyName("teacher");
  928. writer.WriteStartObject();
  929. writer.WriteNull("id");
  930. writer.WriteNull("name");
  931. writer.WriteEndObject();
  932. //if (string.IsNullOrWhiteSpace(gradeId)) writer.WriteNull("gradeId");
  933. //else writer.WriteString("gradeId", gradeId);
  934. if (string.IsNullOrWhiteSpace(periodId)) writer.WriteNull("periodId");
  935. else writer.WriteString("periodId", periodId);
  936. writer.WriteNumber("year", classYear);
  937. writer.WriteNull("sn");
  938. writer.WriteString("style", "smart");
  939. writer.WriteString("openType", "1");
  940. writer.WriteString("scope", "school");
  941. writer.WriteEndObject();
  942. writer.Flush();
  943. var ret = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").CreateItemStreamAsync(memoryStream, new PartitionKey($"Class-{schoolId}"));
  944. if (ret.Status != (int)HttpStatusCode.Created)
  945. {
  946. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createClassInfo()\nStatus:{ret.Status}\nSchoolId:{schoolId},ClassId:{classId}", GroupNames.醍摩豆服務運維群組);
  947. }
  948. return (cId, classNo, className, periodId, gradeId, classYear);
  949. }
  950. catch (CosmosException ex)
  951. {
  952. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createClassInfo()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  953. }
  954. catch (Exception ex)
  955. {
  956. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createClassInfo()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  957. }
  958. return (null, null, null, null, null, 0);
  959. }
  960. /// <summary>
  961. /// 使用學校代碼查詢該校所有學生,並且在查詢該學生所屬的教室及座號,支援offset和limit操作已及ContinuationToken,若有ContinuationToken,則會優先使用ContinuationToken。
  962. /// </summary>
  963. /// <param name="schoolId"></param>
  964. /// <param name="byNameOrId">透過Name或Id來查,所以不會管學制、學級和教室</param>
  965. /// <param name="byPeriod"></param>
  966. /// <param name="byGrade"></param>
  967. /// <param name="byClassId"></param>
  968. /// <param name="offset"></param>
  969. /// <param name="limit"></param>
  970. /// <param name="token"></param>
  971. /// <returns></returns>
  972. private async Task<(List<object> students, string continuationToken)> getStudents(
  973. AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option,
  974. string schoolId, string byNameOrId = null, string byPeriod = null, string byGrade = null, string byClassId = null, int offset = -1, int limit = -1, string token = default)
  975. {
  976. try
  977. {
  978. //以學校學生角度去抓資料
  979. List<(string id, string name, string picture, int year)> listStudent = new List<(string id, string name, string picture, int year)>();
  980. string queryText = $"SELECT c.id, c.name, c.picture, c.year FROM c WHERE c.code = 'Base-{schoolId}'";
  981. //如果有選擇ClassId的話,則先取得該教室內的學生。
  982. List<string> searchId = new List<string>();
  983. if (!string.IsNullOrWhiteSpace(byClassId))
  984. {
  985. var classInfos = await getClassInfoUseId(_azureCosmos,_dingDing,_option, schoolId, new List<string>() { byClassId });
  986. foreach (var classInfo in classInfos)
  987. {
  988. var students = classInfo.Value.GetProperty("students").EnumerateArray();
  989. while (students.MoveNext())
  990. {
  991. JsonElement stud = students.Current;
  992. string id = stud.GetProperty("id").GetString();
  993. searchId.Add(id);
  994. }
  995. }
  996. //將使用者過濾classId所取得的學生ID加入sql字串內
  997. if (searchId.Count != 0)
  998. {
  999. queryText = $"{queryText} AND c.id IN ({string.Join(",", searchId.Select(o => $"'{o}'"))})";
  1000. }
  1001. }
  1002. //檢查是否有接續token及是否要在sql語法內多增加offset及limit
  1003. if (string.IsNullOrWhiteSpace(token))
  1004. {
  1005. token = default;
  1006. if (offset != -1 && limit != -1) queryText = $"{queryText} OFFSET {offset} LIMIT {limit}";
  1007. }
  1008. //回傳用ContinuationToken
  1009. string continuationToken = string.Empty;
  1010. //進行學生資料的查詢
  1011. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student")
  1012. .GetItemQueryStreamIterator(
  1013. queryText: queryText,
  1014. continuationToken: token,
  1015. requestOptions: new QueryRequestOptions()
  1016. { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  1017. {
  1018. continuationToken = item.GetContinuationToken();
  1019. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1020. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1021. {
  1022. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1023. while (accounts.MoveNext())
  1024. {
  1025. JsonElement account = accounts.Current;
  1026. listStudent.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString(), account.GetProperty("picture").GetString(), account.GetProperty("year").GetInt32()));
  1027. }
  1028. }
  1029. //單筆查詢上限為100條,所以查完一次即返回,並且給接續token。
  1030. break;
  1031. }
  1032. //查學生所屬的教室及座號
  1033. List<object> ret = new List<object>();
  1034. //查教室資訊,使用上面的學生id並透過子查詢查詢。
  1035. 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}'"))}))";
  1036. await foreach (Response item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
  1037. .GetItemQueryStreamIterator(
  1038. queryText: queryText,
  1039. //continuationToken: token,
  1040. requestOptions: new QueryRequestOptions()
  1041. { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  1042. {
  1043. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1044. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1045. {
  1046. var classrooms = json.RootElement.GetProperty("Documents").EnumerateArray();
  1047. while (classrooms.MoveNext())
  1048. {
  1049. JsonElement classroom = classrooms.Current;
  1050. var studs = classroom.GetProperty("students").EnumerateArray();
  1051. while (studs.MoveNext())
  1052. {
  1053. JsonElement stud = studs.Current;
  1054. string id = stud.GetProperty("id").GetString();
  1055. //整理出前端所需的資訊
  1056. var tmp = listStudent
  1057. .Where(o => o.id.Equals(id, StringComparison.Ordinal))
  1058. .Select(o =>
  1059. new
  1060. {
  1061. o.id,
  1062. o.name,
  1063. o.picture,
  1064. o.year,
  1065. no = stud.GetProperty("no").GetString(),
  1066. gradeId = classroom.GetProperty("gradeId").GetString(),
  1067. className = classroom.GetProperty("name").GetString()
  1068. });
  1069. ret.AddRange(tmp);
  1070. //刪除已整理完的ID
  1071. listStudent.RemoveAll(o => o.id.Equals(id, StringComparison.Ordinal));
  1072. }
  1073. }
  1074. }
  1075. }
  1076. var notJoinClassStuds = listStudent.Select(o =>
  1077. new
  1078. {
  1079. o.id,
  1080. o.name,
  1081. o.picture,
  1082. o.year,
  1083. no = (string)null,
  1084. gradeId = (string)null,
  1085. className = (string)null
  1086. });
  1087. ret.AddRange(notJoinClassStuds);
  1088. return (ret, continuationToken);
  1089. }
  1090. catch (CosmosException ex)
  1091. {
  1092. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getStudents()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1093. }
  1094. catch (Exception ex)
  1095. {
  1096. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getStudents()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1097. }
  1098. return (null, null);
  1099. }
  1100. /// <summary>
  1101. /// 取得該學校的所有學生。
  1102. /// </summary>
  1103. /// <param name="schoolId"></param>
  1104. /// <returns> [{id,name,picture,year,no,classId,classNo,className,gradeId,periodId},{id,name,picture,..}..]</returns>
  1105. public static async Task<List<object>> getAllStudent(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId)
  1106. {
  1107. try
  1108. {
  1109. //TODO : 進階查詢選項調整、部分地方可用並行處理
  1110. //以學校學生角度去抓資料
  1111. 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)>>();
  1112. 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)>();
  1113. 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}'";
  1114. //回傳用ContinuationToken
  1115. string continuationToken = string.Empty;
  1116. var container = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student");
  1117. //進行學生資料的查詢 TEAMModelOS-Student
  1118. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student")
  1119. .GetItemQueryStreamIterator(
  1120. queryText: queryText,
  1121. requestOptions: new QueryRequestOptions()
  1122. { PartitionKey = new PartitionKey($"Base-{schoolId}"), MaxItemCount = -1 }))
  1123. {
  1124. continuationToken = item.GetContinuationToken();
  1125. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1126. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1127. {
  1128. List<(string id, string name, string picture, int year, string no)> students = new List<(string id, string name, string picture, int year, string no)>();
  1129. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1130. while (accounts.MoveNext())
  1131. {
  1132. JsonElement acc = accounts.Current;
  1133. string classId = acc.GetProperty("classId").GetString();
  1134. acc.TryGetProperty("irs", out JsonElement irs);
  1135. if (string.IsNullOrWhiteSpace(classId))
  1136. {
  1137. notJoinClassStuds.Add(
  1138. (
  1139. acc.GetProperty("id").GetString(),
  1140. acc.GetProperty("name").GetString(),
  1141. acc.GetProperty("picture").GetString(),
  1142. acc.GetProperty("year").GetInt32(),
  1143. acc.GetProperty("no").GetString(),
  1144. acc.TryGetProperty("periodId", out JsonElement _periodId) && _periodId.ValueKind.Equals(JsonValueKind.String) ? _periodId.GetString() : null,
  1145. $"{irs}"
  1146. )
  1147. );
  1148. }
  1149. else
  1150. {
  1151. if (dicClassStuds.ContainsKey(classId))
  1152. {
  1153. dicClassStuds[classId].Add(
  1154. (
  1155. acc.GetProperty("id").GetString(),
  1156. acc.GetProperty("name").GetString(),
  1157. acc.GetProperty("picture").GetString(),
  1158. acc.GetProperty("year").GetInt32(),
  1159. acc.GetProperty("no").GetString(), acc.TryGetProperty("periodId", out JsonElement _periodId) && _periodId.ValueKind.Equals(JsonValueKind.String) ? _periodId.GetString() : null,
  1160. $"{irs}"
  1161. )
  1162. );
  1163. }
  1164. else
  1165. {
  1166. dicClassStuds.Add(classId,
  1167. new List<(string id, string name, string picture, int year, string no, string periodId, string irs)>()
  1168. {
  1169. (
  1170. acc.GetProperty("id").GetString(),
  1171. acc.GetProperty("name").GetString(),
  1172. acc.GetProperty("picture").GetString(),
  1173. acc.GetProperty("year").GetInt32(),
  1174. acc.GetProperty("no").GetString(), acc.TryGetProperty("periodId",out JsonElement _periodId)&& _periodId.ValueKind.Equals(JsonValueKind.String) ? _periodId.GetString() : null,$"{irs}"
  1175. )
  1176. }
  1177. );
  1178. }
  1179. }
  1180. }
  1181. }
  1182. }
  1183. //查學生所屬的教室及座號
  1184. List<object> ret = new List<object>();
  1185. //查教室的資訊,用以取得gradeId,periodId資訊。
  1186. var classInfos = await getClassInfoUseId(_azureCosmos,_dingDing,_option, schoolId, dicClassStuds.Keys.ToList());
  1187. //輪循所有教室學生的資料
  1188. foreach (var classStud in dicClassStuds)
  1189. {
  1190. string classId = null, classNo = null, className = null, gradeId = null, periodId = null;
  1191. int classYear = -1;
  1192. if (classInfos.ContainsKey(classStud.Key))
  1193. {
  1194. classId = classInfos[classStud.Key].GetProperty("id").GetString();
  1195. classNo = classInfos[classStud.Key].GetProperty("no").GetString();
  1196. className = classInfos[classStud.Key].GetProperty("name").GetString();
  1197. periodId = classInfos[classStud.Key].TryGetProperty("periodId", out JsonElement _periodId) && _periodId.ValueKind.Equals(JsonValueKind.String) ? _periodId.GetString() : null;
  1198. if (classInfos[classStud.Key].TryGetProperty("year", out JsonElement year))
  1199. {
  1200. if (year.ValueKind.Equals(JsonValueKind.Number))
  1201. {
  1202. classYear = classInfos[classStud.Key].GetProperty("year").GetInt32();
  1203. }
  1204. }
  1205. }
  1206. var tmp = classStud.Value.Select(o =>
  1207. new
  1208. {
  1209. o.id,
  1210. o.name,
  1211. o.picture,
  1212. o.year,
  1213. o.no,
  1214. classId,
  1215. classNo,
  1216. className,
  1217. gradeId,
  1218. periodId = string.IsNullOrEmpty(periodId) ? o.periodId : periodId,
  1219. classYear,
  1220. irs = o.irs
  1221. });
  1222. ret.AddRange(tmp);
  1223. }
  1224. //彙整沒有加入教室的學生
  1225. notJoinClassStuds.ForEach(o => ret.Add(
  1226. new
  1227. {
  1228. o.id,
  1229. o.name,
  1230. o.picture,
  1231. o.year,
  1232. o.no,
  1233. classId = (string)null,
  1234. classNo = (string)null,
  1235. className = (string)null,
  1236. gradeId = (string)null,
  1237. o.periodId,
  1238. classYear = -1,
  1239. irs = o.irs
  1240. }));
  1241. return ret;
  1242. }
  1243. catch (Exception ex)
  1244. {
  1245. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getStudents()\n{ex.Message},{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1246. }
  1247. return null;
  1248. }
  1249. /// <summary>
  1250. /// 取得該校所有教室內的名單
  1251. /// </summary>
  1252. /// <param name="schoolId"></param>
  1253. /// <returns></returns>
  1254. public async Task<Dictionary<string, JsonElement>> getClassStudent(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, string classId = null)
  1255. {
  1256. try
  1257. {
  1258. string queryText = $"SELECT VALUE FROM c WHERE c.";
  1259. //if (!string.IsNullOrWhiteSpace(classId)) queryText += $" AND c.id = '{classId}'";
  1260. Dictionary<string, JsonElement> listStudent = new Dictionary<string, JsonElement>();
  1261. await foreach (Response item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
  1262. .GetItemQueryStreamIterator(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  1263. {
  1264. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1265. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1266. {
  1267. JsonElement.ArrayEnumerator accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1268. while (accounts.MoveNext())
  1269. {
  1270. JsonElement account = accounts.Current;
  1271. string cId = account.GetProperty("id").GetString();
  1272. var students = account.GetProperty("students").Clone();
  1273. listStudent.Add(cId, students);
  1274. }
  1275. }
  1276. }
  1277. return listStudent;
  1278. }
  1279. catch (Exception ex)
  1280. {
  1281. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassStudentAsync()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1282. }
  1283. return null;
  1284. }
  1285. /// <summary>
  1286. /// 刪除學生,非透過批量刪除方法。
  1287. /// </summary>
  1288. /// <param name="schoolId"></param>
  1289. /// <param name="students"></param>
  1290. /// <returns></returns>
  1291. public static async Task<List<string>> deleteStudents(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, JsonElement.ArrayEnumerator students)
  1292. {
  1293. List<string> sucIds = new List<string>();
  1294. try
  1295. {
  1296. var exceptions = new List<Exception>();
  1297. List<GroupList> scGroupLists = new List<GroupList>();
  1298. List<GroupList> teGroupLists = new List<GroupList>();
  1299. var container = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student");
  1300. while (students.MoveNext())
  1301. {
  1302. string id = string.Empty;
  1303. try
  1304. {
  1305. JsonElement student = students.Current;
  1306. id = student.GetProperty("id").GetString();
  1307. var ret = await container.DeleteItemStreamAsync(id, new PartitionKey($"Base-{schoolId}"));
  1308. if (ret.Status == (int)HttpStatusCode.NoContent) sucIds.Add(id);
  1309. 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}") }))
  1310. {
  1311. scGroupLists.Add(item);
  1312. }
  1313. 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") }))
  1314. {
  1315. teGroupLists.Add(item);
  1316. }
  1317. if (scGroupLists.Count > 0)
  1318. {
  1319. foreach (GroupList stuList in scGroupLists)
  1320. {
  1321. for (int j = 0; j < stuList.members.Count; j++)
  1322. {
  1323. if (id.Equals(stuList.members[j].id) && stuList.members[j].code.Equals(schoolId))
  1324. {
  1325. stuList.members.RemoveAt(j);
  1326. stuList.scount -= 1;
  1327. break;
  1328. }
  1329. }
  1330. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(stuList, stuList.id, new PartitionKey(stuList.code));
  1331. }
  1332. }
  1333. if (teGroupLists.Count > 0)
  1334. {
  1335. foreach (GroupList stuList in teGroupLists)
  1336. {
  1337. for (int j = 0; j < stuList.members.Count; j++)
  1338. {
  1339. if (id.Equals(stuList.members[j].id) && stuList.members[j].code.Equals(schoolId))
  1340. {
  1341. stuList.members.RemoveAt(j);
  1342. stuList.scount -= 1;
  1343. break;
  1344. }
  1345. }
  1346. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(stuList, stuList.id, new PartitionKey(stuList.code));
  1347. }
  1348. }
  1349. }
  1350. catch (CosmosException ex)
  1351. {
  1352. exceptions.Add(ex);
  1353. }
  1354. catch (Exception ex)
  1355. {
  1356. exceptions.Add(ex);
  1357. }
  1358. }
  1359. if (exceptions.Count == 0) return sucIds;
  1360. else if (exceptions.Count > 1) throw new AggregateException(exceptions);
  1361. else if (exceptions.Count == 1) throw exceptions.Single();
  1362. }
  1363. catch (CosmosException ex)
  1364. {
  1365. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/deleteStudents()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1366. }
  1367. catch (Exception ex)
  1368. {
  1369. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/deleteStudents()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1370. }
  1371. return sucIds;
  1372. }
  1373. /// <summary>
  1374. /// 將學生基本資料內的classId、no、groupId及groupName清為null。
  1375. /// </summary>
  1376. /// <param name="schoolId"></param>
  1377. /// <param name="students">["id1","id2",...]</param>
  1378. /// <returns></returns>
  1379. 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)
  1380. {
  1381. //紀錄輸入的學生
  1382. List<string> impStuds = new List<string>();
  1383. //紀錄更新成功的學生
  1384. List<string> sucStuds = new List<string>();
  1385. //記錄沒查到的學生
  1386. List<string> nonexistentIds = new List<string>();
  1387. //紀錄更新出錯的學生
  1388. List<string> errorIds = new List<string>();
  1389. //整理輸入的學生資訊
  1390. while (students.MoveNext())
  1391. {
  1392. JsonElement student = students.Current;
  1393. impStuds.Add(student.GetString());
  1394. }
  1395. if (impStuds.Count == 0) return (null, null, null);
  1396. string queryText = $"SELECT VALUE c FROM c WHERE c.id IN ({string.Join(",", impStuds.Select(o => $"'{o}'"))})";
  1397. await foreach (Response item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student")
  1398. .GetItemQueryStreamIterator(
  1399. queryText: queryText,
  1400. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  1401. {
  1402. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1403. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1404. {
  1405. JsonElement.ArrayEnumerator docs = json.RootElement.GetProperty("Documents").EnumerateArray();
  1406. while (docs.MoveNext())
  1407. {
  1408. JsonElement doc = docs.Current;
  1409. doc.TryGetProperty("id", out var tmpId);
  1410. var id = tmpId.GetString();
  1411. using var stream = new MemoryStream();
  1412. using var writer = new Utf8JsonWriter(stream);
  1413. writer.WriteStartObject();
  1414. foreach (var element in doc.EnumerateObject())
  1415. {
  1416. //將教室相關欄位清空
  1417. switch (true)
  1418. {
  1419. case bool _ when element.Name.Equals("classId", StringComparison.Ordinal):
  1420. writer.WriteNull("classId");
  1421. break;
  1422. case bool _ when element.Name.Equals("no", StringComparison.Ordinal):
  1423. writer.WriteNull("no");
  1424. break;
  1425. case bool _ when element.Name.Equals("groupId", StringComparison.Ordinal):
  1426. writer.WriteNull("groupId");
  1427. break;
  1428. case bool _ when element.Name.Equals("groupName", StringComparison.Ordinal):
  1429. writer.WriteNull("groupName");
  1430. break;
  1431. case bool _ when element.Name.Equals("irs", StringComparison.Ordinal):
  1432. writer.WriteNull("irs");
  1433. break;
  1434. case bool _ when element.Name.StartsWith("_", StringComparison.Ordinal):
  1435. break;
  1436. default:
  1437. element.WriteTo(writer);
  1438. break;
  1439. }
  1440. }
  1441. writer.WriteEndObject();
  1442. writer.Flush();
  1443. var ret = await _azureCosmos
  1444. .GetCosmosClient()
  1445. .GetContainer(Constant.TEAMModelOS, "Student")
  1446. .ReplaceItemStreamAsync(stream, id, new PartitionKey($"Base-{schoolId}"));
  1447. if (ret.Status == (int)HttpStatusCode.OK)
  1448. {
  1449. sucStuds.Add(id);
  1450. }
  1451. else
  1452. {
  1453. impStuds.Remove(id);
  1454. errorIds.Add(id);
  1455. await _dingDing.SendBotMsg(
  1456. $"IES5,{_option.Location},StudentController/removeStudentClassInfo(),CosmosDB response:{ret.Status}\nBase-{schoolId},id:{id}",
  1457. GroupNames.醍摩豆服務運維群組);
  1458. }
  1459. }
  1460. }
  1461. }
  1462. //將impStuds內的資料移除sucStuds及errorIds,所得的結果就是不存在於資料庫的id。
  1463. sucStuds.ForEach(o => impStuds.Remove(o));
  1464. errorIds.ForEach(o => impStuds.Remove(o));
  1465. return (sucStuds, impStuds, errorIds);
  1466. }
  1467. /// <summary>
  1468. /// 取得教室資訊,使用classId進行查詢。
  1469. /// </summary>
  1470. /// <returns></returns>
  1471. private static async Task<Dictionary<string, JsonElement>> getClassInfoUseId(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, List<string> classIds)
  1472. {
  1473. try
  1474. {
  1475. if (!(classIds == null || classIds.Count == 0))
  1476. {
  1477. string queryText = $"SELECT * FROM c WHERE c.code = 'Class-{schoolId}' AND c.id IN ({string.Join(",", classIds.Select(o => $"'{o}'"))})";
  1478. Dictionary<string, JsonElement> dicClassInfo = new Dictionary<string, JsonElement>();
  1479. await foreach (Response item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
  1480. .GetItemQueryStreamIterator(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  1481. {
  1482. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1483. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1484. {
  1485. var classInfos = json.RootElement.GetProperty("Documents").EnumerateArray();
  1486. while (classInfos.MoveNext())
  1487. {
  1488. JsonElement account = classInfos.Current;
  1489. string id = account.GetProperty("id").GetString();
  1490. dicClassInfo.Add(id, account.Clone());
  1491. }
  1492. }
  1493. }
  1494. return dicClassInfo;
  1495. }
  1496. else return null;
  1497. }
  1498. catch (CosmosException ex)
  1499. {
  1500. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassInfoUseId()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1501. }
  1502. catch (Exception ex)
  1503. {
  1504. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassInfoUseId()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1505. }
  1506. return null;
  1507. }
  1508. /// <summary>
  1509. /// 取得教室資訊,使用classNo進行查詢。
  1510. /// </summary>
  1511. /// <returns></returns>
  1512. 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)
  1513. {
  1514. try
  1515. {
  1516. Dictionary<string, Class> dicClassInfo = new Dictionary<string, Class>();
  1517. if (!(classNos == null || classNos.Count == 0))
  1518. {
  1519. foreach (var key in classNos.Keys)
  1520. {
  1521. 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}' ";
  1522. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
  1523. .GetItemQueryIterator<Class>(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  1524. {
  1525. dicClassInfo[item.id] = item;
  1526. item.name = classNos[key].className;
  1527. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<Class>(item, item.id, new PartitionKey(item.code));
  1528. }
  1529. }
  1530. return dicClassInfo;
  1531. }
  1532. else return null;
  1533. }
  1534. catch (CosmosException ex)
  1535. {
  1536. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassInfoUseId()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1537. }
  1538. catch (Exception ex)
  1539. {
  1540. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassInfoUseId()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1541. }
  1542. return null;
  1543. }
  1544. /// <summary>
  1545. /// 批量更新學生資訊,目前支持更新姓名、密碼、座號、性別及教室id,匯入時ClassId為必填。
  1546. /// </summary>
  1547. /// <param name="schoolId"></param>
  1548. /// <param name="students"></param>
  1549. /// <returns></returns>
  1550. 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)>
  1551. updateStudents(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, JsonElement.ArrayEnumerator students)
  1552. {
  1553. try
  1554. {
  1555. //整理輸入的資料->檢查輸入資料有沒有重複座號->取得欲加入的教室資訊->查詢學生並將資料更新並寫入
  1556. //Key:id Value:學生基本資訊
  1557. var studentInfos
  1558. = 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)>();
  1559. //用於進行座號是否重複查詢時使用
  1560. var classStuds
  1561. = 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)>>();
  1562. //紀錄教室"輸入"的學生座號是否有重複
  1563. var impClassDuplNo = new Dictionary<string, List<string>>();
  1564. //紀錄不存在的學生id
  1565. var nonexistentIds = new List<string>();
  1566. //紀錄跟現有雲端學生座號重複的
  1567. var errorNos = new Dictionary<string, List<string>>();
  1568. //紀錄處理錯誤的id,cosmosdb寫入時錯誤等...
  1569. var errorIds = new List<string>();
  1570. //紀錄沒找到的classId
  1571. var errorClassId = new List<string>();
  1572. //紀錄輸出結果
  1573. var retStuds = new List<object>();
  1574. //整理輸入資料
  1575. while (students.MoveNext())
  1576. {
  1577. JsonElement student = students.Current;
  1578. if (student.TryGetProperty("id", out var id))
  1579. {
  1580. //確認是否有id欄位,並且確認是否有給pw欄位,若無給或是null empty等,則使用id當密碼。
  1581. if (!string.IsNullOrWhiteSpace(id.GetString()))
  1582. {
  1583. string salt = null,
  1584. pw = null,
  1585. name = null,
  1586. gender = null,
  1587. mail = null,
  1588. mobile = null,
  1589. classId = null,
  1590. periodId = null,
  1591. irs = null,
  1592. no = null;
  1593. int year = 0;
  1594. //有給pw欄位才進行處理
  1595. if (student.TryGetProperty("pw", out var tmpPw))
  1596. {
  1597. var response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemStreamAsync(id.GetString(), new PartitionKey($"Base-{schoolId}"));
  1598. if (response.Status == 200)
  1599. {
  1600. var rjson = await JsonDocument.ParseAsync(response.ContentStream);
  1601. rjson.RootElement.TryGetProperty("salt", out JsonElement _salt);
  1602. salt = $"{_salt}";
  1603. }
  1604. if (string.IsNullOrWhiteSpace(salt))
  1605. {
  1606. salt = Utils.CreatSaltString(8);
  1607. }
  1608. pw = !string.IsNullOrWhiteSpace(tmpPw.GetString())
  1609. ? Utils.HashedPassword(tmpPw.GetString(), salt)
  1610. : Utils.HashedPassword(id.GetString(), salt);
  1611. }
  1612. if (student.TryGetProperty("name", out var tmpName)) name = tmpName.GetString();
  1613. if (student.TryGetProperty("gender", out var tmpGender)) gender = tmpGender.GetString();
  1614. if (student.TryGetProperty("mail", out var tmpMail)) mail = tmpMail.GetString();
  1615. if (student.TryGetProperty("mobile", out var tmpMobile)) mobile = tmpMobile.GetString();
  1616. if (student.TryGetProperty("year", out var tmpYear)) year = tmpYear.GetInt32();
  1617. if (student.TryGetProperty("periodId", out var tmpperiodId)) periodId = tmpperiodId.GetString();
  1618. if (student.TryGetProperty("irs", out var tmpIrs)) irs = tmpIrs.GetString();
  1619. if (student.TryGetProperty("classId", out var tmpclassId)) classId = tmpclassId.GetString();
  1620. else
  1621. {
  1622. errorClassId.Add(id.GetString());
  1623. continue;
  1624. }
  1625. //如果有給該欄位,且是給空的,代表要清空
  1626. if (student.TryGetProperty("no", out var tmpNo)) no = tmpNo.GetString();
  1627. if (!studentInfos.ContainsKey(id.GetString()))
  1628. {
  1629. //如果有給classId且是給空的,則也將no設為空,後續才能將no欄位清空。
  1630. if (classId != null && classId.Length == 0) no = string.Empty;
  1631. //classId => 沒給欄位(null) 有給欄位("") 但更新一定得給教室?
  1632. if (classId == null)
  1633. {
  1634. classId = "";
  1635. }
  1636. if (classStuds.ContainsKey(classId))
  1637. {
  1638. classStuds[classId].Add((id.GetString(), salt, pw, name, year, null, gender, null, null, classId, no, periodId));
  1639. }
  1640. else
  1641. {
  1642. classStuds.Add(
  1643. classId,
  1644. 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)>()
  1645. { (id.GetString(), salt, pw, name, year, null, gender, null, null, classId, no,periodId) });
  1646. }
  1647. //picture,mail,mobile暫不支持批量更新
  1648. studentInfos.Add(id.GetString(), (salt, pw, name, year, null, gender, null, null, classId, no, periodId, irs));
  1649. //先將id加進去後面再做刪除動作
  1650. nonexistentIds.Add(id.GetString());
  1651. }
  1652. }
  1653. }
  1654. }
  1655. //檢查所有輸入的班級資料內,學生座號是否有重複。
  1656. for (int ii = 0; ii <= classStuds.Values.Count - 1; ii++)
  1657. {
  1658. var duplicateNo = classStuds.ElementAt(ii).Value.GroupBy(o => o.no).Where(o => o.Count() > 1).Select(o => o.Key).ToList();
  1659. duplicateNo.Remove("");
  1660. duplicateNo.Remove(null);
  1661. var wrongStuds = classStuds.ElementAt(ii).Value.Where(o => duplicateNo.Contains(o.no)).Select(o => o).ToList();
  1662. impClassDuplNo.Add(classStuds.ElementAt(ii).Key, wrongStuds.Select(o => o.id).ToList());
  1663. wrongStuds.ForEach(o => { classStuds.ElementAt(ii).Value.Remove(o); nonexistentIds.Remove(o.id); });
  1664. classStuds[classStuds.ElementAt(ii).Key] = classStuds.ElementAt(ii).Value;
  1665. }
  1666. //查詢欲加入的教室資訊。
  1667. var classInfo = await getClassInfoUseId(_azureCosmos,_dingDing,_option, schoolId, classStuds.Keys.ToList());
  1668. //準備查詢db資料
  1669. CosmosContainer cosmosContainer = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student");
  1670. //查要移除教室或是沒加入教室的學生
  1671. foreach (var item in classStuds)
  1672. {
  1673. //如果沒有任何學生要更新,則跳過該間教室。
  1674. if (item.Value.Count == 0) continue;
  1675. string classId = null, className = null, classNo = null, gradeId = null, periodId = null;
  1676. //如果教室不存在的話(填錯教室之類的狀況),則記錄教室的id及學生id。
  1677. if (classInfo.ContainsKey(item.Key))
  1678. {
  1679. classId = item.Key;
  1680. className = classInfo[item.Key].GetProperty("name").GetString();
  1681. classNo = classInfo[item.Key].GetProperty("no").GetString();
  1682. //gradeId = classInfo[item.Key].GetProperty("gradeId").GetString(); 此欄位已不使用
  1683. periodId = classInfo[item.Key].GetProperty("periodId").GetString();
  1684. }
  1685. else if (item.Key.Length == 0)
  1686. {
  1687. }
  1688. else
  1689. {
  1690. //沒查到有該間教室的資訊,故將該間教室的ID及學生資料清單記起來,並且跳過不處理該資料。
  1691. errorClassId.Add(item.Key);
  1692. item.Value.ForEach(o => nonexistentIds.Remove(o.id));
  1693. continue;
  1694. }
  1695. //檢查座號是否有重複
  1696. //若只是改基本資料,該處還是會查到相同的座號。
  1697. var sutdNos = item.Value.Select(o => o.no).ToList();
  1698. var existNos = await checkStudNo(_azureCosmos,_dingDing,_option, schoolId, item.Key, sutdNos);
  1699. //更新並寫入學生資料
  1700. if (item.Value.Count != 0)
  1701. {
  1702. //查學生的基本資料(該間教室全部的學生)
  1703. string queryText = $"SELECT * FROM c WHERE c.id IN ({string.Join(",", item.Value.Select(o => $"'{o.id}'"))})";
  1704. List<JsonElement> listStudent = new List<JsonElement>();
  1705. await foreach (Response responseItem in cosmosContainer
  1706. .GetItemQueryStreamIterator(
  1707. queryText: queryText,
  1708. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  1709. {
  1710. using var json = await JsonDocument.ParseAsync(responseItem.ContentStream);
  1711. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1712. {
  1713. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1714. while (accounts.MoveNext())
  1715. {
  1716. JsonElement account = accounts.Current;
  1717. string id = $"{ account.GetProperty("id")}";
  1718. nonexistentIds.Remove(id);
  1719. //舊的座號,基本上不會重複,但可能會是空的
  1720. string no = $"{account.GetProperty("no")}";
  1721. account.TryGetProperty("irs", out JsonElement irsjson);
  1722. string irs = $"{irsjson}";
  1723. //用來記錄最後更改完的資料
  1724. (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
  1725. = (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);
  1726. bool isUpPwDone = false;
  1727. bool isWrong = false;
  1728. //開始組Json
  1729. using var memoryStream = new MemoryStream();
  1730. using var writer = new Utf8JsonWriter(memoryStream);
  1731. writer.WriteStartObject();
  1732. foreach (var element in account.EnumerateObject())
  1733. {
  1734. if (isWrong) break;
  1735. switch (true)
  1736. {
  1737. case bool _ when element.Name.Equals("name", StringComparison.Ordinal):
  1738. if (string.IsNullOrWhiteSpace(studentInfos[id].name))
  1739. {
  1740. element.WriteTo(writer);
  1741. tmpData.name = element.Value.GetString();
  1742. }
  1743. else
  1744. {
  1745. writer.WriteString("name", studentInfos[id].name);
  1746. }
  1747. break;
  1748. case bool _ when element.Name.Equals("pw", StringComparison.Ordinal):
  1749. case bool _ when element.Name.Equals("salt", StringComparison.Ordinal):
  1750. if (!isUpPwDone && !string.IsNullOrWhiteSpace(studentInfos[id].salt) && !string.IsNullOrWhiteSpace(studentInfos[id].pw))
  1751. {
  1752. writer.WriteString("salt", studentInfos[id].salt);
  1753. writer.WriteString("pw", studentInfos[id].pw);
  1754. isUpPwDone = true;
  1755. }
  1756. break;
  1757. case bool _ when element.Name.Equals("periodId", StringComparison.Ordinal):
  1758. if (string.IsNullOrWhiteSpace(studentInfos[id].periodId))
  1759. {
  1760. element.WriteTo(writer);
  1761. tmpData.periodId = element.Value.GetString();
  1762. }
  1763. else
  1764. {
  1765. writer.WriteString("periodId", studentInfos[id].periodId);
  1766. }
  1767. break;
  1768. case bool _ when element.Name.Equals("gender", StringComparison.Ordinal):
  1769. if (string.IsNullOrWhiteSpace(studentInfos[id].gender))
  1770. {
  1771. element.WriteTo(writer);
  1772. tmpData.gender = element.Value.GetString();
  1773. }
  1774. else
  1775. {
  1776. writer.WriteString("gender", studentInfos[id].gender);
  1777. }
  1778. break;
  1779. case bool _ when element.Name.Equals("year", StringComparison.Ordinal):
  1780. if (studentInfos[id].year == 0)
  1781. {
  1782. element.WriteTo(writer);
  1783. tmpData.year = element.Value.GetInt32();
  1784. }
  1785. else
  1786. {
  1787. writer.WriteNumber("year", studentInfos[id].year);
  1788. }
  1789. break;
  1790. case bool _ when element.Name.Equals("classId", StringComparison.Ordinal):
  1791. if (studentInfos[id].classId != null && studentInfos[id].classId.Length == 0)
  1792. {
  1793. writer.WriteNull("classId");
  1794. writer.WriteNull("groupId");
  1795. writer.WriteNull("groupName");
  1796. tmpData.classId = null;
  1797. }
  1798. else if (string.IsNullOrWhiteSpace(studentInfos[id].classId))
  1799. {
  1800. element.WriteTo(writer);
  1801. tmpData.classId = element.Value.GetString();
  1802. }
  1803. else
  1804. {
  1805. writer.WriteString("classId", studentInfos[id].classId);
  1806. }
  1807. break;
  1808. case bool _ when element.Name.Equals("no", StringComparison.Ordinal):
  1809. //移除座號的話會給空的
  1810. if (studentInfos[id].no != null && studentInfos[id].no.Length == 0)
  1811. {
  1812. writer.WriteNull("no");
  1813. tmpData.no = null;
  1814. }
  1815. else if (string.IsNullOrWhiteSpace(studentInfos[id].no))
  1816. {
  1817. element.WriteTo(writer);
  1818. tmpData.no = element.Value.GetString();
  1819. }
  1820. else
  1821. {
  1822. //如果要更新的座號,跟已存在的座號相同,則不進行更新。
  1823. //沒有設定過舊no,或舊座號與新座號不同,則要進行重複座號的檢查。 舊no=null or 舊no!=新no
  1824. //if (string.IsNullOrWhiteSpace(no) || (!string.IsNullOrWhiteSpace(no) && !no.Equals(studentInfos[id].no)))
  1825. //{
  1826. // //如果有檢查到新座號和舊座號重複
  1827. // if (existNos.Any(o => o.Item2.Contains(studentInfos[id].no))) //.Contains(studentInfos[id].no))
  1828. // {
  1829. // if (errorNos.ContainsKey(id))
  1830. // {
  1831. // errorNos[id].Add(studentInfos[id].no);
  1832. // }
  1833. // else
  1834. // {
  1835. // errorNos.Add(id, new List<string>() { studentInfos[id].no });
  1836. // }
  1837. // isWrong = true;
  1838. // break;
  1839. // }
  1840. //}
  1841. writer.WriteString("no", studentInfos[id].no);
  1842. }
  1843. break;
  1844. case bool _ when element.Name.Equals("irs", StringComparison.Ordinal):
  1845. //移除座號的話會給空的
  1846. if (studentInfos[id].irs != null && studentInfos[id].irs.Length == 0)
  1847. {
  1848. writer.WriteNull("irs");
  1849. tmpData.irs = null;
  1850. }
  1851. else if (string.IsNullOrWhiteSpace(studentInfos[id].irs))
  1852. {
  1853. element.WriteTo(writer);
  1854. tmpData.irs = element.Value.GetString();
  1855. }
  1856. else
  1857. {
  1858. writer.WriteString("irs", studentInfos[id].irs);
  1859. }
  1860. break;
  1861. case bool _ when element.Name.StartsWith("_", StringComparison.Ordinal):
  1862. break;
  1863. default:
  1864. element.WriteTo(writer);
  1865. break;
  1866. }
  1867. }
  1868. //如果有錯誤,如座號重覆等,就會跳過該次更新。
  1869. if (isWrong)
  1870. {
  1871. await writer.DisposeAsync();
  1872. continue;
  1873. }
  1874. if (!account.TryGetProperty("irs", out JsonElement _irs) || _irs.ValueKind.Equals(JsonValueKind.Undefined))
  1875. {
  1876. writer.WriteString("irs", studentInfos[id].irs);
  1877. }
  1878. //若密碼和鹽沒有更新,就把舊的資料寫回去
  1879. if (!isUpPwDone)
  1880. {
  1881. writer.WriteString("salt", account.GetProperty("salt").GetString());
  1882. writer.WriteString("pw", account.GetProperty("pw").GetString());
  1883. }
  1884. writer.WriteEndObject();
  1885. writer.Flush();
  1886. try
  1887. {
  1888. var ret = await cosmosContainer.ReplaceItemStreamAsync(memoryStream, id, new PartitionKey($"Base-{schoolId}"));
  1889. //將更新完的id從字典內移除,保留沒查到的。
  1890. if (ret.Status == (int)HttpStatusCode.OK)
  1891. {
  1892. nonexistentIds.Remove(id);
  1893. retStuds.Add(new { id, tmpData.name, tmpData.picture, tmpData.year, tmpData.no, classId, classNo, className, gradeId, periodId, tmpData.irs });
  1894. }
  1895. else errorIds.Add(id);
  1896. }
  1897. catch (CosmosException ex)
  1898. {
  1899. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/updateStudents()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1900. errorIds.Add(id);
  1901. }
  1902. catch (Exception ex)
  1903. {
  1904. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/updateStudents()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1905. errorIds.Add(id);
  1906. }
  1907. }
  1908. }
  1909. //將輸入不存在的資料移除。
  1910. // nonexistentIds.ForEach(o => studentInfos.Remove(o));
  1911. }
  1912. }
  1913. }
  1914. errorClassId.ForEach(o => impClassDuplNo.Remove(o));
  1915. return (retStuds, impClassDuplNo.Where(o => o.Value.Count != 0).ToDictionary(o => o.Key, o => o.Value), nonexistentIds, errorIds, errorNos, errorClassId);
  1916. }
  1917. catch (CosmosException ex)
  1918. {
  1919. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/updateStudents()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1920. }
  1921. catch (Exception ex)
  1922. {
  1923. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/updateStudents()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1924. }
  1925. return (null, null, null, null, null, null);
  1926. }
  1927. /// <summary>
  1928. /// 創建學生帳號,目前SDK4.0預覽版還不支援批量創建(TransactionalBatch),待SDK正式發行時在優化此代碼。
  1929. /// </summary>
  1930. /// <param name="userStudents"></param>
  1931. /// <returns>已存在的ID</returns>
  1932. private async Task<(bool isSuc, List<string> existId)> createStudents(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, List<Student> userStudents)
  1933. {
  1934. var existId = new List<string>();
  1935. var exceptions = new List<Exception>();
  1936. try
  1937. {
  1938. var container = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student");
  1939. Parallel.ForEach(userStudents, async item =>
  1940. {
  1941. try
  1942. {
  1943. await container.CreateItemAsync(item);
  1944. }
  1945. catch (CosmosException ex)
  1946. {
  1947. if (ex.Status == (int)HttpStatusCode.Conflict) existId.Add(item.id);
  1948. else exceptions.Add(ex);
  1949. }
  1950. catch (Exception ex)
  1951. {
  1952. exceptions.Add(ex);
  1953. }
  1954. });
  1955. if (exceptions.Count == 0) return (true, existId);
  1956. else if (exceptions.Count > 1) throw new AggregateException(exceptions);
  1957. else if (exceptions.Count == 1) throw exceptions.Single();
  1958. }
  1959. catch (AggregateException ex)
  1960. {
  1961. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createStudents()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1962. }
  1963. catch (Exception ex)
  1964. {
  1965. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createStudents()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1966. }
  1967. return (false, existId);
  1968. }
  1969. /// <summary>
  1970. /// 取得該教室的學生座號,若有給座號LIST,則座號存在才會被查到;反之,若沒給則會將該間教室所有座號抓出來。
  1971. /// </summary>
  1972. /// <param name="schoolId"></param>
  1973. /// <param name="classId"></param>
  1974. /// <param name="nos"></param>
  1975. /// <returns></returns>
  1976. public static async Task<List<(string id, string no)>> checkStudNo(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId, string classId, List<string> nos = null)
  1977. {
  1978. List<(string id, string no)> ret = new List<(string id, string no)>();
  1979. string queryText = $"SELECT c.id, c.no FROM c WHERE c.classId = '{classId}' AND c.code = 'Base-{schoolId}'";
  1980. if (nos != null) queryText += $"AND c.no IN ({string.Join(",", nos.Select(o => $"'{o}'"))})";
  1981. await foreach (Response item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student")
  1982. .GetItemQueryStreamIterator(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  1983. {
  1984. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1985. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1986. {
  1987. var classInfos = json.RootElement.GetProperty("Documents").EnumerateArray();
  1988. while (classInfos.MoveNext())
  1989. {
  1990. JsonElement account = classInfos.Current;
  1991. string id = account.GetProperty("id").GetString();
  1992. string no = account.GetProperty("no").GetString();
  1993. ret.Add((id, no));
  1994. }
  1995. }
  1996. }
  1997. return ret;
  1998. }
  1999. /// <summary>
  2000. /// 取得年級資訊
  2001. /// </summary>
  2002. /// <param name="schoolId"></param>
  2003. /// <returns>Key:periodId Vaule:list gradeInfo</returns>
  2004. public static async Task<Dictionary<string, List<(int gradeId, string gradeName)>>> getGrades(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string schoolId)
  2005. {
  2006. try
  2007. {
  2008. //Key:學制 Value:年級資訊list
  2009. Dictionary<string, List<(int gradeId, string gradeName)>> dicPeriod = new Dictionary<string, List<(int gradeId, string gradeName)>>();
  2010. var response = await _azureCosmos
  2011. .GetCosmosClient()
  2012. .GetContainer(Constant.TEAMModelOS, "School")
  2013. .ReadItemStreamAsync(schoolId, new PartitionKey("Base"));
  2014. if (response.Status != (int)HttpStatusCode.OK) return null;
  2015. using Stream stream = response.ContentStream;
  2016. var jsonDoc = await JsonDocument.ParseAsync(stream);
  2017. var emumObject = jsonDoc.RootElement.EnumerateObject();
  2018. var period = jsonDoc.RootElement.GetProperty("period").EnumerateArray();
  2019. while (period.MoveNext())
  2020. {
  2021. List<(int gradeId, string gradeName)> gradeInfos = new List<(int gradeId, string gradeName)>();
  2022. JsonElement jsonPeriod = period.Current;
  2023. var periodId = jsonPeriod.GetProperty("id").GetString();
  2024. var grades = jsonPeriod.GetProperty("grades").ToObject<List<string>>();
  2025. for (int index = 0; index < grades.Count; index++)
  2026. {
  2027. gradeInfos.Add((index, grades[index]));
  2028. }
  2029. //var grades = jsonPeriod.GetProperty("grades").EnumerateArray();
  2030. //while (grades.MoveNext())
  2031. //{
  2032. // JsonElement grade = grades.Current;
  2033. // var gradeId = grade.GetInt32();
  2034. // var gradeName = grade.GetProperty("name").GetString();
  2035. // gradeInfos.Add((gradeId, gradeName));
  2036. //}
  2037. dicPeriod.Add(periodId, gradeInfos);
  2038. }
  2039. return dicPeriod;
  2040. }
  2041. catch (Exception ex)
  2042. {
  2043. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getGrades()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  2044. return null;
  2045. }
  2046. }
  2047. public struct studCreateInfo
  2048. {
  2049. public studCreateInfo(string id, string name, string gender, int year, string pw, string classId, string no, string periodId)
  2050. {
  2051. this.id = id;
  2052. this.name = name;
  2053. this.gender = gender;
  2054. this.year = year;
  2055. this.pw = pw;
  2056. this.classId = classId;
  2057. this.no = no;
  2058. this.periodId = periodId;
  2059. }
  2060. public string id { get; }
  2061. public string name { get; }
  2062. public string gender { get; }
  2063. public int year { get; }
  2064. public string pw { get; }
  2065. public string classId { get; }
  2066. public string no { get; }
  2067. public string periodId { get; set; }
  2068. }
  2069. }
  2070. }