StudentService.cs 150 KB

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