StudentService.cs 145 KB

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