StudentController.cs 119 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Dynamic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Text;
  9. using System.Text.Json;
  10. using System.Threading.Tasks;
  11. using Azure;
  12. using Azure.Cosmos;
  13. using Azure.Storage.Sas;
  14. using Microsoft.AspNetCore.Authorization;
  15. using Microsoft.AspNetCore.Cryptography.KeyDerivation;
  16. using Microsoft.AspNetCore.Mvc;
  17. using Microsoft.Extensions.Options;
  18. using TEAMModelOS.Filter;
  19. using TEAMModelOS.Models;
  20. using TEAMModelOS.SDK.DI;
  21. using TEAMModelOS.SDK.Extension;
  22. using TEAMModelOS.SDK.Models;
  23. using TEAMModelOS.SDK.Models.Cosmos;
  24. using TEAMModelOS.SDK.Models.Cosmos.Common;
  25. namespace TEAMModelOS.Controllers
  26. {
  27. [Route("student")]
  28. [ApiController]
  29. public class StudentController : Controller
  30. {
  31. private readonly AzureCosmosFactory _azureCosmos;
  32. private readonly AzureStorageFactory _azureStorage;
  33. private readonly DingDing _dingDing;
  34. private readonly Option _option;
  35. public StudentController(
  36. AzureCosmosFactory azureCosmos,
  37. AzureStorageFactory azureStorage,
  38. DingDing dingDing,
  39. IOptionsSnapshot<Option> option
  40. )
  41. {
  42. _azureCosmos = azureCosmos;
  43. _azureStorage = azureStorage;
  44. _dingDing = dingDing;
  45. _option = option?.Value;
  46. }
  47. /// <summary>
  48. /// 學生帳號管理
  49. /// </summary>
  50. /// <param name="request"></param>
  51. /// <returns></returns>
  52. [AllowAnonymous]
  53. [HttpPost("student-manage")]
  54. public async Task<IActionResult> StudentManage(JsonElement request)
  55. {
  56. try
  57. {
  58. //TODO : 權限檢查、學校檢查。
  59. if (!request.TryGetProperty("grant_type", out JsonElement grant_type) || !request.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
  60. switch (grant_type.GetString())
  61. {
  62. case "create":
  63. //單人創建 創建學生->將學生加入教室 檢查學生ID是否重複,欲加入的班級存不存在,座號是否重複。
  64. //id pw name classId no year
  65. //retrun 如果有重複則回{ existNo } , 成功則{ id, name, year, classId, no }
  66. var importStuds = request.GetProperty("students").EnumerateArray();
  67. while (importStuds.MoveNext())
  68. {
  69. JsonElement currStud = importStuds.Current;
  70. string id = null, name = null, pw = null, no = null, classId = null;
  71. int year = 0;
  72. //讀取輸入的資料
  73. if (!currStud.TryGetProperty("id", out var tmpId) || !currStud.TryGetProperty("name", out var tmpName)) continue;
  74. id = tmpId.GetString();
  75. name = tmpName.GetString();
  76. if (currStud.TryGetProperty("pw", out var tmpPw)) pw = tmpPw.GetString();
  77. if (currStud.TryGetProperty("year", out var tmpYear)) year = tmpYear.GetInt32();
  78. if (currStud.TryGetProperty("no", out var tmpNo)) no = tmpNo.GetString();
  79. if (currStud.TryGetProperty("classId", out var tmpClassId)) classId = tmpClassId.GetString();
  80. //要檢查座號使否已被使用
  81. var existNo = await checkStudNo(schoolId.GetString(), classId, new List<string>() { id });
  82. if (existNo.Count != 0) return this.Ok(new { code = $"Base-{schoolId.GetString()}", existNo = existNo.Select(o => o.id).ToList() });
  83. //建立學生
  84. studCreateInfo studCreateInfo = new studCreateInfo(id, name, "M", year, pw, classId, no);
  85. var isCreateSuc = await createStudent(schoolId.GetString(), studCreateInfo);
  86. if (isCreateSuc) return this.Ok(new { code = $"Base-{schoolId.GetString()}", id, name, year, classId, no });
  87. else return this.Ok(new { code = $"Base-{schoolId.GetString()}", errorId = id });
  88. }
  89. break;
  90. case "import":
  91. //只有ClassNo可以比對
  92. var retUpsert = await upsertStudents(schoolId.GetString(), request.GetProperty("students").EnumerateArray());
  93. return this.Ok(new { code = $"Base-{schoolId.GetString()}", students = retUpsert.studs, retUpsert.classDuplNos, retUpsert.errorIds });
  94. case "read":
  95. //讀取該間學校所有的學生資訊
  96. var students = await getAllStudent(schoolId.GetString());
  97. return this.Ok(new { code = $"Base-{schoolId.GetString()}", students });
  98. case "update":
  99. //更新學生資料,批量密碼重置,基本資訊更新(姓名、教室ID、性別、學年及座號)
  100. var retUpdate = await updateStudents(schoolId.GetString(), request.GetProperty("students").EnumerateArray());
  101. return this.Ok(new { code = $"Base-{schoolId.GetString()}", students = retUpdate.studs, retUpdate.classDuplNos, retUpdate.nonexistentIds, retUpdate.errorNos, retUpdate.errorClassId });
  102. case "delete":
  103. //刪除學生資料及從教室學生名單內移除該學生
  104. var sucDelIds = await deleteStudents(schoolId.GetString(), request.GetProperty("students").EnumerateArray());
  105. return this.Ok(new { code = $"Base-{schoolId.GetString()}", ids = sucDelIds });
  106. case "remove":
  107. //將學生基本資料內的classId、no、groupId及groupName寫入null
  108. ( List<string> studs, List< string > nonexistentIds, List<string> errorIds) retRemove = await removeStudentClassInfo(schoolId.GetString(), request.GetProperty("students").EnumerateArray());
  109. return Ok(new { code = $"Base-{schoolId.GetString()}", ids = retRemove.studs, retRemove.nonexistentIds, retRemove.errorIds });
  110. default:
  111. return BadRequest();
  112. }
  113. }
  114. catch (Exception ex)
  115. {
  116. Console.WriteLine(ex.Message);
  117. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/StudentManage()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  118. }
  119. return BadRequest();
  120. }
  121. /// <summary>
  122. /// 整理前端匯入的學生資訊
  123. /// </summary>
  124. /// <param name="schoolId"></param>
  125. /// <param name="students"></param>
  126. /// <returns></returns>
  127. private (Dictionary<string, (string name, string no, int year, string salt, string pw, string classNo, string className, string periodId)> studs,
  128. Dictionary<string, (string className, string periodId, int year, string no )> classInfo,
  129. Dictionary<string, List<(string id, string no)>> classStudNo,
  130. List<string> errorYear,
  131. List<string> duplId) doSortImpStuds(string schoolId, JsonElement.ArrayEnumerator students)
  132. {
  133. //批量匯入 檢查輸入數據 確認座號 確認教室(創建教室) 確認學生存不存在或是要不要更新
  134. //存放輸入的學生資訊 key:stud id value:學生詳細資料
  135. Dictionary<string, (string name, string no, int year, string salt, string pw, string classNo, string className, string periodId)> dicStuds = new Dictionary<string, (string name, string no, int year, string salt, string pw, string classNo, string className, string periodId)>();
  136. //存放教室資訊用 key:classNo value:className
  137. Dictionary<string, (string className, string periodId, int year,string classNo)> dicClassInfo = new Dictionary<string, (string className, string periodId, int year,string classNo)>();
  138. //存放欲加入該間教室的學生座號清單 key:classNo value:no list
  139. Dictionary<string, List<(string id, string no)>> dicClassStudNo = new Dictionary<string, List<(string id, string no)>>();
  140. //存放輸入id重複
  141. List<string> duplId = new List<string>();
  142. List<string> errorYear = new List<string>();
  143. while (students.MoveNext())
  144. {
  145. //string id = null, no = null, name = null, year = null, pw = null, classNo = null, className = null;
  146. JsonElement student = students.Current;
  147. //ClassNo內的座號
  148. //欲加入的教室
  149. //查學生
  150. //該間教室的座號與目前欲更新的是否有重複 有些可能是同教室換座號 反正都要將學生讀出來
  151. //舊學生完整資料+新學生資料
  152. //進行輸入資料的整理
  153. if (student.TryGetProperty("id", out var tmpId))
  154. {
  155. string id = tmpId.GetString();
  156. //如果id欄位是空的,則跳過該筆資料
  157. if (string.IsNullOrWhiteSpace(id)) continue;
  158. //輸入的id不應有重複
  159. if (dicStuds.ContainsKey(id))
  160. {
  161. //如果id重複,則將之從整理清單內清除
  162. duplId.Add(id);
  163. dicStuds.Remove(id);
  164. }
  165. (string name, string no, int year, string salt, string pw, string classNo, string className, string periodId) studentInfo = (null, null, 0, null, null, null, null, null);
  166. if (student.TryGetProperty("name", out var tmpName) && !string.IsNullOrWhiteSpace(tmpName.GetString())) studentInfo.name = tmpName.GetString();
  167. //入學學年為必須,故若是無給值則將之紀錄並跳過該筆資料
  168. if (student.TryGetProperty("year", out var tmpYear) && !string.IsNullOrWhiteSpace(Convert.ToString(tmpYear))) studentInfo.year = tmpYear.GetInt32();
  169. else
  170. {
  171. errorYear.Add(id);
  172. continue;
  173. }
  174. //Password,若沒給則使用學號當密碼
  175. studentInfo.salt = Utils.CreatSaltString(8);
  176. studentInfo.pw = student.TryGetProperty("pw", out var tmpPw) && !string.IsNullOrWhiteSpace(tmpPw.GetString())
  177. ? Utils.HashedPassword(tmpPw.GetString(), studentInfo.salt)
  178. : Utils.HashedPassword(id, studentInfo.salt);
  179. if (student.TryGetProperty("periodId", out var tmpPeriodId) && !string.IsNullOrWhiteSpace(tmpPeriodId.GetString())) studentInfo.periodId = tmpPeriodId.GetString();
  180. // if (student.TryGetProperty("gradeIndex", out var tmpGradeIndex)) studentInfo.gradeIndex = tmpGradeIndex.GetInt32();
  181. if (student.TryGetProperty("classNo", out var tmpClassNo) && !string.IsNullOrWhiteSpace(tmpClassNo.GetString()))
  182. {
  183. studentInfo.classNo = tmpClassNo.GetString();
  184. //在新建帳號上,應要給classNo才能設定no,但是若只是已存在的帳號要進行座號更新呢? 為避免使用者出錯,故已存在的帳號也應當給classNo。
  185. if (student.TryGetProperty("no", out var tmpNo) && !string.IsNullOrWhiteSpace(tmpNo.GetString()))
  186. {
  187. studentInfo.no = tmpNo.GetString();
  188. //這邊先將該間教室欲使用到的no整理出來
  189. if (dicClassStudNo.ContainsKey(tmpClassNo.GetString())) dicClassStudNo[tmpClassNo.GetString()].Add((id, tmpNo.GetString()));
  190. else dicClassStudNo.Add(tmpClassNo.GetString(), new List<(string id, string no)>() { (id, tmpNo.GetString()) });
  191. }
  192. //有給classNo才會紀錄className,classNo屬於實體教室門牌號,全校理當只會有一個。
  193. int year =0;
  194. if (student.TryGetProperty("classYear", out var tmpClassYear) && tmpClassYear.TryGetInt32(out int syear))
  195. {
  196. year = syear;
  197. }
  198. if (student.TryGetProperty("className", out var tmpClassName) && !string.IsNullOrWhiteSpace(tmpClassName.GetString()))
  199. {
  200. studentInfo.className = tmpClassName.GetString();
  201. if (!dicClassInfo.ContainsKey($"{studentInfo.periodId}_{year}_{tmpClassNo.GetString()}"))
  202. { dicClassInfo.Add($"{studentInfo.periodId}_{year}_{tmpClassNo.GetString()}", (tmpClassName.GetString(), studentInfo.periodId, year, tmpClassNo.GetString())); }
  203. }
  204. }
  205. //將最後結果加到字典內
  206. dicStuds.Add(id, studentInfo);
  207. }
  208. }
  209. return (dicStuds, dicClassInfo, dicClassStudNo, errorYear, duplId);
  210. }
  211. /// <summary>
  212. /// 更新或是新增學生
  213. /// </summary>
  214. /// <param name="schoolId"></param>
  215. /// <param name="students"></param>
  216. /// <returns></returns>
  217. private async Task<(List<object> studs, Dictionary<string ,List<string>> classDuplNos, List<string> errorIds)> upsertStudents(
  218. string schoolId,
  219. JsonElement.ArrayEnumerator students)
  220. {
  221. try
  222. {
  223. var sortedImpData = doSortImpStuds(schoolId, students);
  224. //var classNos = sortedImpData.classInfo.Select(o => new {key= o.Key, periodId=o.Value.periodId,index= o.Value.gradeIndex,year = o.Value.year }).ToList();
  225. //抓到教室資訊
  226. var classInfos = await getClassInfoUseNo(schoolId, sortedImpData.classInfo);
  227. //取出已存在教室的classId,後面查座號要用。
  228. List<Task> tasks = new List<Task>();
  229. //Key:ClassNo Value:No 匯入時只有ClassNo
  230. Dictionary<string, List<(string id, string no)>> classStudNos = new Dictionary<string, List<(string id, string no)>>();
  231. //Key:ClassNo Value:ClassId 存放教室no及id的變數
  232. 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)>();
  233. foreach (var classInfo in classInfos)
  234. {
  235. string classGradeId = classInfo.Value.gradeId;
  236. int classYear = classInfo.Value.year;
  237. classNoId.Add(classInfo.Value.no,
  238. (classInfo.Value.id, classInfo.Value.name, classInfo.Value.periodId, classGradeId, classYear));
  239. tasks.Add(
  240. Task.Run(
  241. async () =>
  242. {
  243. //(id,no)
  244. var studNo = await checkStudNo(schoolId, classInfo.Value.id);
  245. classStudNos.Add(classInfo.Value.no, studNo);
  246. }));
  247. }
  248. //這邊整理出不存在的教室,之後創建新教室用(比對classNo)。
  249. //var nonexistentClassNo = classNos.Except(classInfos.Select(o => o.Key).ToList());
  250. List<string> exsitkey = new List<string>();
  251. foreach (var classInfo in classInfos)
  252. {
  253. //$"{studentInfo.periodId}_{year}_{tmpClassNo.GetString()}"
  254. var key = $"{classInfo.Value.periodId}_{classInfo.Value.year}_{classInfo.Value.no}";
  255. exsitkey.Add(key);
  256. }
  257. List<KeyValuePair<string, (string className, string periodId, int year, string no)>> nonexistentClassNo =new List<KeyValuePair<string, (string className, string periodId, int year, string no)>>();
  258. foreach (var key in sortedImpData.classInfo.Keys) {
  259. if (!exsitkey.Contains(key)) {
  260. nonexistentClassNo.Add(new KeyValuePair<string, (string className, string periodId, int year, string no)> (key, sortedImpData.classInfo[key]));
  261. }
  262. }
  263. // var nonexistentClassNo = exsitkey.Except(sortedImpData.classInfo.Select(o => o.Key).ToList());
  264. if (nonexistentClassNo.Count() != 0)
  265. {
  266. var gradesInfo = await getGrades(schoolId);
  267. foreach (var item in nonexistentClassNo)
  268. {
  269. string gradeId = string.Empty;
  270. string periodId = periodId = sortedImpData.classInfo[item.Key].periodId;
  271. int year = sortedImpData.classInfo[item.Key].year;
  272. //確認該學段存在及輸入的年級index正確(-1後大於等於0)
  273. //if (gradesInfo.ContainsKey(sortedImpData.classInfo[item].periodId) && sortedImpData.classInfo[item].gradeIndex - 1>=0)
  274. // {
  275. // periodId = sortedImpData.classInfo[item].periodId;
  276. //gradeId = gradesInfo[sortedImpData.classInfo[item].periodId][sortedImpData.classInfo[item].gradeIndex - 1].gradeId;
  277. //}
  278. //建立新教室
  279. (string classId, string classNo, string className, string periodId, string gradeId) retCreateClassInfo =
  280. await createClassInfo(
  281. schoolId,
  282. null,
  283. sortedImpData.classInfo[item.Key].className,
  284. sortedImpData.classInfo[item.Key].no,
  285. periodId,
  286. gradeId,
  287. year);
  288. classStudNos.Add(retCreateClassInfo.classNo, new List<(string id, string no)>());
  289. classNoId.Add(retCreateClassInfo.classNo, (retCreateClassInfo.classId, retCreateClassInfo.className, periodId, gradeId, year));
  290. }
  291. }
  292. var taskWhenAll = Task.WhenAll(tasks);
  293. taskWhenAll.Wait();
  294. //-------------------------------------------------------------------------
  295. //建立學生或是更新學生,並且要確認座號是否重複
  296. //每間教室的全部座號 欲更新的教室座號
  297. //先新建帳號若出現409則進行資料更新
  298. //紀錄有重複做號的id
  299. Dictionary<string, List<string>> duplNos = new Dictionary<string, List<string>>();
  300. List<string> errorIds = new List<string>();
  301. List<object> retStuds = new List<object>();
  302. CosmosContainer cosmosContainer = _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Student");
  303. //並行處理
  304. foreach (var stud in sortedImpData.studs)
  305. {
  306. //這邊一樣要確認已存在和欲加入還有欲修改的座號。
  307. //欲修改的不會有重複
  308. string classId = null;
  309. bool isContinue = false;
  310. if (!string.IsNullOrWhiteSpace(stud.Value.no) && !string.IsNullOrWhiteSpace(stud.Value.classNo))
  311. {
  312. classId = classNoId[stud.Value.classNo].classId;
  313. (string id, string no) existNoInfo = (null, null);
  314. //檢查要更新的座號是否已存在於雲端座號(已被其他同學使用)
  315. classStudNos[stud.Value.classNo].ForEach(
  316. o =>
  317. {
  318. if (o.no.Equals(stud.Value.no) && !o.id.Equals(stud.Key))
  319. {
  320. existNoInfo = (o.id, o.no);
  321. if (duplNos.ContainsKey(stud.Value.classNo)) duplNos[stud.Value.classNo].Add(stud.Key);
  322. else duplNos.Add(stud.Value.classNo, new List<string>() { stud.Key });
  323. }
  324. });
  325. //如果不是空的代表有座號重覆到,此時要再確認這個重複座號的id,是否存在於這次的更新,而且是要更新座號的。
  326. if (!string.IsNullOrWhiteSpace(existNoInfo.id))
  327. {
  328. isContinue = true;
  329. //輪巡所有匯入的學生資料,並檢查匯入的座號。
  330. sortedImpData.classStudNo[stud.Value.classNo].ForEach(
  331. o =>
  332. {
  333. if (o.id.Equals(existNoInfo.id) && !o.no.Equals(existNoInfo.no))
  334. {
  335. //可以更新該座號
  336. isContinue = false;
  337. duplNos[stud.Value.classNo].Remove(stud.Key);
  338. return;
  339. }
  340. });
  341. }
  342. }
  343. if (isContinue) continue;
  344. (string id, string name, string pic, int year, string no, string classId, string classNo, string className, string gradeId, string periodId) tmpStudInfo
  345. = (stud.Key, stud.Value.name, null, stud.Value.year, stud.Value.no, null, stud.Value.classNo, null, null, null);
  346. using var memoryStream = new MemoryStream();
  347. using var writer = new Utf8JsonWriter(memoryStream);
  348. writer.WriteStartObject();
  349. writer.WriteString("id", stud.Key);
  350. writer.WriteString("pk", $"Base");
  351. writer.WriteString("code", $"Base-{schoolId}");
  352. writer.WriteString("schoolId", schoolId);
  353. writer.WriteNumber("year", stud.Value.year);
  354. writer.WriteString("salt", stud.Value.salt);
  355. writer.WriteString("pw", stud.Value.pw);
  356. if (string.IsNullOrWhiteSpace(stud.Value.name)) writer.WriteNull("name");
  357. else writer.WriteString("name", stud.Value.name);
  358. writer.WriteString("gender", "M");
  359. writer.WriteNull("picture");
  360. writer.WriteNull("mail");
  361. writer.WriteNull("mobile");
  362. writer.WriteNull("country");
  363. if (string.IsNullOrWhiteSpace(stud.Value.classNo)) writer.WriteNull("classId");
  364. else
  365. {
  366. writer.WriteString("classId", classId);
  367. tmpStudInfo.classId = classId;
  368. tmpStudInfo.className = classNoId[stud.Value.classNo].className;
  369. tmpStudInfo.gradeId = classNoId[stud.Value.classNo].gradeId;
  370. tmpStudInfo.periodId = classNoId[stud.Value.classNo].periodId;
  371. }
  372. if (string.IsNullOrWhiteSpace(stud.Value.no)) writer.WriteNull("no");
  373. else writer.WriteString("no", stud.Value.no);
  374. writer.WriteNull("groupId");
  375. writer.WriteNull("groupName");
  376. writer.WriteEndObject();
  377. writer.Flush();
  378. var response = await cosmosContainer.CreateItemStreamAsync(memoryStream, new PartitionKey($"Base-{schoolId}"));
  379. if (response.Status == (int)HttpStatusCode.Created)
  380. {
  381. //如果是Created則啥都不做,讓他去下面進行資料的彙整。
  382. }
  383. //查到已存在的id,則進行基本資料更新。
  384. else if (response.Status == (int)HttpStatusCode.Conflict)
  385. {
  386. response = await _azureCosmos
  387. .GetCosmosClient()
  388. .GetContainer("TEAMModelOS", "Student")
  389. .ReadItemStreamAsync(stud.Key, new PartitionKey($"Base-{schoolId}"));
  390. if (response.Status == (int)HttpStatusCode.OK)
  391. {
  392. memoryStream.Position = 0;
  393. using Stream streamId = response.ContentStream;
  394. var jsonDoc = await JsonDocument.ParseAsync(streamId);
  395. //重置
  396. writer.Reset();
  397. writer.WriteStartObject();
  398. bool isUpPwDone = false;
  399. foreach (var element in jsonDoc.RootElement.EnumerateObject())
  400. {
  401. if (!element.Name.StartsWith("_"))
  402. {
  403. switch (element.Name)
  404. {
  405. case "name":
  406. if (string.IsNullOrWhiteSpace(stud.Value.name)) goto default;
  407. else writer.WriteString("name", stud.Value.name);
  408. break;
  409. case "year":
  410. if (stud.Value.year==0) goto default;
  411. else writer.WriteNumber("year", stud.Value.year);
  412. break;
  413. case "no":
  414. if (string.IsNullOrWhiteSpace(stud.Value.no)) goto default;
  415. else writer.WriteString("no", stud.Value.no);
  416. break;
  417. case "classId":
  418. if (string.IsNullOrWhiteSpace(stud.Value.classNo)) goto default;
  419. else writer.WriteString("classId", classId);
  420. break;
  421. case "pw":
  422. case "salt":
  423. if (!isUpPwDone)
  424. {
  425. writer.WriteString("pw", stud.Value.pw);
  426. writer.WriteString("salt", stud.Value.salt);
  427. isUpPwDone = true;
  428. }
  429. break;
  430. case "picture":
  431. tmpStudInfo.pic = element.Value.GetString();
  432. goto default;
  433. default:
  434. element.WriteTo(writer);
  435. break;
  436. }
  437. }
  438. }
  439. writer.WriteEndObject();
  440. writer.Flush();
  441. //此處用Replace,不使用Upsert
  442. response = await cosmosContainer.ReplaceItemStreamAsync(memoryStream, stud.Key, new PartitionKey($"Base-{schoolId}"));
  443. if (response.Status != (int)HttpStatusCode.OK)
  444. {
  445. errorIds.Add(stud.Key);
  446. continue;
  447. }
  448. }
  449. else
  450. {
  451. errorIds.Add(stud.Key);
  452. continue;
  453. }
  454. }
  455. else
  456. {
  457. errorIds.Add(stud.Key);
  458. continue;
  459. }
  460. //整理輸出用資料
  461. retStuds.Add(
  462. new
  463. {
  464. tmpStudInfo.id,
  465. tmpStudInfo.name,
  466. tmpStudInfo.pic,
  467. tmpStudInfo.year,
  468. tmpStudInfo.no,
  469. tmpStudInfo.classId,
  470. tmpStudInfo.classNo,
  471. tmpStudInfo.className,
  472. tmpStudInfo.gradeId,
  473. tmpStudInfo.periodId
  474. });
  475. }
  476. return (retStuds, duplNos.Where(o => o.Value.Count != 0).ToDictionary(o=>o.Key,o=>o.Value), errorIds);
  477. }
  478. catch (Exception ex)
  479. {
  480. await _dingDing.SendBotMsg(
  481. $"IES5,{_option.Location},StudentController/upsertStudents()\nex:{ex.Message}{ex.StackTrace}",
  482. GroupNames.醍摩豆服務運維群組);
  483. }
  484. return (null, null, null);
  485. }
  486. /// <summary>
  487. /// 單純建立單一學生
  488. /// </summary>
  489. /// <param name="schoolId"></param>
  490. /// <param name="studCreateInfo"></param>
  491. private async Task<bool> createStudent(string schoolId, studCreateInfo studCreateInfo)
  492. {
  493. try
  494. {
  495. using var stream = new MemoryStream();
  496. using var writer = new Utf8JsonWriter(stream);
  497. writer.WriteStartObject();
  498. writer.WriteString("pk", $"Base");
  499. writer.WriteString("code", $"Base-{schoolId}");
  500. writer.WriteString("id", studCreateInfo.id);
  501. if (string.IsNullOrWhiteSpace(studCreateInfo.name)) writer.WriteNull("name");
  502. else writer.WriteString("name", studCreateInfo.name);
  503. if (string.IsNullOrWhiteSpace(studCreateInfo.gender)) writer.WriteNull("gender");
  504. else writer.WriteString("gender", studCreateInfo.gender);
  505. writer.WriteString("schoolId", schoolId);
  506. writer.WriteNumber("year", studCreateInfo.year);
  507. writer.WriteNull("picture");
  508. writer.WriteNull("mail");
  509. writer.WriteNull("mobile");
  510. writer.WriteNull("country");
  511. //Password,若沒給則使用學號當密碼
  512. string salt = Utils.CreatSaltString(8);
  513. string hashPw = string.IsNullOrWhiteSpace(studCreateInfo.pw)
  514. ? Utils.HashedPassword(studCreateInfo.id, salt)
  515. : Utils.HashedPassword(studCreateInfo.pw, salt);
  516. writer.WriteString("salt", salt);
  517. writer.WriteString("pw", hashPw);
  518. if (string.IsNullOrWhiteSpace(studCreateInfo.classId)) writer.WriteNull("classId");
  519. else writer.WriteString("classId", studCreateInfo.classId);
  520. if (string.IsNullOrWhiteSpace(studCreateInfo.no)) writer.WriteNull("no");
  521. else writer.WriteString("no", studCreateInfo.no);
  522. writer.WriteNull("groupId");
  523. writer.WriteNull("groupName");
  524. writer.WriteEndObject();
  525. writer.Flush();
  526. var response = await _azureCosmos
  527. .GetCosmosClient()
  528. .GetContainer("TEAMModelOS", "Student")
  529. .CreateItemStreamAsync(stream, new PartitionKey($"Base-{schoolId}"));
  530. if (response.Status == (int)HttpStatusCode.Created || response.Status == (int)HttpStatusCode.OK) return true;
  531. if (response.Status == (int)HttpStatusCode.Conflict) return false;
  532. else
  533. {
  534. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createStudent()\nCosmosDB Create response status = {response.Status}\nID:{studCreateInfo.id}", GroupNames.醍摩豆服務運維群組);
  535. return false;
  536. }
  537. }
  538. catch(Exception ex)
  539. {
  540. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createStudent()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  541. return false;
  542. }
  543. }
  544. /// <summary>
  545. /// 生成Class資料
  546. /// </summary>
  547. /// <param name="schoolId"></param>
  548. /// <param name="classId"></param>
  549. /// <param name="className"></param>
  550. /// <param name="students"></param>
  551. /// <returns></returns>
  552. private async Task<(string classId, string classNo, string className, string periodId, string gradeId)> createClassInfo(string schoolId, string classId, string className, string classNo, string periodId, string gradeId,int year)
  553. {
  554. //組Class JSON
  555. try
  556. {
  557. string cId = classId;
  558. using var memoryStream = new MemoryStream();
  559. using var writer = new Utf8JsonWriter(memoryStream);
  560. writer.WriteStartObject();
  561. writer.WriteString("pk", "Class");
  562. writer.WriteString("code", $"Class-{schoolId}");
  563. //如果classId是空的,則生成一組GUID。
  564. if (string.IsNullOrWhiteSpace(classId))
  565. {
  566. cId = Guid.NewGuid().ToString();
  567. writer.WriteString("id", cId);
  568. }
  569. else writer.WriteString("id", classId);
  570. if (string.IsNullOrWhiteSpace(classNo)) writer.WriteNull("no");
  571. else writer.WriteString("no", classNo);
  572. writer.WriteNull("x");
  573. writer.WriteNull("y");
  574. if (string.IsNullOrWhiteSpace(className)) writer.WriteNull("name");
  575. else writer.WriteString("name", className);
  576. writer.WritePropertyName("teacher");
  577. writer.WriteStartObject();
  578. writer.WriteNull("id");
  579. writer.WriteNull("name");
  580. writer.WriteEndObject();
  581. //if (string.IsNullOrWhiteSpace(gradeId)) writer.WriteNull("gradeId");
  582. //else writer.WriteString("gradeId", gradeId);
  583. if (string.IsNullOrWhiteSpace(periodId)) writer.WriteNull("periodId");
  584. else writer.WriteString("periodId", periodId);
  585. writer.WriteNumber("year", year);
  586. writer.WriteNull("sn");
  587. writer.WriteString("style", "smart");
  588. writer.WriteString("openType", "1");
  589. writer.WriteString("scope", "school");
  590. writer.WriteEndObject();
  591. writer.Flush();
  592. var ret = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").CreateItemStreamAsync(memoryStream, new PartitionKey($"Class-{schoolId}"));
  593. if (ret.Status != (int)HttpStatusCode.Created)
  594. {
  595. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createClassInfo()\nStatus:{ret.Status}\nSchoolId:{schoolId},ClassId:{classId}", GroupNames.醍摩豆服務運維群組);
  596. }
  597. return (cId, classNo, className, periodId, gradeId);
  598. }
  599. catch (CosmosException ex)
  600. {
  601. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createClassInfo()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  602. }
  603. catch (Exception ex)
  604. {
  605. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createClassInfo()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  606. }
  607. return (null, null, null, null, null);
  608. }
  609. /// <summary>
  610. /// 使用學校代碼查詢該校所有學生,並且在查詢該學生所屬的教室及座號,支援offset和limit操作已及ContinuationToken,若有ContinuationToken,則會優先使用ContinuationToken。
  611. /// </summary>
  612. /// <param name="schoolId"></param>
  613. /// <param name="byNameOrId">透過Name或Id來查,所以不會管學制、學級和教室</param>
  614. /// <param name="byPeriod"></param>
  615. /// <param name="byGrade"></param>
  616. /// <param name="byClassId"></param>
  617. /// <param name="offset"></param>
  618. /// <param name="limit"></param>
  619. /// <param name="token"></param>
  620. /// <returns></returns>
  621. private async Task<(List<object> students, string continuationToken)> getStudents(string schoolId, string byNameOrId = null, string byPeriod = null, string byGrade = null, string byClassId = null, int offset = -1, int limit = -1, string token = default)
  622. {
  623. try
  624. {
  625. //以學校學生角度去抓資料
  626. List<(string id, string name, string pic, int year)> listStudent = new List<(string id, string name, string pic, int year)>();
  627. string queryText = $"SELECT c.id, c.name, c.picture, c.year FROM c WHERE c.code = 'Base-{schoolId}'";
  628. //如果有選擇ClassId的話,則先取得該教室內的學生。
  629. List<string> searchId = new List<string>();
  630. if (!string.IsNullOrWhiteSpace(byClassId))
  631. {
  632. var classInfos = await getClassInfoUseId(schoolId, new List<string>() { byClassId });
  633. foreach (var classInfo in classInfos)
  634. {
  635. var students = classInfo.Value.GetProperty("students").EnumerateArray();
  636. while (students.MoveNext())
  637. {
  638. JsonElement stud = students.Current;
  639. string id = stud.GetProperty("id").GetString();
  640. searchId.Add(id);
  641. }
  642. }
  643. //將使用者過濾classId所取得的學生ID加入sql字串內
  644. if (searchId.Count != 0)
  645. {
  646. queryText = $"{queryText} AND c.id IN ({string.Join(",", searchId.Select(o => $"'{o}'"))})";
  647. }
  648. }
  649. //檢查是否有接續token及是否要在sql語法內多增加offset及limit
  650. if (string.IsNullOrWhiteSpace(token))
  651. {
  652. token = default;
  653. if (offset != -1 && limit != -1) queryText = $"{queryText} OFFSET {offset} LIMIT {limit}";
  654. }
  655. //回傳用ContinuationToken
  656. string continuationToken = string.Empty;
  657. //進行學生資料的查詢
  658. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Student")
  659. .GetItemQueryStreamIterator(
  660. queryText: queryText,
  661. continuationToken: token,
  662. requestOptions: new QueryRequestOptions()
  663. { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  664. {
  665. continuationToken = item.GetContinuationToken();
  666. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  667. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  668. {
  669. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  670. while (accounts.MoveNext())
  671. {
  672. JsonElement account = accounts.Current;
  673. listStudent.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString(), account.GetProperty("picture").GetString(), account.GetProperty("year").GetInt32()));
  674. }
  675. }
  676. //單筆查詢上限為100條,所以查完一次即返回,並且給接續token。
  677. break;
  678. }
  679. //查學生所屬的教室及座號
  680. List<object> ret = new List<object>();
  681. //查教室資訊,使用上面的學生id並透過子查詢查詢。
  682. 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}'"))}))";
  683. await foreach (Response item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School")
  684. .GetItemQueryStreamIterator(
  685. queryText: queryText,
  686. //continuationToken: token,
  687. requestOptions: new QueryRequestOptions()
  688. { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  689. {
  690. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  691. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  692. {
  693. var classrooms = json.RootElement.GetProperty("Documents").EnumerateArray();
  694. while (classrooms.MoveNext())
  695. {
  696. JsonElement classroom = classrooms.Current;
  697. var studs = classroom.GetProperty("students").EnumerateArray();
  698. while (studs.MoveNext())
  699. {
  700. JsonElement stud = studs.Current;
  701. string id = stud.GetProperty("id").GetString();
  702. //整理出前端所需的資訊
  703. var tmp = listStudent
  704. .Where(o => o.id.Equals(id, StringComparison.Ordinal))
  705. .Select(o =>
  706. new
  707. {
  708. o.id,
  709. o.name,
  710. o.pic,
  711. o.year,
  712. no = stud.GetProperty("no").GetString(),
  713. gradeId = classroom.GetProperty("gradeId").GetString(),
  714. className = classroom.GetProperty("name").GetString()
  715. });
  716. ret.AddRange(tmp);
  717. //刪除已整理完的ID
  718. listStudent.RemoveAll(o => o.id.Equals(id, StringComparison.Ordinal));
  719. }
  720. }
  721. }
  722. }
  723. var notJoinClassStuds = listStudent.Select(o =>
  724. new
  725. {
  726. o.id,
  727. o.name,
  728. o.pic,
  729. o.year,
  730. no = (string)null,
  731. gradeId = (string)null,
  732. className = (string)null
  733. });
  734. ret.AddRange(notJoinClassStuds);
  735. return (ret, continuationToken);
  736. }
  737. catch (CosmosException ex)
  738. {
  739. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getStudents()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  740. }
  741. catch (Exception ex)
  742. {
  743. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getStudents()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  744. }
  745. return (null, null);
  746. }
  747. /// <summary>
  748. /// 取得該學校的所有學生。
  749. /// </summary>
  750. /// <param name="schoolId"></param>
  751. /// <returns> [{id,name,pic,year,no,classId,classNo,className,gradeId,periodId},{id,name,pic,..}..]</returns>
  752. private async Task<List<object>> getAllStudent(string schoolId)
  753. {
  754. try
  755. {
  756. //TODO : 進階查詢選項調整、部分地方可用並行處理
  757. //以學校學生角度去抓資料
  758. Dictionary<string, List<(string id, string name, string pic, int year, string no)>> dicClassStuds = new Dictionary<string, List<(string id, string name, string pic, int year, string no)>>();
  759. List<(string id, string name, string pic, int year, string no)> notJoinClassStuds = new List<(string id, string name, string pic, int year, string no)>();
  760. string queryText = $"SELECT c.id, c.name, c.picture, c.year, c.classId, c.no FROM c WHERE c.code = 'Base-{schoolId}'";
  761. //回傳用ContinuationToken
  762. string continuationToken = string.Empty;
  763. var container = _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Student");
  764. //進行學生資料的查詢 TEAMModelOS-Student
  765. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Student")
  766. .GetItemQueryStreamIterator(
  767. queryText: queryText,
  768. requestOptions: new QueryRequestOptions()
  769. { PartitionKey = new PartitionKey($"Base-{schoolId}"), MaxItemCount = -1 }))
  770. {
  771. continuationToken = item.GetContinuationToken();
  772. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  773. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  774. {
  775. List<(string id, string name, string pic, int year,string no)> students = new List<(string id, string name, string pic, int year, string no)>();
  776. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  777. while (accounts.MoveNext())
  778. {
  779. JsonElement acc = accounts.Current;
  780. string classId = acc.GetProperty("classId").GetString();
  781. if (string.IsNullOrWhiteSpace(classId))
  782. {
  783. notJoinClassStuds.Add(
  784. (
  785. acc.GetProperty("id").GetString(),
  786. acc.GetProperty("name").GetString(),
  787. acc.GetProperty("picture").GetString(),
  788. acc.GetProperty("year").GetInt32(),
  789. acc.GetProperty("no").GetString()
  790. )
  791. );
  792. }
  793. else if(dicClassStuds.ContainsKey(classId))
  794. {
  795. dicClassStuds[classId].Add(
  796. (
  797. acc.GetProperty("id").GetString(),
  798. acc.GetProperty("name").GetString(),
  799. acc.GetProperty("picture").GetString(),
  800. acc.GetProperty("year").GetInt32(),
  801. acc.GetProperty("no").GetString()
  802. )
  803. );
  804. }
  805. else
  806. {
  807. dicClassStuds.Add(classId,
  808. new List<(string id, string name, string pic, int year, string no)>()
  809. {
  810. (
  811. acc.GetProperty("id").GetString(),
  812. acc.GetProperty("name").GetString(),
  813. acc.GetProperty("picture").GetString(),
  814. acc.GetProperty("year").GetInt32(),
  815. acc.GetProperty("no").GetString()
  816. )
  817. }
  818. );
  819. }
  820. }
  821. }
  822. }
  823. //查學生所屬的教室及座號
  824. List<object> ret = new List<object>();
  825. //查教室的資訊,用以取得gradeId,periodId資訊。
  826. var classInfos = await getClassInfoUseId(schoolId, dicClassStuds.Keys.ToList());
  827. //輪循所有教室學生的資料
  828. foreach (var classStud in dicClassStuds)
  829. {
  830. string classId = null, classNo = null, className = null, gradeId = null, periodId = null;
  831. int classYear = -1;
  832. if (classInfos.ContainsKey(classStud.Key))
  833. {
  834. classId = classInfos[classStud.Key].GetProperty("id").GetString();
  835. classNo = classInfos[classStud.Key].GetProperty("no").GetString();
  836. className = classInfos[classStud.Key].GetProperty("name").GetString();
  837. //gradeId = classInfos[classStud.Key].GetProperty("gradeId").GetString();
  838. periodId = classInfos[classStud.Key].GetProperty("periodId").GetString();
  839. if (classInfos[classStud.Key].TryGetProperty("year", out JsonElement year)) {
  840. if (year.ValueKind.Equals(JsonValueKind.Number)) {
  841. classYear = classInfos[classStud.Key].GetProperty("year").GetInt32();
  842. }
  843. }
  844. }
  845. var tmp = classStud.Value.Select(o =>
  846. new
  847. {
  848. o.id,
  849. o.name,
  850. o.pic,
  851. o.year,
  852. o.no,
  853. classId,
  854. classNo,
  855. className,
  856. gradeId,
  857. periodId,
  858. classYear
  859. });
  860. ret.AddRange(tmp);
  861. }
  862. //彙整沒有加入教室的學生
  863. notJoinClassStuds.ForEach(o=> ret.Add(
  864. new
  865. {
  866. o.id,
  867. o.name,
  868. o.pic,
  869. o.year,
  870. o.no,
  871. classId = (string)null,
  872. classNo = (string)null,
  873. className = (string)null,
  874. gradeId = (string)null,
  875. periodId = (string)null,
  876. classYear = -1
  877. }));
  878. return ret;
  879. }
  880. catch (Exception ex)
  881. {
  882. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getStudents()\n{ex.Message},{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  883. }
  884. return null;
  885. }
  886. /// <summary>
  887. /// 取得該校所有教室內的名單
  888. /// </summary>
  889. /// <param name="schoolId"></param>
  890. /// <returns></returns>
  891. public async Task<Dictionary<string, JsonElement>> getClassStudent(string schoolId, string classId = null)
  892. {
  893. try
  894. {
  895. string queryText = $"SELECT VALUE FROM c WHERE c.";
  896. //if (!string.IsNullOrWhiteSpace(classId)) queryText += $" AND c.id = '{classId}'";
  897. Dictionary<string, JsonElement> listStudent = new Dictionary<string, JsonElement>();
  898. await foreach (Response item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School")
  899. .GetItemQueryStreamIterator(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  900. {
  901. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  902. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  903. {
  904. JsonElement.ArrayEnumerator accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  905. while (accounts.MoveNext())
  906. {
  907. JsonElement account = accounts.Current;
  908. string cId = account.GetProperty("id").GetString();
  909. var students = account.GetProperty("students").Clone();
  910. listStudent.Add(cId, students);
  911. }
  912. }
  913. }
  914. return listStudent;
  915. }
  916. catch (Exception ex)
  917. {
  918. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassStudentAsync()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  919. }
  920. return null;
  921. }
  922. /// <summary>
  923. /// 刪除學生,非透過批量刪除方法。
  924. /// </summary>
  925. /// <param name="schoolId"></param>
  926. /// <param name="students"></param>
  927. /// <returns></returns>
  928. private async Task<List<string>> deleteStudents(string schoolId, JsonElement.ArrayEnumerator students)
  929. {
  930. List<string> sucIds = new List<string>();
  931. try
  932. {
  933. var exceptions = new List<Exception>();
  934. var container = _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Student");
  935. while (students.MoveNext())
  936. {
  937. string id = string.Empty;
  938. try
  939. {
  940. JsonElement student = students.Current;
  941. id = student.GetProperty("id").GetString();
  942. var ret = await container.DeleteItemStreamAsync(id, new PartitionKey($"Base-{schoolId}"));
  943. if (ret.Status == (int)HttpStatusCode.NoContent) sucIds.Add(id);
  944. }
  945. catch (CosmosException ex)
  946. {
  947. exceptions.Add(ex);
  948. }
  949. catch (Exception ex)
  950. {
  951. exceptions.Add(ex);
  952. }
  953. }
  954. if (exceptions.Count == 0) return sucIds;
  955. else if (exceptions.Count > 1) throw new AggregateException(exceptions);
  956. else if (exceptions.Count == 1) throw exceptions.Single();
  957. }
  958. catch (CosmosException ex)
  959. {
  960. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/deleteStudents()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  961. }
  962. catch (Exception ex)
  963. {
  964. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/deleteStudents()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  965. }
  966. return sucIds;
  967. }
  968. /// <summary>
  969. /// 將學生基本資料內的classId、no、groupId及groupName清為null。
  970. /// </summary>
  971. /// <param name="schoolId"></param>
  972. /// <param name="students">["id1","id2",...]</param>
  973. /// <returns></returns>
  974. private async Task<(List<string> studs, List<string> nonexistentIds, List<string> errorIds)> removeStudentClassInfo(string schoolId, JsonElement.ArrayEnumerator students)
  975. {
  976. //紀錄輸入的學生
  977. List<string> impStuds = new List<string>();
  978. //紀錄更新成功的學生
  979. List<string> sucStuds = new List<string>();
  980. //記錄沒查到的學生
  981. List<string> nonexistentIds = new List<string>();
  982. //紀錄更新出錯的學生
  983. List<string> errorIds = new List<string>();
  984. //整理輸入的學生資訊
  985. while (students.MoveNext())
  986. {
  987. JsonElement student = students.Current;
  988. impStuds.Add(student.GetString());
  989. }
  990. if (impStuds.Count == 0) return (null, null, null);
  991. string queryText = $"SELECT VALUE c FROM c WHERE c.id IN ({string.Join(",", impStuds.Select(o => $"'{o}'"))})";
  992. await foreach (Response item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Student")
  993. .GetItemQueryStreamIterator(
  994. queryText: queryText,
  995. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  996. {
  997. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  998. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  999. {
  1000. JsonElement.ArrayEnumerator docs = json.RootElement.GetProperty("Documents").EnumerateArray();
  1001. while (docs.MoveNext())
  1002. {
  1003. JsonElement doc = docs.Current;
  1004. doc.TryGetProperty("id", out var tmpId);
  1005. var id = tmpId.GetString();
  1006. using var stream = new MemoryStream();
  1007. using var writer = new Utf8JsonWriter(stream);
  1008. writer.WriteStartObject();
  1009. foreach (var element in doc.EnumerateObject())
  1010. {
  1011. Console.WriteLine(element.ToJsonString());
  1012. //將教室相關欄位清空
  1013. switch (true)
  1014. {
  1015. case bool _ when element.Name.Equals("classId", StringComparison.Ordinal):
  1016. writer.WriteNull("classId");
  1017. break;
  1018. case bool _ when element.Name.Equals("no", StringComparison.Ordinal):
  1019. writer.WriteNull("no");
  1020. break;
  1021. case bool _ when element.Name.Equals("groupId", StringComparison.Ordinal):
  1022. writer.WriteNull("groupId");
  1023. break;
  1024. case bool _ when element.Name.Equals("groupName", StringComparison.Ordinal):
  1025. writer.WriteNull("groupName");
  1026. break;
  1027. case bool _ when element.Name.StartsWith("_", StringComparison.Ordinal):
  1028. break;
  1029. default:
  1030. element.WriteTo(writer);
  1031. break;
  1032. }
  1033. }
  1034. writer.WriteEndObject();
  1035. writer.Flush();
  1036. Console.WriteLine(1111);
  1037. var ret = await _azureCosmos
  1038. .GetCosmosClient()
  1039. .GetContainer("TEAMModelOS", "Student")
  1040. .ReplaceItemStreamAsync(stream, id, new PartitionKey($"Base-{schoolId}"));
  1041. if (ret.Status == (int)HttpStatusCode.OK)
  1042. {
  1043. sucStuds.Add(id);
  1044. }
  1045. else
  1046. {
  1047. impStuds.Remove(id);
  1048. errorIds.Add(id);
  1049. await _dingDing.SendBotMsg(
  1050. $"IES5,{_option.Location},StudentController/removeStudentClassInfo(),CosmosDB response:{ret.Status}\nBase-{schoolId},id:{id}",
  1051. GroupNames.醍摩豆服務運維群組);
  1052. }
  1053. Console.WriteLine(2222);
  1054. }
  1055. }
  1056. }
  1057. Console.WriteLine(333);
  1058. //將impStuds內的資料移除sucStuds及errorIds,所得的結果就是不存在於資料庫的id。
  1059. sucStuds.ForEach(o => impStuds.Remove(o));
  1060. errorIds.ForEach(o => impStuds.Remove(o));
  1061. Console.WriteLine(444);
  1062. return (sucStuds, impStuds, errorIds);
  1063. }
  1064. /// <summary>
  1065. /// 取得教室資訊,使用classId進行查詢。
  1066. /// </summary>
  1067. /// <returns></returns>
  1068. private async Task<Dictionary<string, JsonElement>> getClassInfoUseId(string schoolId, List<string> classIds)
  1069. {
  1070. try
  1071. {
  1072. if (!(classIds == null || classIds.Count == 0))
  1073. {
  1074. string queryText = $"SELECT * FROM c WHERE c.code = 'Class-{schoolId}' AND c.id IN ({string.Join(",", classIds.Select(o => $"'{o}'"))})";
  1075. Dictionary<string, JsonElement> dicClassInfo = new Dictionary<string, JsonElement>();
  1076. await foreach (Response item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School")
  1077. .GetItemQueryStreamIterator(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  1078. {
  1079. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1080. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1081. {
  1082. var classInfos = json.RootElement.GetProperty("Documents").EnumerateArray();
  1083. while (classInfos.MoveNext())
  1084. {
  1085. JsonElement account = classInfos.Current;
  1086. string id = account.GetProperty("id").GetString();
  1087. dicClassInfo.Add(id, account.Clone());
  1088. }
  1089. }
  1090. }
  1091. return dicClassInfo;
  1092. }
  1093. else return null;
  1094. }
  1095. catch (CosmosException ex)
  1096. {
  1097. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassInfoUseId()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1098. }
  1099. catch (Exception ex)
  1100. {
  1101. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassInfoUseId()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1102. }
  1103. return null;
  1104. }
  1105. /// <summary>
  1106. /// 取得教室資訊,使用classNo進行查詢。
  1107. /// </summary>
  1108. /// <returns></returns>
  1109. private async Task<Dictionary<string, Class>> getClassInfoUseNo(string schoolId, Dictionary<string, (string className, string periodId, int year,string no)> classNos)
  1110. {
  1111. try
  1112. {
  1113. Dictionary<string, Class> dicClassInfo = new Dictionary<string, Class>();
  1114. if (!(classNos == null || classNos.Count == 0))
  1115. {
  1116. foreach (var key in classNos.Keys) {
  1117. 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}' ";
  1118. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School")
  1119. .GetItemQueryIterator<Class>(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  1120. {
  1121. dicClassInfo[item.id] = item;
  1122. }
  1123. }
  1124. return dicClassInfo;
  1125. }
  1126. else return null;
  1127. }
  1128. catch (CosmosException ex)
  1129. {
  1130. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassInfoUseId()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1131. }
  1132. catch (Exception ex)
  1133. {
  1134. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getClassInfoUseId()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1135. }
  1136. return null;
  1137. }
  1138. /// <summary>
  1139. /// 批量更新學生資訊,目前支持更新姓名、密碼、座號、性別及教室id,匯入時ClassId為必填。
  1140. /// </summary>
  1141. /// <param name="schoolId"></param>
  1142. /// <param name="students"></param>
  1143. /// <returns></returns>
  1144. private async Task<(List<object> studs, Dictionary<string, List<string>> classDuplNos, List<string> nonexistentIds, List<string> errorIds, Dictionary<string, List<string>> errorNos, List<string> errorClassId)>
  1145. updateStudents(string schoolId, JsonElement.ArrayEnumerator students)
  1146. {
  1147. try
  1148. {
  1149. //整理輸入的資料->檢查輸入資料有沒有重複座號->取得欲加入的教室資訊->查詢學生並將資料更新並寫入
  1150. //Key:id Value:學生基本資訊
  1151. var studentInfos
  1152. = new Dictionary<string, (string salt, string pw, string name, int year, string pic, string gender, string mail, string mobile, string classId, string no)>();
  1153. //用於進行座號是否重複查詢時使用
  1154. var classStuds
  1155. = new Dictionary<string, List<(string id, string salt, string pw, string name, int year, string pic, string gender, string mail, string mobile, string classId, string no)>>();
  1156. //紀錄教室"輸入"的學生座號是否有重複
  1157. var impClassDuplNo = new Dictionary<string, List<string>>();
  1158. //紀錄不存在的學生id
  1159. var nonexistentIds = new List<string>();
  1160. //紀錄跟現有雲端學生座號重複的
  1161. var errorNos = new Dictionary<string, List<string>>();
  1162. //紀錄處理錯誤的id,cosmosdb寫入時錯誤等...
  1163. var errorIds = new List<string>();
  1164. //紀錄沒找到的classId
  1165. var errorClassId = new List<string>();
  1166. //紀錄輸出結果
  1167. var retStuds = new List<object>();
  1168. //整理輸入資料
  1169. while (students.MoveNext())
  1170. {
  1171. JsonElement student = students.Current;
  1172. if (student.TryGetProperty("id", out var id))
  1173. {
  1174. //確認是否有id欄位,並且確認是否有給pw欄位,若無給或是null empty等,則使用id當密碼。
  1175. if (!string.IsNullOrWhiteSpace(id.GetString()))
  1176. {
  1177. string salt = null,
  1178. pw = null,
  1179. name = null,
  1180. gender = null,
  1181. mail = null,
  1182. mobile = null,
  1183. classId = null,
  1184. no = null;
  1185. int year = 0;
  1186. //有給pw欄位才進行處理
  1187. if (student.TryGetProperty("pw", out var tmpPw))
  1188. {
  1189. salt = Utils.CreatSaltString(8);
  1190. pw = !string.IsNullOrWhiteSpace(tmpPw.GetString())
  1191. ? Utils.HashedPassword(tmpPw.GetString(), salt)
  1192. : Utils.HashedPassword(id.GetString(), salt);
  1193. }
  1194. if (student.TryGetProperty("name", out var tmpName)) name = tmpName.GetString();
  1195. if (student.TryGetProperty("gender", out var tmpGender)) gender = tmpGender.GetString();
  1196. if (student.TryGetProperty("mail", out var tmpMail)) mail = tmpMail.GetString();
  1197. if (student.TryGetProperty("mobile", out var tmpMobile)) mobile = tmpMobile.GetString();
  1198. if (student.TryGetProperty("year", out var tmpYear)) year = tmpYear.GetInt32();
  1199. if (student.TryGetProperty("classId", out var tmpclassId)) classId = tmpclassId.GetString();
  1200. else
  1201. {
  1202. errorClassId.Add(id.GetString());
  1203. continue;
  1204. }
  1205. //如果有給該欄位,且是給空的,代表要清空
  1206. if (student.TryGetProperty("no", out var tmpNo)) no = tmpNo.GetString();
  1207. if (!studentInfos.ContainsKey(id.GetString()))
  1208. {
  1209. //如果有給classId且是給空的,則也將no設為空,後續才能將no欄位清空。
  1210. if (classId != null && classId.Length == 0) no = string.Empty;
  1211. //classId => 沒給欄位(null) 有給欄位("") 但更新一定得給教室?
  1212. if (classStuds.ContainsKey(classId))
  1213. {
  1214. classStuds[classId].Add((id.GetString(), salt, pw, name, year, null, gender, null, null, classId, no));
  1215. }
  1216. else
  1217. {
  1218. classStuds.Add(
  1219. classId,
  1220. new List<(string id, string salt, string pw, string name, int year, string pic, string gender, string mail, string mobile, string classId, string no)>()
  1221. { (id.GetString(), salt, pw, name, year, null, gender, null, null, classId, no) });
  1222. }
  1223. //pic,mail,mobile暫不支持批量更新
  1224. studentInfos.Add(id.GetString(), (salt, pw, name, year, null, gender, null, null, classId, no));
  1225. //先將id加進去後面再做刪除動作
  1226. nonexistentIds.Add(id.GetString());
  1227. }
  1228. }
  1229. }
  1230. }
  1231. //檢查所有輸入的班級資料內,學生座號是否有重複。
  1232. for (int ii = 0; ii <= classStuds.Values.Count - 1; ii++)
  1233. {
  1234. var duplicateNo = classStuds.ElementAt(ii).Value.GroupBy(o => o.no).Where(o => o.Count() > 1).Select(o => o.Key).ToList();
  1235. duplicateNo.Remove("");
  1236. duplicateNo.Remove(null);
  1237. var wrongStuds = classStuds.ElementAt(ii).Value.Where(o => duplicateNo.Contains(o.no)).Select(o => o).ToList();
  1238. impClassDuplNo.Add(classStuds.ElementAt(ii).Key, wrongStuds.Select(o => o.id).ToList());
  1239. wrongStuds.ForEach(o => { classStuds.ElementAt(ii).Value.Remove(o); nonexistentIds.Remove(o.id); });
  1240. classStuds[classStuds.ElementAt(ii).Key] = classStuds.ElementAt(ii).Value;
  1241. }
  1242. //查詢欲加入的教室資訊。
  1243. var classInfo = await getClassInfoUseId(schoolId, classStuds.Keys.ToList());
  1244. //準備查詢db資料
  1245. CosmosContainer cosmosContainer = _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Student");
  1246. //查要移除教室或是沒加入教室的學生
  1247. foreach (var item in classStuds)
  1248. {
  1249. //如果沒有任何學生要更新,則跳過該間教室。
  1250. if (item.Value.Count == 0) continue;
  1251. string classId = null, className = null, classNo = null, gradeId = null, periodId = null;
  1252. //如果教室不存在的話(填錯教室之類的狀況),則記錄教室的id及學生id。
  1253. if (classInfo.ContainsKey(item.Key))
  1254. {
  1255. classId = item.Key;
  1256. className = classInfo[item.Key].GetProperty("name").GetString();
  1257. classNo = classInfo[item.Key].GetProperty("no").GetString();
  1258. gradeId = classInfo[item.Key].GetProperty("gradeId").GetString();
  1259. periodId = classInfo[item.Key].GetProperty("periodId").GetString();
  1260. }
  1261. else if (item.Key.Length == 0)
  1262. {
  1263. }
  1264. else
  1265. {
  1266. //沒查到有該間教室的資訊,故將該間教室的ID及學生資料清單記起來,並且跳過不處理該資料。
  1267. errorClassId.Add(item.Key);
  1268. item.Value.ForEach(o => nonexistentIds.Remove(o.id));
  1269. continue;
  1270. }
  1271. //檢查座號是否有重複
  1272. //若只是改基本資料,該處還是會查到相同的座號。
  1273. var sutdNos = item.Value.Select(o => o.no).ToList();
  1274. var existNos = await checkStudNo(schoolId, item.Key, sutdNos);
  1275. //更新並寫入學生資料
  1276. if (item.Value.Count != 0)
  1277. {
  1278. //查學生的基本資料(該間教室全部的學生)
  1279. string queryText = $"SELECT * FROM c WHERE c.id IN ({string.Join(",", item.Value.Select(o => $"'{o.id}'"))})";
  1280. List<JsonElement> listStudent = new List<JsonElement>();
  1281. await foreach (Response responseItem in cosmosContainer
  1282. .GetItemQueryStreamIterator(
  1283. queryText: queryText,
  1284. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  1285. {
  1286. using var json = await JsonDocument.ParseAsync(responseItem.ContentStream);
  1287. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1288. {
  1289. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1290. while (accounts.MoveNext())
  1291. {
  1292. JsonElement account = accounts.Current;
  1293. string id = account.GetProperty("id").GetString();
  1294. nonexistentIds.Remove(id);
  1295. //舊的座號,基本上不會重複,但可能會是空的
  1296. string no = account.GetProperty("no").GetString();
  1297. //用來記錄最後更改完的資料
  1298. (string salt, string pw, string name, int year, string pic, string gender, string mail, string mobile, string classId, string no) tmpData
  1299. = (studentInfos[id].salt, studentInfos[id].pw, studentInfos[id].name, studentInfos[id].year, studentInfos[id].pic, studentInfos[id].gender, studentInfos[id].mail, studentInfos[id].mobile, studentInfos[id].classId, studentInfos[id].no);
  1300. bool isUpPwDone = false;
  1301. bool isWrong = false;
  1302. //開始組Json
  1303. using var memoryStream = new MemoryStream();
  1304. using var writer = new Utf8JsonWriter(memoryStream);
  1305. writer.WriteStartObject();
  1306. foreach (var element in account.EnumerateObject())
  1307. {
  1308. if (isWrong) break;
  1309. switch (true)
  1310. {
  1311. case bool _ when element.Name.Equals("name", StringComparison.Ordinal):
  1312. if (string.IsNullOrWhiteSpace(studentInfos[id].name))
  1313. {
  1314. element.WriteTo(writer);
  1315. tmpData.name = element.Value.GetString();
  1316. }
  1317. else
  1318. {
  1319. writer.WriteString("name", studentInfos[id].name);
  1320. }
  1321. break;
  1322. case bool _ when element.Name.Equals("pw", StringComparison.Ordinal):
  1323. case bool _ when element.Name.Equals("salt", StringComparison.Ordinal):
  1324. if (!isUpPwDone && !string.IsNullOrWhiteSpace(studentInfos[id].salt) && !string.IsNullOrWhiteSpace(studentInfos[id].pw))
  1325. {
  1326. writer.WriteString("salt", studentInfos[id].salt);
  1327. writer.WriteString("pw", studentInfos[id].pw);
  1328. isUpPwDone = true;
  1329. }
  1330. break;
  1331. case bool _ when element.Name.Equals("gender", StringComparison.Ordinal):
  1332. if (string.IsNullOrWhiteSpace(studentInfos[id].gender))
  1333. {
  1334. element.WriteTo(writer);
  1335. tmpData.gender = element.Value.GetString();
  1336. }
  1337. else
  1338. {
  1339. writer.WriteString("gender", studentInfos[id].gender);
  1340. }
  1341. break;
  1342. case bool _ when element.Name.Equals("year", StringComparison.Ordinal):
  1343. if (studentInfos[id].year==0)
  1344. {
  1345. element.WriteTo(writer);
  1346. tmpData.year = element.Value.GetInt32();
  1347. }
  1348. else
  1349. {
  1350. writer.WriteNumber("year", studentInfos[id].year);
  1351. }
  1352. break;
  1353. case bool _ when element.Name.Equals("classId", StringComparison.Ordinal):
  1354. if (studentInfos[id].classId != null && studentInfos[id].classId.Length == 0)
  1355. {
  1356. writer.WriteNull("classId");
  1357. writer.WriteNull("groupId");
  1358. writer.WriteNull("groupName");
  1359. tmpData.classId = null;
  1360. }
  1361. else if (string.IsNullOrWhiteSpace(studentInfos[id].classId))
  1362. {
  1363. element.WriteTo(writer);
  1364. tmpData.classId = element.Value.GetString();
  1365. }
  1366. else
  1367. {
  1368. writer.WriteString("classId", studentInfos[id].classId);
  1369. }
  1370. break;
  1371. case bool _ when element.Name.Equals("no", StringComparison.Ordinal):
  1372. //移除座號的話會給空的
  1373. if (studentInfos[id].no != null && studentInfos[id].no.Length == 0)
  1374. {
  1375. writer.WriteNull("no");
  1376. tmpData.no = null;
  1377. }
  1378. else if (string.IsNullOrWhiteSpace(studentInfos[id].no))
  1379. {
  1380. element.WriteTo(writer);
  1381. tmpData.no = element.Value.GetString();
  1382. }
  1383. else
  1384. {
  1385. //如果要更新的座號,跟已存在的座號相同,則不進行更新。
  1386. //沒有設定過舊no,或舊座號與新座號不同,則要進行重複座號的檢查。 舊no=null or 舊no!=新no
  1387. if (string.IsNullOrWhiteSpace(no) || (!string.IsNullOrWhiteSpace(no) && !no.Equals(studentInfos[id].no)))
  1388. {
  1389. //如果有檢查到新座號和舊座號重複
  1390. if (existNos.Any(o => o.Item2.Contains(studentInfos[id].no))) //.Contains(studentInfos[id].no))
  1391. {
  1392. if (errorNos.ContainsKey(id))
  1393. {
  1394. errorNos[id].Add(studentInfos[id].no);
  1395. }
  1396. else
  1397. {
  1398. errorNos.Add(id, new List<string>() { studentInfos[id].no });
  1399. }
  1400. isWrong = true;
  1401. break;
  1402. }
  1403. }
  1404. writer.WriteString("no", studentInfos[id].no);
  1405. }
  1406. break;
  1407. case bool _ when element.Name.StartsWith("_", StringComparison.Ordinal):
  1408. break;
  1409. default:
  1410. element.WriteTo(writer);
  1411. break;
  1412. }
  1413. }
  1414. //如果有錯誤,如座號重覆等,就會跳過該次更新。
  1415. if (isWrong)
  1416. {
  1417. await writer.DisposeAsync();
  1418. continue;
  1419. }
  1420. //若密碼和鹽沒有更新,就把舊的資料寫回去
  1421. if (!isUpPwDone)
  1422. {
  1423. writer.WriteString("salt", account.GetProperty("salt").GetString());
  1424. writer.WriteString("pw", account.GetProperty("pw").GetString());
  1425. }
  1426. writer.WriteEndObject();
  1427. writer.Flush();
  1428. try
  1429. {
  1430. var ret = await cosmosContainer.ReplaceItemStreamAsync(memoryStream, id, new PartitionKey($"Base-{schoolId}"));
  1431. //將更新完的id從字典內移除,保留沒查到的。
  1432. if (ret.Status == (int)HttpStatusCode.OK)
  1433. {
  1434. nonexistentIds.Remove(id);
  1435. retStuds.Add(new { id, tmpData.name, tmpData.pic, tmpData.year, tmpData.no, classId, classNo, className, gradeId, periodId });
  1436. }
  1437. else errorIds.Add(id);
  1438. }
  1439. catch (CosmosException ex)
  1440. {
  1441. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/updateStudents()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1442. errorIds.Add(id);
  1443. }
  1444. catch (Exception ex)
  1445. {
  1446. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/updateStudents()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1447. errorIds.Add(id);
  1448. }
  1449. }
  1450. }
  1451. //將輸入不存在的資料移除。
  1452. nonexistentIds.ForEach(o => studentInfos.Remove(o));
  1453. }
  1454. }
  1455. }
  1456. errorClassId.ForEach(o => impClassDuplNo.Remove(o));
  1457. return (retStuds, impClassDuplNo.Where(o => o.Value.Count != 0).ToDictionary(o => o.Key, o => o.Value), nonexistentIds, errorIds, errorNos, errorClassId);
  1458. }
  1459. catch (CosmosException ex)
  1460. {
  1461. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/updateStudents()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1462. }
  1463. catch (Exception ex)
  1464. {
  1465. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/updateStudents()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1466. }
  1467. return (null, null, null, null, null, null);
  1468. }
  1469. /// <summary>
  1470. /// 創建學生帳號,目前SDK4.0預覽版還不支援批量創建(TransactionalBatch),待SDK正式發行時在優化此代碼。
  1471. /// </summary>
  1472. /// <param name="userStudents"></param>
  1473. /// <returns>已存在的ID</returns>
  1474. private async Task<(bool isSuc, List<string> existId)> createStudents(List<Student> userStudents)
  1475. {
  1476. var existId = new List<string>();
  1477. var exceptions = new List<Exception>();
  1478. try
  1479. {
  1480. var container = _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Student");
  1481. Parallel.ForEach(userStudents, async item =>
  1482. {
  1483. try
  1484. {
  1485. await container.CreateItemAsync(item);
  1486. }
  1487. catch (CosmosException ex)
  1488. {
  1489. if (ex.Status == (int)HttpStatusCode.Conflict) existId.Add(item.id);
  1490. else exceptions.Add(ex);
  1491. }
  1492. catch (Exception ex)
  1493. {
  1494. exceptions.Add(ex);
  1495. }
  1496. });
  1497. if (exceptions.Count == 0) return (true, existId);
  1498. else if (exceptions.Count > 1) throw new AggregateException(exceptions);
  1499. else if (exceptions.Count == 1) throw exceptions.Single();
  1500. }
  1501. catch (AggregateException ex)
  1502. {
  1503. Console.WriteLine(ex.Message);
  1504. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createStudents()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1505. }
  1506. catch (Exception ex)
  1507. {
  1508. Console.WriteLine(ex.Message);
  1509. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/createStudents()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1510. }
  1511. return (false, existId);
  1512. }
  1513. /// <summary>
  1514. /// 取得該教室的學生座號,若有給座號LIST,則座號存在才會被查到;反之,若沒給則會將該間教室所有座號抓出來。
  1515. /// </summary>
  1516. /// <param name="schoolId"></param>
  1517. /// <param name="classId"></param>
  1518. /// <param name="nos"></param>
  1519. /// <returns></returns>
  1520. private async Task<List<(string id,string no)>> checkStudNo(string schoolId, string classId, List<string> nos = null)
  1521. {
  1522. List<(string id, string no)> ret = new List<(string id, string no)>();
  1523. string queryText = $"SELECT c.id, c.no FROM c WHERE c.classId = '{classId}' AND c.code = 'Base-{schoolId}'";
  1524. if (nos != null) queryText += $"AND c.no IN ({string.Join(",", nos.Select(o => $"'{o}'"))})";
  1525. await foreach (Response item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Student")
  1526. .GetItemQueryStreamIterator(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  1527. {
  1528. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1529. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1530. {
  1531. var classInfos = json.RootElement.GetProperty("Documents").EnumerateArray();
  1532. while (classInfos.MoveNext())
  1533. {
  1534. JsonElement account = classInfos.Current;
  1535. string id = account.GetProperty("id").GetString();
  1536. string no = account.GetProperty("no").GetString();
  1537. ret.Add((id, no));
  1538. }
  1539. }
  1540. }
  1541. return ret;
  1542. }
  1543. /// <summary>
  1544. /// 取得年級資訊
  1545. /// </summary>
  1546. /// <param name="schoolId"></param>
  1547. /// <returns>Key:periodId Vaule:list gradeInfo</returns>
  1548. private async Task<Dictionary<string, List<(int gradeId, string gradeName)>>> getGrades(string schoolId)
  1549. {
  1550. try
  1551. {
  1552. //Key:學制 Value:年級資訊list
  1553. Dictionary<string, List<(int gradeId, string gradeName)>> dicPeriod = new Dictionary<string, List<(int gradeId, string gradeName)>>();
  1554. var response = await _azureCosmos
  1555. .GetCosmosClient()
  1556. .GetContainer("TEAMModelOS", "School")
  1557. .ReadItemStreamAsync(schoolId, new PartitionKey("Base"));
  1558. if (response.Status != (int)HttpStatusCode.OK) return null;
  1559. using Stream stream = response.ContentStream;
  1560. var jsonDoc = await JsonDocument.ParseAsync(stream);
  1561. var emumObject = jsonDoc.RootElement.EnumerateObject();
  1562. var period = jsonDoc.RootElement.GetProperty("period").EnumerateArray();
  1563. while (period.MoveNext())
  1564. {
  1565. List<(int gradeId, string gradeName)> gradeInfos = new List<(int gradeId, string gradeName)>();
  1566. JsonElement jsonPeriod = period.Current;
  1567. var periodId = jsonPeriod.GetProperty("id").GetString();
  1568. var grades = jsonPeriod.GetProperty("grades").ToObject<List<string>>();
  1569. for (int index = 0; index < grades.Count; index++) {
  1570. gradeInfos.Add((index, grades[index]));
  1571. }
  1572. //var grades = jsonPeriod.GetProperty("grades").EnumerateArray();
  1573. //while (grades.MoveNext())
  1574. //{
  1575. // JsonElement grade = grades.Current;
  1576. // var gradeId = grade.GetInt32();
  1577. // var gradeName = grade.GetProperty("name").GetString();
  1578. // gradeInfos.Add((gradeId, gradeName));
  1579. //}
  1580. dicPeriod.Add(periodId, gradeInfos);
  1581. }
  1582. return dicPeriod;
  1583. }
  1584. catch(Exception ex)
  1585. {
  1586. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/getGrades()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1587. return null;
  1588. }
  1589. }
  1590. private struct studCreateInfo
  1591. {
  1592. public studCreateInfo(string id, string name, string gender, int year, string pw, string classId, string no,string periodId)
  1593. {
  1594. this.id = id;
  1595. this.name = name;
  1596. this.gender = gender;
  1597. this.year = year;
  1598. this.pw = pw;
  1599. this.classId = classId;
  1600. this.no = no;
  1601. this.periodId = periodId;
  1602. }
  1603. public string id { get; }
  1604. public string name { get; }
  1605. public string gender { get; }
  1606. public int year { get; }
  1607. public string pw { get; }
  1608. public string classId { get; }
  1609. public string no { get; }
  1610. public string periodId { get; set; }
  1611. }
  1612. /// <summary>
  1613. /// 學生登入
  1614. /// </summary>
  1615. /// <param name = "request" ></ param >
  1616. [AllowAnonymous]
  1617. [HttpPost("login")]
  1618. public async Task<IActionResult> Login(JsonElement request)
  1619. {
  1620. try
  1621. {
  1622. var client = _azureCosmos.GetCosmosClient();
  1623. var schoolClient = client.GetContainer("TEAMModelOS", "School");
  1624. var teacherClient = client.GetContainer("TEAMModelOS", "Teacher");
  1625. var studentClient = client.GetContainer("TEAMModelOS", "Student");
  1626. //參數取得
  1627. if (!request.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
  1628. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1629. if (!request.TryGetProperty("pw", out JsonElement pw)) return BadRequest();
  1630. var response = await studentClient.ReadItemStreamAsync(id.GetString(), new PartitionKey($"Base-{school_code.GetString().ToLower()}"));
  1631. if (response.Status == 200)
  1632. {
  1633. var rjson = await JsonDocument.ParseAsync(response.ContentStream);
  1634. rjson.RootElement.TryGetProperty("salt", out JsonElement salt);
  1635. rjson.RootElement.TryGetProperty("pw", out JsonElement dbpw);
  1636. rjson.RootElement.TryGetProperty("name", out JsonElement name);
  1637. rjson.RootElement.TryGetProperty("picture", out JsonElement picture);
  1638. rjson.RootElement.TryGetProperty("classId", out JsonElement classId);
  1639. rjson.RootElement.TryGetProperty("no", out JsonElement no);
  1640. rjson.RootElement.TryGetProperty("groupId", out JsonElement groupId);
  1641. rjson.RootElement.TryGetProperty("groupName", out JsonElement groupName);
  1642. var HashedPW = Utils.HashedPassword(pw.ToString(), salt.ToString());
  1643. if (HashedPW.Equals(dbpw.GetString()))
  1644. {
  1645. //班級課程
  1646. object classinfo = null;
  1647. List<object> courses = new List<object>();
  1648. ////校本
  1649. //取得所屬預設班級信息
  1650. if (!classId.ValueKind.Equals(JsonValueKind.Null) && classId.ValueKind.Equals(JsonValueKind.String))
  1651. {
  1652. var query = $"SELECT c.code, c.id, c.name, c.periodId, c.gradeId FROM c WHERE c.id = '{classId.GetString()}'";
  1653. await foreach (var item in schoolClient.GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{school_code}") }))
  1654. {
  1655. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1656. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1657. {
  1658. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1659. {
  1660. classinfo = obj.ToObject<object>();
  1661. }
  1662. }
  1663. }
  1664. }
  1665. //取得該學生跑班課名單ID
  1666. List<string> stulistidsSch = new List<string>();
  1667. var querysl = $"SELECT c.id FROM c JOIN students IN c.students WHERE students.id = '{id.GetString()}' AND students.code = 'Base-{school_code}'";
  1668. await foreach (var item in schoolClient.GetItemQueryStreamIterator(queryText: querysl, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList-{school_code}") }))
  1669. {
  1670. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1671. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1672. {
  1673. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1674. {
  1675. stulistidsSch.Add(obj.GetProperty("id").ToString());
  1676. }
  1677. }
  1678. }
  1679. //取得該學生的學校課程名單
  1680. var queryc = $"SELECT DISTINCT c.id, c.name, schedule.class, schedule.time, schedule.notice, c.scope FROM c JOIN schedule IN c.schedule WHERE (schedule.class.id = '{classId}' AND schedule.stulist = null) OR (ARRAY_CONTAINS({JsonSerializer.Serialize(stulistidsSch)}, schedule.stulist, true))";
  1681. await foreach (var item in schoolClient.GetItemQueryStreamIterator(queryText: queryc, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{school_code}") }))
  1682. {
  1683. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1684. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1685. {
  1686. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1687. {
  1688. courses.Add(obj.ToObject<object>());
  1689. }
  1690. }
  1691. }
  1692. ////個人
  1693. //取得該學生跑班課名單ID
  1694. Dictionary<string, Dictionary<string, string>> stulistidsTea = new Dictionary<string, Dictionary<string, string>>();
  1695. var queryslt = $"SELECT c.id, c.course.id as courseId, c.course.code as courseCode FROM c JOIN students IN c.students WHERE students.id = '{id.GetString()}' AND students.code = 'Base-{school_code}'";
  1696. await foreach (var item in teacherClient.GetItemQueryStreamIterator(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("StuList") }))
  1697. {
  1698. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1699. var js = json.RootElement.ToJsonString();
  1700. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1701. {
  1702. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1703. {
  1704. string courseCode = "";
  1705. if (obj.TryGetProperty("courseCode", out var code)) {
  1706. courseCode = code.GetString();
  1707. }
  1708. string courseId = "";
  1709. if (obj.TryGetProperty("courseId", out var cosid))
  1710. {
  1711. courseId = cosid.GetString();
  1712. }
  1713. string stulistId = "";
  1714. if (obj.TryGetProperty("id", out var listId))
  1715. {
  1716. stulistId = listId.GetString();
  1717. }
  1718. if (!string.IsNullOrEmpty(courseCode)) {
  1719. if (!stulistidsTea.ContainsKey(courseCode))
  1720. {
  1721. Dictionary<string, string> pCourseIdDic = new Dictionary<string, string>();
  1722. pCourseIdDic.Add(courseId, stulistId);
  1723. stulistidsTea.Add(courseCode, pCourseIdDic);
  1724. }
  1725. else
  1726. {
  1727. if (!stulistidsTea[courseCode].ContainsKey(courseId))
  1728. {
  1729. stulistidsTea[courseCode].Add(courseId, stulistId);
  1730. }
  1731. }
  1732. }
  1733. }
  1734. }
  1735. }
  1736. //取得該學生的老師個人課程名單
  1737. foreach (KeyValuePair<string, Dictionary<string, string>> item in stulistidsTea)
  1738. {
  1739. string courseCode = item.Key;
  1740. Dictionary<string, string> courseIdDic = item.Value;
  1741. string stucourseWhere = string.Empty;
  1742. foreach (KeyValuePair<string, string> itemDic in courseIdDic) {
  1743. string courseId = itemDic.Key;
  1744. string stuListId = itemDic.Value;
  1745. if(!string.IsNullOrWhiteSpace(stucourseWhere))
  1746. {
  1747. stucourseWhere += " OR ";
  1748. }
  1749. stucourseWhere += $"( c.id = '{courseId}' AND schedule.stulist = '{stuListId}' )";
  1750. }
  1751. var querycst = $"SELECT DISTINCT c.id, c.name, schedule.class, schedule.time, schedule.notice, c.scope FROM c JOIN schedule IN c.schedule WHERE {stucourseWhere}";
  1752. await foreach (var itemcs in teacherClient.GetItemQueryStreamIterator(queryText: querycst, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{courseCode}") }))
  1753. {
  1754. using var json = await JsonDocument.ParseAsync(itemcs.ContentStream);
  1755. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1756. {
  1757. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1758. {
  1759. courses.Add(obj.ToObject<object>());
  1760. }
  1761. }
  1762. }
  1763. }
  1764. // BLOB(學校,唯讀)
  1765. var (blob_uri, blob_sas) = _azureStorage.GetBlobContainerSAS(school_code.GetString().ToLower(), BlobContainerSasPermissions.Read);
  1766. //換取AuthToken,提供給前端
  1767. var auth_token = JwtAuthExtension.CreateAuthToken(_option.HostName, id.GetString(), name.GetString(), picture.GetString(), _option.JwtSecretKey, schoolID: school_code.GetString(), roles: new[] { "student" });
  1768. return Ok(new { error = 0, auth_token, blob_uri, blob_sas, classinfo, courses });
  1769. }
  1770. else
  1771. {
  1772. return Ok(new { error = 1, message = "账号或密码错误" });
  1773. }
  1774. }
  1775. else
  1776. {
  1777. return Ok(new { error = 2, message = "無此帳號存在" });
  1778. }
  1779. }
  1780. catch (Exception ex)
  1781. {
  1782. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/login()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1783. return BadRequest();
  1784. }
  1785. }
  1786. //查询学生名单详情
  1787. [ProducesDefaultResponseType]
  1788. //[AuthToken(Roles = "Teacher")]
  1789. [HttpPost("get-summary-student")]
  1790. public async Task<IActionResult> getSummary(JsonElement requert)
  1791. {
  1792. try
  1793. {
  1794. if (!requert.TryGetProperty("students", out JsonElement students)) return BadRequest();
  1795. //if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  1796. var client = _azureCosmos.GetCosmosClient();
  1797. List<Students> stuList = students.ToObject<List<Students>>();
  1798. List<object> stus = new List<object>();
  1799. foreach (Students stu in stuList) {
  1800. var query = $"select c.id,c.name,c.picture,c.classId,c.code,c.groupId,c.groupName,c.no from c where c.id = '{stu.id}'";
  1801. await foreach (var item in client.GetContainer("TEAMModelOS", "Student").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{stu.code}") }))
  1802. {
  1803. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1804. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1805. {
  1806. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1807. {
  1808. stus.Add(obj.ToObject<object>());
  1809. }
  1810. }
  1811. }
  1812. }
  1813. return Ok(new { stus });
  1814. }
  1815. catch (Exception ex)
  1816. {
  1817. await _dingDing.SendBotMsg($"OS,{_option.Location},student/get-summary-student()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1818. return BadRequest();
  1819. }
  1820. }
  1821. /// <summary>
  1822. /// 學生簡易登入
  1823. /// </summary>
  1824. /// <param name = "request" ></ param >
  1825. [AllowAnonymous]
  1826. [HttpPost("login-simple")]
  1827. public async Task<IActionResult> LoginSimple(JsonElement request)
  1828. {
  1829. try
  1830. {
  1831. var client = _azureCosmos.GetCosmosClient();
  1832. var schoolClient = client.GetContainer("TEAMModelOS", "School");
  1833. var studentClient = client.GetContainer("TEAMModelOS", "Student");
  1834. //參數取得
  1835. if (!request.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
  1836. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1837. if (!request.TryGetProperty("pw", out JsonElement pw)) return BadRequest();
  1838. var response = await studentClient.ReadItemStreamAsync(id.GetString(), new PartitionKey($"Base-{school_code.GetString().ToLower()}"));
  1839. if (response.Status == 200)
  1840. {
  1841. var rjson = await JsonDocument.ParseAsync(response.ContentStream);
  1842. rjson.RootElement.TryGetProperty("salt", out JsonElement salt);
  1843. rjson.RootElement.TryGetProperty("pw", out JsonElement dbpw);
  1844. rjson.RootElement.TryGetProperty("name", out JsonElement name);
  1845. rjson.RootElement.TryGetProperty("picture", out JsonElement picture);
  1846. rjson.RootElement.TryGetProperty("classId", out JsonElement classId);
  1847. rjson.RootElement.TryGetProperty("no", out JsonElement no);
  1848. rjson.RootElement.TryGetProperty("groupId", out JsonElement groupId);
  1849. rjson.RootElement.TryGetProperty("groupName", out JsonElement groupName);
  1850. dynamic user = new ExpandoObject();
  1851. user.no = no;
  1852. user.groupId = groupId;
  1853. user.groupName = groupName;
  1854. var HashedPW = Utils.HashedPassword(pw.ToString(), salt.ToString());
  1855. if (HashedPW.Equals(dbpw.GetString()))
  1856. {
  1857. //取得所屬預設班級信息
  1858. object classinfo = null;
  1859. if (!classId.ValueKind.Equals(JsonValueKind.Null) && classId.ValueKind.Equals(JsonValueKind.String))
  1860. {
  1861. var query = $"SELECT c.id, c.no, c.name FROM c WHERE c.id = '{classId.GetString()}'";
  1862. await foreach (var item in schoolClient.GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{school_code}") }))
  1863. {
  1864. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1865. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1866. {
  1867. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1868. {
  1869. classinfo = obj.ToObject<object>();
  1870. }
  1871. }
  1872. }
  1873. }
  1874. //換取AuthToken,提供給前端
  1875. var auth_token = JwtAuthExtension.CreateAuthToken(_option.HostName, id.GetString(), name.GetString(), picture.GetString(), _option.JwtSecretKey, schoolID: school_code.GetString(), roles: new[] { "student" });
  1876. //其他訊息
  1877. dynamic school = new ExpandoObject();
  1878. //回傳
  1879. return Ok(new { error = 0, auth_token, classinfo, user });
  1880. }
  1881. else
  1882. {
  1883. return Ok(new { error = 1, message = "Invalid account or password" });
  1884. }
  1885. }
  1886. else
  1887. {
  1888. return Ok(new { error = 2, message = "Invalid account" });
  1889. }
  1890. }
  1891. catch (Exception ex)
  1892. {
  1893. await _dingDing.SendBotMsg($"IES5,{_option.Location},StudentController/login-simple()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1894. return BadRequest();
  1895. }
  1896. }
  1897. //TODO 此API需處理對應前端返回的相關數據
  1898. [ProducesDefaultResponseType]
  1899. [ AuthToken(Roles = "student")]
  1900. [HttpPost("get-school-info")]
  1901. public async Task<IActionResult> GetSchoolInfo(JsonElement requert)
  1902. {
  1903. try
  1904. {
  1905. var (id, _, _, school) = HttpContext.GetAuthTokenInfo();
  1906. var client = _azureCosmos.GetCosmosClient();
  1907. List<string> roles = new List<string>();
  1908. List<string> permissions = new List<string>();
  1909. int size = 0;
  1910. var response = await client.GetContainer("TEAMModelOS", "Student").ReadItemStreamAsync(id, new PartitionKey($"Base-{school}"));
  1911. if (response.Status == 200)
  1912. {
  1913. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  1914. if (json.RootElement.TryGetProperty("size", out JsonElement _size) && _size.ValueKind == JsonValueKind.Number)
  1915. {
  1916. size = _size.GetInt32();
  1917. }
  1918. if (json.RootElement.TryGetProperty("roles", out JsonElement _roles) && _roles.ValueKind != JsonValueKind.Null)
  1919. {
  1920. foreach (var obj in _roles.EnumerateArray())
  1921. {
  1922. roles.Add(obj.GetString());
  1923. }
  1924. }
  1925. if (json.RootElement.TryGetProperty("permissions", out JsonElement _permissions) && _permissions.ValueKind != JsonValueKind.Null)
  1926. {
  1927. foreach (var obj in _permissions.EnumerateArray())
  1928. {
  1929. permissions.Add(obj.GetString());
  1930. }
  1931. }
  1932. }
  1933. else //無此學校資料
  1934. {
  1935. return Ok(new { status = 404 });
  1936. }
  1937. if (roles.Count == 0)
  1938. {
  1939. roles.Add("student");
  1940. }
  1941. //TODO JJ,调整为取得学校基础设置数据,取代下方學校學制、年級
  1942. object school_base = null;
  1943. response = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(school, new PartitionKey("Base"));
  1944. if (response.Status == 200)
  1945. {
  1946. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  1947. school_base = json.RootElement.ToObject<object>();
  1948. }
  1949. //取得班级
  1950. List<object> school_classes = new List<object>();
  1951. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: $"SELECT c.id,c.x,c.y,c.name,c.year,c.teacher,c.periodId,c.gradeId,c.room,c.sn,c.no,c.style,c.status,c.openType,c.scope, ARRAY_LENGTH(c.students) AS studCount FROM c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{school}") }))
  1952. {
  1953. var jsonc = await JsonDocument.ParseAsync(item.ContentStream);
  1954. foreach (var classeinfo in jsonc.RootElement.GetProperty("Documents").EnumerateArray())
  1955. {
  1956. school_classes.Add(classeinfo.ToObject<object>());
  1957. }
  1958. }
  1959. //取得教室
  1960. List<Room> school_rooms = new List<Room>();
  1961. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<Room>(queryText: $"select value(c) from c ",
  1962. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Room-{school}") }))
  1963. {
  1964. school_rooms.Add(item);
  1965. }
  1966. return Ok(new { school_base, school_classes, school_rooms, status =200});
  1967. }
  1968. catch(CosmosException ex) {
  1969. return Ok(new { status=ex.Status }); ;
  1970. }
  1971. catch (Exception ex)
  1972. {
  1973. await _dingDing.SendBotMsg($"IES5,{_option.Location},Student/get-school-info()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1974. return BadRequest();
  1975. }
  1976. }
  1977. }
  1978. }