StudentService.cs 135 KB

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