StudentService.cs 146 KB

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