StudentService.cs 149 KB

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