StudentService.cs 167 KB

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