StudentService.cs 169 KB

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