StudentController.cs 122 KB

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