StudentService.cs 179 KB

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