StudentService.cs 124 KB

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