StudentService.cs 176 KB

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