StudentService.cs 152 KB

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