StudentService.cs 168 KB

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