StudentController.cs 113 KB

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