StudentService.cs 149 KB

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