StudentController.cs 161 KB

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