StudentService.cs 175 KB

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