StudentController.cs 109 KB

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