StudentService.cs 177 KB

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