StudentService.cs 168 KB

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