OpenApiService.cs 131 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439
  1. using Azure;
  2. using Azure.Cosmos;
  3. using HTEXLib.COMM.Helpers;
  4. using Microsoft.AspNetCore.Http;
  5. using Microsoft.Azure.Cosmos.Table;
  6. using Microsoft.Azure.Functions.Worker.Http;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Net;
  12. using System.Net.Http;
  13. using System.Text;
  14. using System.Text.Json;
  15. using System.Threading.Tasks;
  16. using TEAMModelOS.Filter;
  17. using TEAMModelOS.SDK;
  18. using TEAMModelOS.SDK.DI;
  19. using TEAMModelOS.SDK.Extension;
  20. using TEAMModelOS.SDK.Models;
  21. using TEAMModelOS.SDK.Models.Table;
  22. using TEAMModelOS.SDK.Helper.Common.ReflectorExtensions;
  23. using TEAMModelOS.SDK.Context.Constant;
  24. using TEAMModelOS.SDK.Models.Dtos;
  25. using TEAMModelOS.SDK.Services;
  26. using Microsoft.Extensions.Configuration;
  27. using Azure.Messaging.ServiceBus;
  28. using TEAMModelOS.Models;
  29. using TEAMModelOS.SDK.Models.Service;
  30. using TEAMModelOS.SDK.Models.Cosmos.BI.BINormal;
  31. using TEAMModelOS.SDK.Models.Cosmos.Student;
  32. using Microsoft.OData.Edm;
  33. using System.IdentityModel.Tokens.Jwt;
  34. using TEAMModelOS.SDK.Models.Cosmos.OpenEntity;
  35. using Microsoft.OData.UriParser;
  36. using Azure.Core;
  37. using System.Security.Policy;
  38. using System.Net.Http.Json;
  39. using System.Drawing;
  40. using Microsoft.AspNetCore.DataProtection;
  41. using Newtonsoft.Json.Linq;
  42. using Microsoft.Extensions.Hosting;
  43. using Microsoft.AspNetCore.Hosting;
  44. using TEAMModelOS.Models.ShanDa;
  45. using System.Runtime.ConstrainedExecution;
  46. using DocumentFormat.OpenXml.Wordprocessing;
  47. using DocumentFormat.OpenXml.Office2010.Excel;
  48. using DocumentFormat.OpenXml.Office2016.Excel;
  49. namespace TEAMModelOS.SDK
  50. {
  51. public class OpenApiService
  52. {
  53. private static List<string> weekDays = new List<string> { "MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN" };
  54. /// <summary>
  55. /// 第三方获取学校列表
  56. /// [ApiToken(Auth = "1000", Name = "合作商获取可访问的学校列表",TName ="",EName ="", RWN = "R", Limit = false)]
  57. /// </summary>
  58. /// <param name="_azureCosmos"></param>
  59. /// <param name="_dingDing"></param>
  60. /// <param name="json"></param>
  61. /// <returns></returns>
  62. public static async Task<ResponseData<List<BizSchool>>> GetSchools(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId)
  63. {
  64. try
  65. {
  66. List<BizSchool> schools = new();
  67. var response = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Normal").ReadItemStreamAsync(bizId, new PartitionKey("BizConfig"));
  68. if (response.Status == 200)
  69. {
  70. using var resJson = await JsonDocument.ParseAsync(response.ContentStream);
  71. Business bizConfig = resJson.ToObject<Business>();
  72. schools = bizConfig.schools;
  73. }
  74. else return new ResponseData<List<BizSchool>>() { code = RespondCode.NotFound, msg = "未找到该企业" };
  75. return new ResponseData<List<BizSchool>>() { code = RespondCode.Ok, msg = "成功", data = schools };
  76. }
  77. catch (Exception ex)
  78. {
  79. await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetSchools() 参数:bizId:{bizId} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  80. return new ResponseData<List<BizSchool>>() { code = RespondCode.Error, msg = "服务端异常" };
  81. }
  82. }
  83. /// <summary>
  84. /// josn:
  85. /// {
  86. /// "roles":"",
  87. /// "scope":""
  88. /// "pageCount":"",
  89. /// "DESC":"",
  90. /// "ASC":"",
  91. /// "continuationToken":"",
  92. /// "school":"",
  93. /// "tmdid":""
  94. /// }
  95. /// </summary>
  96. /// <param name="azureCosmos"></param>
  97. /// <param name="dingDing"></param>
  98. /// <param name="id"></param>
  99. /// <param name="school"></param>
  100. /// <param name="json"></param>
  101. /// <returns></returns>
  102. /// <exception cref="NotImplementedException"></exception>
  103. public static async Task<ResponseData<dynamic>> GetLessonRecordCount(AzureCosmosFactory _azureCosmos, IConfiguration _configuration, AzureServiceBusFactory _serviceBus,
  104. Option _option, DingDing _dingDing, string id, string school, JsonElement json)
  105. {
  106. json.TryGetProperty("identity", out JsonElement _identity);
  107. string identity = "";
  108. if (!string.IsNullOrWhiteSpace($"{_identity}"))
  109. {
  110. identity = $"{_identity}";
  111. }
  112. json.TryGetProperty("managePage", out JsonElement _managePage);
  113. bool managePage = false;
  114. if (_managePage.ValueKind.Equals(JsonValueKind.True))
  115. {
  116. managePage = true;
  117. }
  118. StringBuilder sql = new StringBuilder();
  119. sql.Append("select c.id,c.groupIds,c.courseId from c ");
  120. Dictionary<string, object> dict = LessonService.GetLessonCond(json);
  121. AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
  122. string tbname = "";
  123. string code = "";
  124. List<string> autoTch = new List<string>();
  125. string sqlPrivate = "";
  126. code = $"LessonRecord-{school}";
  127. tbname = "School";
  128. List<string> ids = new List<string>();
  129. //只查询某个老师的课例
  130. if (json.TryGetProperty("tmdid", out JsonElement tmdid) && !string.IsNullOrWhiteSpace($"{tmdid}"))
  131. {
  132. ids.Add($"{tmdid}");
  133. }
  134. else
  135. {
  136. string sqltch = "select distinct value(c.id) from c ";
  137. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
  138. .GetItemQueryIterator<string>(queryText: sqltch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Teacher-{school}") }))
  139. {
  140. ids.Add(item);
  141. }
  142. }
  143. if (ids.Any())
  144. {
  145. string sqlTechbase = $"select distinct value(c.id) from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))}) and (array_contains(c.lessonShow,'student') or array_contains(c.lessonShow,'all')) ";
  146. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  147. .GetItemQueryIterator<string>(queryText: sqlTechbase, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
  148. {
  149. autoTch.Add(item);
  150. }
  151. }
  152. int count = 0;
  153. string sqlShow = "";
  154. if (identity.Equals("student"))
  155. {
  156. string autoSql = "";
  157. if (autoTch.Any())
  158. {
  159. autoSql = $" or c.tmdid in ({string.Join(",", autoTch.Select(x => $"'{x}'"))})";
  160. }
  161. sqlShow = $" and (array_contains(c.show,'student') or array_contains(c.show,'all') {autoSql} ) ";
  162. }
  163. string sql_status_managePage = " (c.status<>404 or IS_DEFINED(c.status) = false ) and ";
  164. if (managePage)
  165. {
  166. sql_status_managePage = "";
  167. }
  168. long now = DateTimeOffset.Now.ToUnixTimeMilliseconds();
  169. cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where {sql_status_managePage} array_length(c.groupIds)>0 {sqlPrivate} {sqlShow} and ");
  170. if (json.TryGetProperty("singleGreen", out JsonElement doubleGreen) && doubleGreen.GetBoolean())
  171. {
  172. cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where ((c.tLevel=2 and c.pLevel<2 )or(c.tLevel<2 and c.pLevel=2 )) and ");
  173. }
  174. if (json.TryGetProperty("expire", out JsonElement expire) && expire.ValueKind.Equals(JsonValueKind.True))
  175. {
  176. cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where c.expire>{now} and ");
  177. }
  178. List<LessonRecord> records = new List<LessonRecord>();
  179. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).GetItemQueryIterator<LessonRecord>(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
  180. {
  181. records.Add(item);
  182. }
  183. if (records.Any())
  184. {
  185. var groupIds = records.SelectMany(x => x.groupIds).ToHashSet();
  186. if (groupIds.Any())
  187. {
  188. var groups = await GroupListService.GetGroupListByListids(_azureCosmos.GetCosmosClient(), _dingDing, groupIds.ToList(), school, " c.id ");
  189. //获取已经被删除的名单。
  190. var idsExp = groupIds.Except(groups.Select(x => x.id));
  191. if (idsExp.Any())
  192. {
  193. foreach (var item in records)
  194. {
  195. int countRmv = item.groupIds.RemoveAll(x => idsExp.Contains(x));
  196. if (countRmv > 0)
  197. {
  198. try
  199. {
  200. LessonRecord record = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<LessonRecord>(item.id, new PartitionKey(code));
  201. record.groupIds = item.groupIds;
  202. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(record, item.id, new PartitionKey(code));
  203. }
  204. catch (CosmosException ex) when (ex.Status == 404)
  205. {
  206. continue;
  207. }
  208. }
  209. }
  210. }
  211. }
  212. }
  213. count = records.Count;
  214. ResponseData<dynamic> resDate = new ResponseData<dynamic>
  215. {
  216. code = RespondCode.Ok,
  217. msg = "成功",
  218. data = new
  219. {
  220. count = count,
  221. }
  222. };
  223. return resDate;
  224. }
  225. /// <summary>
  226. /// josn:
  227. /// {
  228. /// "roles":"",
  229. /// "scope":""
  230. /// "pageCount":"",
  231. /// "DESC":"",
  232. /// "ASC":"",
  233. /// "continuationToken":"",
  234. /// "school":"",
  235. /// "tmdid":""
  236. /// }
  237. /// </summary>
  238. /// <param name="azureCosmos"></param>
  239. /// <param name="dingDing"></param>
  240. /// <param name="id"></param>
  241. /// <param name="school"></param>
  242. /// <param name="json"></param>
  243. /// <returns></returns>
  244. /// <exception cref="NotImplementedException"></exception>
  245. public static async Task<ResponseData<dynamic>> GetLessonRecord(AzureCosmosFactory _azureCosmos, IConfiguration _configuration, AzureServiceBusFactory _serviceBus,
  246. Option _option, DingDing _dingDing, string id, string school, JsonElement json)
  247. {
  248. json.TryGetProperty("identity", out JsonElement _identity);
  249. string identity = "";
  250. if (!string.IsNullOrWhiteSpace($"{_identity}"))
  251. {
  252. identity = $"{_identity}";
  253. }
  254. json.TryGetProperty("managePage", out JsonElement _managePage);
  255. bool managePage = false;
  256. if (_managePage.ValueKind.Equals(JsonValueKind.True))
  257. {
  258. managePage = true;
  259. }
  260. StringBuilder sql = new StringBuilder();
  261. sql.Append("select value(c) from c ");
  262. int pageCount = 10;
  263. Dictionary<string, object> dict = LessonService.GetLessonCond(json);
  264. if (json.TryGetProperty("pageCount", out JsonElement _pageCount))
  265. {
  266. int.TryParse($"{_pageCount}", out int pcount);
  267. if (pcount > 0)
  268. {
  269. pageCount = pcount;
  270. }
  271. }
  272. if (json.TryGetProperty("DESC", out JsonElement desc))
  273. {
  274. dict.Add("@DESC", desc.ToString());
  275. }
  276. if (json.TryGetProperty("ASC", out JsonElement asc))
  277. {
  278. dict.Add("@ASC", asc.ToString());
  279. }
  280. string continuationToken = null;
  281. if (json.TryGetProperty("continuationToken", out JsonElement _continuationToken))
  282. {
  283. if (!string.IsNullOrEmpty($"{_continuationToken}"))
  284. {
  285. continuationToken = $"{_continuationToken}";
  286. }
  287. }
  288. AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
  289. string tbname = "";
  290. string code = "";
  291. string sqlPrivate = "";
  292. List<string> autoTch = new List<string>();
  293. code = $"LessonRecord-{school}";
  294. tbname = "School";
  295. List<string> ids = new List<string>();
  296. //只查询某个老师的课例
  297. if (json.TryGetProperty("tmdid", out JsonElement tmdid) && !string.IsNullOrWhiteSpace($"{tmdid}"))
  298. {
  299. ids.Add($"{tmdid}");
  300. }
  301. else
  302. {
  303. string sqltch = "select distinct value(c.id) from c ";
  304. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
  305. .GetItemQueryIterator<string>(queryText: sqltch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Teacher-{school}") }))
  306. {
  307. ids.Add(item);
  308. }
  309. }
  310. if (ids.Any())
  311. {
  312. string sqlTechbase = $"select distinct value(c.id) from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))}) and (array_contains(c.lessonShow,'student') or array_contains(c.lessonShow,'all')) ";
  313. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  314. .GetItemQueryIterator<string>(queryText: sqlTechbase, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
  315. {
  316. autoTch.Add(item);
  317. }
  318. }
  319. List<LessonRecord> lessonRecords = new List<LessonRecord>();
  320. try
  321. {
  322. string sqlShow = "";
  323. if (identity.Equals("student"))
  324. {
  325. string autoSql = "";
  326. if (autoTch.Any())
  327. {
  328. autoSql = $" or c.tmdid in ({string.Join(",", autoTch.Select(x => $"'{x}'"))})";
  329. }
  330. sqlShow = $" and (array_contains(c.show,'student') or array_contains(c.show,'all') {autoSql} ) ";
  331. }
  332. string sql_status_managePage = "(c.status<>404 or IS_DEFINED(c.status) = false ) and ";
  333. if (managePage)
  334. {
  335. sql_status_managePage = "";
  336. }
  337. cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where {sql_status_managePage} array_length(c.groupIds)>0 {sqlPrivate} {sqlShow} and ");
  338. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname)
  339. .GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, continuationToken: continuationToken,
  340. requestOptions: new QueryRequestOptions() { MaxItemCount = pageCount, PartitionKey = new PartitionKey(code) }))
  341. {
  342. using var jsonData = await JsonDocument.ParseAsync(item.ContentStream);
  343. if (jsonData.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  344. {
  345. foreach (var obj in jsonData.RootElement.GetProperty("Documents").EnumerateArray())
  346. {
  347. lessonRecords.Add(obj.ToObject<LessonRecord>());
  348. }
  349. continuationToken = item.GetContinuationToken();
  350. break;
  351. }
  352. }
  353. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  354. //查询时处理已经过期的课例。防止ServiceBus未触发的。
  355. var expireRecords = lessonRecords.Where(x => x.expire > 0 && now > x.expire);
  356. try
  357. {
  358. foreach (var item in expireRecords)
  359. {
  360. //item.status = 404;
  361. //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
  362. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  363. var messageChange = new ServiceBusMessage(new { delete_id = item.id, tmdid = item.tmdid, scope = item.scope, opt = "delete", school = item.school }.ToJsonString());
  364. messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
  365. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
  366. }
  367. }
  368. catch (Exception ex)
  369. {
  370. await _dingDing.SendBotMsg($"{_option.Location},ServiceBus ,LessonRecordEvent 发送消息失败,检查是否配置正常。", GroupNames.成都开发測試群組);
  371. }
  372. var tmdids = lessonRecords.Select(x => x.tmdid).ToHashSet();
  373. if (tmdids != null && tmdids.Count > 0)
  374. {
  375. List<IdNameCode> codes = new List<IdNameCode>();
  376. string sqltmd = $"select c.id,c.name,c.picture from c where c.id in ({string.Join(",", tmdids.Select(x => $"'{x}'"))})";
  377. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<IdNameCode>(queryText: sqltmd, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  378. {
  379. codes.Add(item);
  380. }
  381. if (codes.IsNotEmpty())
  382. {
  383. lessonRecords.ForEach(x =>
  384. {
  385. var tmd = codes.Find(z => z.id.Equals(x.tmdid));
  386. if (tmd != null)
  387. {
  388. x.tmdname = tmd.name;
  389. x.tmdpicture = tmd.picture;
  390. }
  391. });
  392. }
  393. }
  394. var groupIds = lessonRecords.SelectMany(x => x.groupIds);
  395. if (groupIds.Any())
  396. {
  397. List<GroupListDto> groupLists = await GroupListService.GetGroupListByListids(_azureCosmos.GetCosmosClient(), _dingDing, groupIds.ToList(), school);
  398. lessonRecords.ForEach(x =>
  399. {
  400. List<string> groupNmae = new List<string>();
  401. x.groupIds.ForEach(y =>
  402. {
  403. var dto = groupLists.Find(z => z.id.Equals(y));
  404. string name = dto != null ? dto.name : "-";
  405. groupNmae.Add(name);
  406. });
  407. x.groupNames = groupNmae;
  408. });
  409. }
  410. ResponseData<dynamic> resDate = new ResponseData<dynamic>
  411. {
  412. code = RespondCode.Ok,
  413. msg = "成功",
  414. data = new
  415. {
  416. currCount = lessonRecords.Count,
  417. continuationToken,
  418. lessonRecords = lessonRecords.Select(x => new { x.tmdid, x.tmdname, x.tmdpicture, x.name, x.school, x.startTime, x.duration, x.courseId, x.groupIds, x.periodId, x.subjectId, x.grade, x.id, x.category })
  419. }
  420. };
  421. return resDate;
  422. }
  423. catch (Exception)
  424. {
  425. continuationToken = null;
  426. ResponseData<dynamic> resDate = new ResponseData<dynamic> { code = RespondCode.Ok, msg = "成功", data = new { currCount = 0, continuationToken = continuationToken, lessonRecords } };
  427. return resDate;
  428. }
  429. }
  430. /// <summary>
  431. /// 学校基本信息
  432. /// //[ApiToken(Auth = "1001", Name = "学校基本信息",TName ="",EName ="", RWN = "R", Limit = false)]
  433. /// </summary>
  434. /// <param name="_azureCosmos"></param>
  435. /// <param name="_dingDing"></param>
  436. /// <param name="bizId"></param>
  437. /// <param name="schoolId"></param>
  438. /// <returns></returns>
  439. public static async Task<ResponseData<dynamic>> GetSchoolInfo(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string schoolId)
  440. {
  441. try
  442. {
  443. ResponseData<dynamic> resDate = new();
  444. School data = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(schoolId, new PartitionKey("Base"));
  445. List<dynamic> period = new();
  446. data.period.ForEach(x => { period.Add(new { x.subjects, x.grades, x.name, x.id, x.campusId, x.semesters }); });
  447. if (data != null)
  448. {
  449. resDate.code = RespondCode.Ok;
  450. resDate.msg = "成功";
  451. resDate.data = new { data.id, data.name, data.areaId, data.type, data.region, data.province, data.city, data.dist, data.campuses, period };
  452. }
  453. else
  454. {
  455. resDate.code = RespondCode.NotFound;
  456. resDate.msg = "未找到学校信息";
  457. }
  458. return resDate;
  459. }
  460. catch (Exception ex)
  461. {
  462. await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetSchoolInfo() 参数:bizId:{bizId},school:{schoolId} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  463. return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务端异常" };
  464. }
  465. }
  466. /// <summary>
  467. /// 名单列表信息 获取学校的行政班,教学班,教研组,研修名单
  468. /// [ApiToken(Auth = "1201", Name = "名单列表信息",TName ="",EName ="", RWN = "R", Limit = false)]
  469. /// </summary>
  470. /// <param name="_azureCosmos"></param>
  471. /// <param name="_dingDing"></param>
  472. /// <param name="bizId"></param>
  473. /// <param name="school"></param>
  474. /// <param name="json"></param>
  475. /// <returns></returns>
  476. public static async Task<ResponseData<List<OGroupList>>> GetGroupList(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string school, JsonElement json)
  477. {
  478. try
  479. {
  480. ResponseData<List<OGroupList>> resDate = new();
  481. List<OGroupList> groupLists = new();
  482. var client = _azureCosmos.GetCosmosClient();
  483. json.TryGetProperty("periodId", out JsonElement periodId);
  484. List<GroupListGrp> tempGroupLists = new();
  485. //包含,学校的行政班,教学班
  486. json.TryGetProperty("type", out JsonElement _type);
  487. List<string> types = null;
  488. if (_type.ValueKind.Equals(JsonValueKind.Array))
  489. {
  490. types = _type.ToObject<List<string>>();
  491. }
  492. else if (_type.ValueKind.Equals(JsonValueKind.String))
  493. {
  494. types = new List<string> { $"{types}" };
  495. }
  496. if (types.IsEmpty() || types.Contains("class"))
  497. {
  498. StringBuilder classsql = new StringBuilder($"SELECT c.id,c.name,c.periodId ,c.year FROM c ");
  499. if (!string.IsNullOrEmpty($"{periodId}"))
  500. {
  501. classsql.Append($" where c.periodId='{periodId}' ");
  502. }
  503. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ClassInfo>(queryText: classsql.ToString(),
  504. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{school}") }))
  505. {
  506. HashSet<string> groupNames = new HashSet<string>();
  507. string gpsql = $"SELECT distinct c.groupId,c.groupName FROM c where c.classId='{item.id}'and c.groupName <>null";
  508. await foreach (var gp in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: gpsql,
  509. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{school}") }))
  510. {
  511. groupNames.Add(gp.groupName);
  512. }
  513. ///行政班(学生搜寻classId动态返回)class
  514. GroupListGrp group = new GroupListGrp
  515. {
  516. id = item.id,
  517. code = $"GroupList-{school}",
  518. name = item.name,
  519. periodId = item.periodId,
  520. scope = "school",
  521. school = $"{school}",
  522. type = "class",
  523. year = item.year,
  524. expire = 0,
  525. groupName = groupNames
  526. };
  527. tempGroupLists.Add(group);
  528. }
  529. }
  530. if (types.IsEmpty() || types.Contains("teach"))
  531. {
  532. //教学班
  533. StringBuilder teachsql = new StringBuilder($" SELECT distinct value(c) FROM c where c.type='teach'");
  534. if (!string.IsNullOrEmpty($"{periodId}"))
  535. {
  536. teachsql.Append($" and c.periodId='{periodId}'");
  537. }
  538. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  539. GetItemQueryIterator<GroupList>(queryText: teachsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
  540. {
  541. HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  542. tempGroupLists.Add(new GroupListGrp(item, groupName));
  543. }
  544. }
  545. if (types.IsEmpty() || types.Contains("research"))
  546. {
  547. //教研组
  548. StringBuilder researchsql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='research'");
  549. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  550. GetItemQueryIterator<GroupList>(queryText: researchsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
  551. {
  552. HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  553. tempGroupLists.Add(new GroupListGrp(item, groupName));
  554. }
  555. }
  556. if (types.IsEmpty() || types.Contains("yxtrain"))
  557. {
  558. //研修名单
  559. StringBuilder yxtrainsql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='yxtrain'");
  560. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  561. GetItemQueryIterator<GroupList>(queryText: yxtrainsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
  562. {
  563. HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
  564. tempGroupLists.Add(new GroupListGrp(item, groupName));
  565. }
  566. }
  567. groupLists = tempGroupLists.Select(x => new OGroupList { id = x.id, name = x.name, type = x.type, periodId = x.periodId, school = x.school, scope = x.scope, year = x.year, expire = x.expire }).ToList();
  568. if (groupLists.Count > 0)
  569. {
  570. resDate.code = RespondCode.Ok;
  571. resDate.msg = "成功";
  572. resDate.data = groupLists;
  573. }
  574. else
  575. {
  576. resDate.code = RespondCode.NotFound;
  577. resDate.msg = "未找到学校信息";
  578. }
  579. return resDate;
  580. }
  581. catch (Exception ex)
  582. {
  583. await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetGroupList() 参数:bizId:{bizId},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  584. return new ResponseData<List<OGroupList>>() { code = RespondCode.Error, msg = "服务端异常" };
  585. }
  586. }
  587. /// <summary>
  588. /// 名单成员信息,学生成员信息,包含(学生,成员)基本信息,分组等信息
  589. /// [ApiToken(Auth = "1202", Name = "名单成员信息",TName ="",EName ="", RWN = "R", Limit = false)]
  590. /// </summary>
  591. /// <param name="_azureCosmos"></param>
  592. /// <param name="_coreAPIHttpService"></param>
  593. /// <param name="_dingDing"></param>
  594. /// <param name="bizId"></param>
  595. /// <param name="school"></param>
  596. /// <param name="json"></param>
  597. /// <returns></returns>
  598. public static async Task<ResponseData<dynamic>> GetGroupMembers(AzureCosmosFactory _azureCosmos, CoreAPIHttpService _coreAPIHttpService, DingDing _dingDing, string bizId, string school, JsonElement json)
  599. {
  600. try
  601. {
  602. List<OGgroup> groups = new();
  603. var client = _azureCosmos.GetCosmosClient();
  604. if (!json.TryGetProperty("ids", out JsonElement ids)) return new ResponseData<dynamic>() { code = RespondCode.NotFound, msg = "参数错误" };
  605. List<string> listids = ids.ToObject<List<string>>();
  606. (List<RMember> members, List<RGroupList> tGroups) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, listids, $"{school}");
  607. groups = tGroups.Select(x => new OGgroup
  608. {
  609. name = x.name,
  610. no = x.no,
  611. periodId = x.periodId,
  612. school = x.school,
  613. type = x.type,
  614. year = x.year,
  615. expire = x.expire,
  616. tcount = x.tcount,
  617. scount = x.scount,
  618. leader = x.leader,
  619. members = x.members,
  620. id = x.id
  621. }).ToList();
  622. if (bizId.Equals("cc7e900c-4881-4fe9-9c64-abb1a1f95518") || bizId.Equals("633d4d36-2cae-469a-bdcb-c52ce2e416b3") || bizId.Equals("8254bc86-aae9-4fef-9655-4fbda1bd39da"))
  623. {
  624. if (listids.Count == 1 && listids.First().Equals("TeacherAll") && !string.IsNullOrEmpty(school))
  625. {
  626. var keys = members.Select(x => x.id).ToHashSet();
  627. var content = new StringContent(keys.ToJsonString(), Encoding.UTF8, "application/json");
  628. string ujson = await _coreAPIHttpService.GetUserInfos(content);
  629. if (!string.IsNullOrWhiteSpace(ujson))
  630. {
  631. var coreUsers = ujson.ToObject<List<CoreUser>>();
  632. if (coreUsers.IsNotEmpty())
  633. {
  634. coreUsers.ForEach(z => {
  635. var mb = members.Find(x => x.id.Equals(z.id));
  636. if (mb != null)
  637. {
  638. mb.no = z.mobile;
  639. }
  640. });
  641. }
  642. }
  643. }
  644. }
  645. return new ResponseData<dynamic>() { code = RespondCode.Ok, msg = "成功", data = new { groups, members } };
  646. }
  647. catch (Exception ex)
  648. {
  649. await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetGroupMembers() 参数:bizId:{bizId},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  650. return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务端异常" };
  651. }
  652. }
  653. /// <summary>
  654. /// 获取课程列表信息
  655. /// [ApiToken(Auth = "1301", Name = "获取课程列表信息",TName ="",EName ="", RWN = "R", Limit = false)]
  656. /// </summary>
  657. /// <param name="_azureCosmos"></param>
  658. /// <param name="_dingDing"></param>
  659. /// <param name="bizId"></param>
  660. /// <param name="school"></param>
  661. /// <param name="json"></param>
  662. /// <returns></returns>
  663. public static async Task<ResponseData<dynamic>> GetCourseList(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string school, JsonElement json)
  664. {
  665. try
  666. {
  667. var client = _azureCosmos.GetCosmosClient();
  668. json.TryGetProperty("periodId", out JsonElement periodId);
  669. json.TryGetProperty("subjectId", out JsonElement subjectId);
  670. StringBuilder sql = new StringBuilder($"SELECT c.id,c.name,c.subject,c.period,c.scope,c.no,c.school FROM c where 1=1 ");
  671. if (!string.IsNullOrWhiteSpace($"{periodId}"))
  672. {
  673. sql.Append($" and c.period.id='{periodId}'");
  674. }
  675. if (!string.IsNullOrWhiteSpace($"{subjectId}"))
  676. {
  677. sql.Append($" and c.subject.id='{subjectId}'");
  678. }
  679. List<dynamic> courses = new List<dynamic>();
  680. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<dynamic>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{school}") }))
  681. {
  682. courses.Add(item);
  683. }
  684. return new ResponseData<dynamic>() { code = RespondCode.Ok, msg = "成功", data = courses };
  685. }
  686. catch (Exception ex)
  687. {
  688. await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetCourseList() 参数:bizId:{bizId},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  689. return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务端异常" };
  690. }
  691. }
  692. /// <summary>
  693. /// 课程详细信息
  694. /// [ApiToken(Auth = "1302", Name = "课程详细信息",TName ="",EName ="", RWN = "R", Limit = false)]
  695. /// </summary>
  696. /// <param name="_azureCosmos"></param>
  697. /// <param name="_dingDing"></param>
  698. /// <param name="bizId"></param>
  699. /// <param name="school"></param>
  700. /// <param name="json"></param>
  701. /// <returns></returns>
  702. public static async Task<ResponseData<dynamic>> GetCourseInfo(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string school, JsonElement json)
  703. {
  704. try
  705. {
  706. json.TryGetProperty("courseId", out JsonElement courseId);
  707. Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{courseId}", new PartitionKey($"Course-{school}"));
  708. if (response.Status == 200)
  709. {
  710. JsonDocument document = JsonDocument.Parse(response.Content);
  711. Course course = document.RootElement.Deserialize<Course>();
  712. return new ResponseData<dynamic>() { code = RespondCode.Ok, msg = "成功", data = new { course.name, course.id, course.subject, course.period, course.scope, course.school, course.no, course.desc, course.schedule } };
  713. }
  714. else
  715. return new ResponseData<dynamic>() { code = RespondCode.NotFound, msg = "未找到相关课程" };
  716. }
  717. catch (Exception ex)
  718. {
  719. await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetCourseInfo() 参数:bizId:{bizId},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  720. return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务端异常" };
  721. }
  722. }
  723. /// <summary>
  724. /// 获取指定学段作息
  725. /// [ApiToken(Auth = "1303", Name = "获取指定学段作息",TName ="",EName ="", RWN = "R", Limit = false)]
  726. /// </summary>
  727. /// <param name="_azureCosmos"></param>
  728. /// <param name="_dingDing"></param>
  729. /// <param name="bizId"></param>
  730. /// <param name="school"></param>
  731. /// <param name="json"></param>
  732. /// <returns></returns>
  733. public static async Task<ResponseData<dynamic>> GetPaperExamCondition(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string school, JsonElement json)
  734. {
  735. try
  736. {
  737. json.TryGetProperty("periodId", out JsonElement _periodId);
  738. School data = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(school, new PartitionKey("Base"));
  739. var period = data.period.Find(x => x.id.Equals($"{_periodId}"));
  740. if (period != null)
  741. {
  742. return new ResponseData<dynamic>() { code = RespondCode.Ok, msg = "成功", data = new { period.subjects, period.timetable, period.grades, period.majors, weekDays } };
  743. }
  744. else
  745. return new ResponseData<dynamic>() { code = RespondCode.NotFound, msg = "未找到相关课程" };
  746. }
  747. catch (Exception ex)
  748. {
  749. await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetPaperExamCondition() 参数:bizId:{bizId},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  750. return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务端异常" };
  751. }
  752. }
  753. public static async Task<ResponseData<dynamic>> getCourseTechnology(IHttpClientFactory _httpClient, DingDing _dingDing, string bizId, string school, JsonElement json, IWebHostEnvironment _environment)
  754. {
  755. try
  756. {
  757. _httpClient.CreateClient().DefaultRequestHeaders.Add("ContentLength", "0");
  758. HttpContent httpContent = new StringContent(new { method = "statistic/data/" }.ToJsonString());
  759. /*Dictionary<string, object> data = new Dictionary<string, object>();
  760. data.Add("method", "statistic/data/");*/
  761. //data.Add("params", new { method = "statistic/data/"});
  762. //HttpResponseMessage responseMessage = await _httpClient.CreateClient().PostAsJsonAsync("http://116.204.72.199:81/statistic/data/", data);
  763. var response = await _httpClient.CreateClient().PostAsync("http://116.204.72.199:81/statistic/data/", httpContent);
  764. //获取配置文件内容
  765. string path = $"{_environment.ContentRootPath}/JsonFile/Core/field.json";
  766. StreamReader streamReader = new(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Encoding.UTF8);
  767. StringBuilder stringBuilder = new();
  768. string text;
  769. while ((text = streamReader.ReadLine()) != null)
  770. {
  771. stringBuilder.Append(text.ToString());
  772. }
  773. streamReader.Close();
  774. string input = stringBuilder.ToString();
  775. Field fields = input.ToObject<Field>();
  776. List<OCourseBase> courses = new();
  777. List<(string name, double T, double P, int attendCount, int mCount, int groups, long time,
  778. List<(string name, int count)> counts, List<(string name, double score)> ps,
  779. List<(string name, long time)> appTimes, List<(string name, string url, int duration, long time)> vd)> scores = new();
  780. //List<(string name, List<(string name, int count)> counts)> eveCounts = new();
  781. if (response.IsSuccessStatusCode)
  782. {
  783. string responseBody = response.Content.ReadAsStringAsync().Result;
  784. JObject jo = JObject.Parse(responseBody.ToString());
  785. JArray array = jo.Value<JArray>("base");
  786. foreach (var ne in array)
  787. {
  788. OCourseBase @base = new();
  789. var tname = ne["tmdname"].Value<string>();
  790. var cname = ne["courseName"].Value<string>();
  791. var attendCount = ne["attendCount"].Value<int>();
  792. var mCount = ne["mCount"].Value<int>();
  793. var time = ne["time"].Value<long>();
  794. var obj = ne["events"].ToObject<List<Events>>();
  795. var video = ne["videos"].ToObject<List<Videos>>();
  796. @base.tmdname = tname;
  797. @base.courseName = cname;
  798. @base.attendCount = attendCount;
  799. @base.mCount = mCount;
  800. @base.groups = new List<string>();
  801. @base.time = time;
  802. @base.eves = obj;
  803. @base.videos = video;
  804. //events.Add(obj);
  805. courses.Add(@base);
  806. }
  807. foreach (var eve in courses)
  808. {
  809. var countEve = eve.eves.GroupBy(x => x.@event).Select(y => new { name = y.Key, value = y.Sum(c => c.freq) });
  810. double scoreA = 0;
  811. if (countEve.Any())
  812. {
  813. scoreA += 20;
  814. }
  815. double scoreB = 0;
  816. int P1Count = 0;
  817. int P2Count = 0;
  818. int P3Count = 0;
  819. int P4Count = 0;
  820. int P5Count = 0;
  821. List<(string name, long time)> eveTimes = new();
  822. List<(string name, string url, int duration, long time)> videos = new();
  823. foreach (var v in eve.videos)
  824. {
  825. videos.Add((v.videoName, v.video, v.duration, v.startTime));
  826. }
  827. foreach (var apps in eve.eves)
  828. {
  829. var name = fields.fields.Where(x => x.field.Equals(apps.@event)).FirstOrDefault()?.desc;
  830. eveTimes.Add((name, apps.createTime));
  831. }
  832. List<(string name, int count)> eves = new();
  833. foreach (var per in countEve)
  834. {
  835. var name = fields.fields.Where(x => x.field.Equals(per.name)).FirstOrDefault()?.desc;
  836. eves.Add((name, per.value));
  837. foreach (var evePercent in fields.fields)
  838. {
  839. //计算T分
  840. if (per.name.Equals(evePercent.field))
  841. {
  842. if (evePercent.dimension.Equals("小组学习"))
  843. {
  844. P1Count++;
  845. }
  846. if (evePercent.dimension.Equals("全班互动"))
  847. {
  848. P2Count++;
  849. }
  850. if (evePercent.dimension.Equals("生本决策"))
  851. {
  852. P3Count++;
  853. }
  854. if (evePercent.dimension.Equals("全班测验"))
  855. {
  856. P4Count++;
  857. }
  858. if (evePercent.dimension.Equals("个人学习"))
  859. {
  860. P5Count++;
  861. }
  862. double bScore = 0;
  863. if (per.value == 1)
  864. {
  865. bScore += evePercent.percent * 0.9;
  866. }
  867. else if (per.value == 2)
  868. {
  869. bScore += evePercent.percent * 0.95;
  870. }
  871. else if (per.value >= 3)
  872. {
  873. bScore += evePercent.percent;
  874. }
  875. scoreB += bScore;
  876. }
  877. }
  878. }
  879. List<(string name, double score)> PScore = new();
  880. double P1Score = 0;
  881. if (P1Count == 1)
  882. {
  883. P1Score = 18 * 0.8;
  884. }
  885. else if (P1Count == 2)
  886. {
  887. P1Score = 18 * 0.9;
  888. }
  889. else if (P1Count >= 3)
  890. {
  891. P1Score = 18;
  892. }
  893. double P2Score = 0;
  894. if (P2Count == 1)
  895. {
  896. P2Score = 18 * 0.8;
  897. }
  898. else if (P2Count == 2)
  899. {
  900. P2Score = 18 * 0.9;
  901. }
  902. else if (P2Count >= 3)
  903. {
  904. P2Score = 18;
  905. }
  906. double P3Score = 0;
  907. if (P3Count == 1)
  908. {
  909. P3Score = 18 * 0.8;
  910. }
  911. else if (P3Count == 2)
  912. {
  913. P3Score = 18 * 0.9;
  914. }
  915. else if (P3Count >= 3)
  916. {
  917. P3Score = 18;
  918. }
  919. double P4Score = 0;
  920. if (P4Count == 1)
  921. {
  922. P4Score = 18 * 0.8;
  923. }
  924. else if (P3Count == 2)
  925. {
  926. P4Score = 18 * 0.9;
  927. }
  928. else if (P4Count >= 3)
  929. {
  930. P4Score = 18;
  931. }
  932. double P5Score = 0;
  933. if (P5Count == 1)
  934. {
  935. P5Score = 18 * 0.8;
  936. }
  937. else if (P5Count == 2)
  938. {
  939. P5Score = 18 * 0.9;
  940. }
  941. else if (P5Count >= 3)
  942. {
  943. P5Score = 18;
  944. }
  945. double P6Score = (P1Score + P2Score + P3Score + P4Score + P5Score) * 0.1;
  946. PScore.Add(("小组学习", P1Score));
  947. PScore.Add(("全班互动", P2Score));
  948. PScore.Add(("生本决策", P3Score));
  949. PScore.Add(("全班测验", P4Score));
  950. PScore.Add(("个人学习", P5Score));
  951. PScore.Add(("多元评价", P6Score));
  952. double P = P1Score + P2Score + P3Score + P4Score + P5Score + P6Score;
  953. double scoreC = (scoreA + scoreB) * 0.1;
  954. double scoreT = scoreA + scoreB + scoreC;
  955. scoreT = scoreT > 0 ? Math.Round(scoreT, 2) : 0;
  956. P = P > 0 ? Math.Round(P, 2) : 0;
  957. scores.Add((eve.courseName, scoreT, P, eve.attendCount, eve.mCount, eve.groups.Count, eve.time, eves, PScore, eveTimes, videos));
  958. //eveCounts.Add((eve.courseName, eves));
  959. }
  960. //var eve = courses.Select(c => c.eves).ToList();
  961. /*using JsonDocument document = JsonDocument.Parse(responseBody.ToString());
  962. if (document.RootElement.TryGetProperty("base", out JsonElement AccessTokenObj))
  963. {
  964. //AccessToken = AccessTokenObj.ToString();
  965. }*/
  966. }
  967. var courseScore = scores.Select(c => new
  968. {
  969. c.name,
  970. c.T,
  971. c.P,
  972. c.attendCount,
  973. c.mCount,
  974. c.groups,
  975. c.time,
  976. count = c.counts.Select(x => new { x.name, x.count }),
  977. pScore = c.ps.Select(x => new { x.name, x.score }),
  978. appTime = c.appTimes.Select(x => new { x.name, x.time }),
  979. videos = c.vd.Select(x => new { x.name, x.url, x.duration, x.time })
  980. });
  981. /*var courseCount = eveCounts.Select(c => new
  982. {
  983. c.name,
  984. count = c.counts.Select(x => new { x.name, x.count })
  985. });*/
  986. return new ResponseData<dynamic>() { code = RespondCode.Ok, msg = "成功", data = new { courseScore } };
  987. /*if (period != null)
  988. {
  989. return new ResponseData<dynamic>() { code = RespondCode.Ok, msg = "成功", data = new { period.subjects, period.timetable, period.grades, period.majors, weekDays } };
  990. }
  991. else
  992. return new ResponseData<dynamic>() { code = RespondCode.NotFound, msg = "未找到相关课程" };*/
  993. }
  994. catch (Exception ex)
  995. {
  996. await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/getCourseTechnology() 参数:bizId:{bizId},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  997. return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务端异常" };
  998. }
  999. }
  1000. /// <summary>
  1001. /// 物理教室列表
  1002. /// [ApiToken(Auth = "1401", Name = "物理教室列表",TName ="",EName ="", RWN = "R", Limit = false)]
  1003. /// </summary>
  1004. /// <param name="_azureCosmos"></param>
  1005. /// <param name="_dingDing"></param>
  1006. /// <param name="bizId"></param>
  1007. /// <param name="school"></param>
  1008. /// <param name="json"></param>
  1009. /// <returns></returns>
  1010. public static async Task<ResponseData<List<ORoom>>> GetRoomList(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string school, JsonElement json)
  1011. {
  1012. try
  1013. {
  1014. var client = _azureCosmos.GetCosmosClient();
  1015. List<ORoom> dtRooms = new();
  1016. StringBuilder sql = new StringBuilder($"select value(c) from c where 1=1 ");
  1017. json.TryGetProperty("openType", out JsonElement openType);
  1018. json.TryGetProperty("no", out JsonElement no);
  1019. if (!string.IsNullOrWhiteSpace($"{openType}"))
  1020. {
  1021. sql.Append($" and c.openType='{openType}'");
  1022. }
  1023. if (!string.IsNullOrWhiteSpace($"{no}"))
  1024. {
  1025. sql.Append($" and c.no='{no}'");
  1026. }
  1027. List<Room> rooms = new List<Room>();
  1028. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Room>(queryText: sql.ToString(),
  1029. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Room-{school}") }))
  1030. {
  1031. rooms.Add(item);
  1032. }
  1033. dtRooms = rooms.Select(s => new ORoom { id = s.id, name = s.name, x = s.x, y = s.y, openType = s.openType, style = s.style, area = s.area, address = s.address, school = school }).ToList();
  1034. if (dtRooms.Count > 0)
  1035. return new ResponseData<List<ORoom>>() { code = RespondCode.Ok, data = dtRooms };
  1036. else
  1037. return new ResponseData<List<ORoom>>() { code = RespondCode.NotFound, msg = "未找到该学校的物理教室" };
  1038. }
  1039. catch (Exception ex)
  1040. {
  1041. await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetRoomList() 参数:bizId:{bizId},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  1042. return new ResponseData<List<ORoom>>() { code = RespondCode.Error, msg = "服务端异常" };
  1043. }
  1044. }
  1045. /// <summary>
  1046. /// 物理教室详细
  1047. /// [ApiToken(Auth = "1402", Name = "物理教室详细",TName ="",EName ="", RWN = "R", Limit = false)]
  1048. /// </summary>
  1049. /// <param name="_azureCosmos"></param>
  1050. /// <param name="_dingDing"></param>
  1051. /// <param name="bizId"></param>
  1052. /// <param name="school"></param>
  1053. /// <param name="json"></param>
  1054. /// <returns></returns>
  1055. public static async Task<ResponseData<dynamic>> GetRoomInfo(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string school, JsonElement json)
  1056. {
  1057. try
  1058. {
  1059. var client = _azureCosmos.GetCosmosClient();
  1060. if (!json.TryGetProperty("roomId", out JsonElement roomId)) return new ResponseData<dynamic>() { code = RespondCode.ParamsError, msg = "参数错误" };
  1061. Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{roomId}", new PartitionKey($"Room-{school}"));
  1062. if (response.Status == 200)
  1063. {
  1064. JsonDocument document = JsonDocument.Parse(response.Content);
  1065. Room tRoom = document.RootElement.Deserialize<Room>();
  1066. return new ResponseData<dynamic>() { code = RespondCode.Ok, msg = "成功", data = new { tRoom.id, tRoom.name, tRoom.x, tRoom.y, tRoom.openType, tRoom.style, tRoom.area, tRoom.address, school } };
  1067. }
  1068. else
  1069. return new ResponseData<dynamic>() { code = RespondCode.NotFound, msg = "未找到物理教室详情" };
  1070. }
  1071. catch (Exception ex)
  1072. {
  1073. await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetRoomInfo() 参数:bizId:{bizId},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  1074. return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务端异常" };
  1075. }
  1076. }
  1077. /// <summary>
  1078. /// 教师列表信息
  1079. /// [ApiToken(Auth = "1501", Name = "教师列表信息",TName ="",EName ="", RWN = "R", Limit = false)]
  1080. /// </summary>
  1081. /// <param name="_azureCosmos"></param>
  1082. /// <param name="_coreAPIHttpService"></param>
  1083. /// <param name="_dingDing"></param>
  1084. /// <param name="bizId"></param>
  1085. /// <param name="school"></param>
  1086. /// <param name="json"></param>
  1087. /// <returns></returns>
  1088. public static async Task<ResponseData<dynamic>> GetTeacherList(AzureCosmosFactory _azureCosmos, CoreAPIHttpService _coreAPIHttpService, DingDing _dingDing, string bizId, string school, JsonElement json)
  1089. {
  1090. try
  1091. {
  1092. var client = _azureCosmos.GetCosmosClient();
  1093. json.TryGetProperty("searchKey", out JsonElement _searchKey);
  1094. List<CoreUser> coreUsers = new(); List<CoreUser> unjoined = new();
  1095. IEnumerable<string> unexist = null;
  1096. StringBuilder sql = new("select c.id,c.name ,c.picture,c.job ,c.subjectIds,c.roles from c");
  1097. if (_searchKey.ValueKind.Equals(JsonValueKind.Array))
  1098. {
  1099. List<string> searchKey = _searchKey.ToObject<List<string>>();
  1100. if (searchKey.Any())
  1101. {
  1102. var keys = searchKey.Where(x => !string.IsNullOrWhiteSpace(x));
  1103. var content = new StringContent(keys.ToJsonString(), Encoding.UTF8, "application/json");
  1104. string ujson = await _coreAPIHttpService.GetUserInfos(content);
  1105. if (!string.IsNullOrWhiteSpace(ujson))
  1106. {
  1107. coreUsers = ujson.ToObject<List<CoreUser>>();
  1108. }
  1109. if (coreUsers.Any())
  1110. unexist = searchKey.Except(coreUsers.Select(x => x.searchKey));
  1111. else
  1112. return new ResponseData<dynamic>() { code = RespondCode.NotFound, msg = "没有找到对应的教师信息", data = _searchKey };
  1113. }
  1114. }
  1115. List<SchoolTeacher> teachers = new();
  1116. //string insql = "";
  1117. if (coreUsers.Any())
  1118. sql.Append($" where c.id in ({string.Join(",", coreUsers.Select(x => $"'{x.id}'"))}) ");
  1119. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<SchoolTeacher>
  1120. (queryText: sql.ToString(), requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Teacher-{school}") }))
  1121. {
  1122. teachers.Add(item);
  1123. }
  1124. if (coreUsers.Count > 0)
  1125. {
  1126. var teacherIds = coreUsers.Select(x => x.id).Except(teachers.Select(x => x.id));
  1127. unjoined = coreUsers.FindAll(x => teacherIds.Contains(x.id));
  1128. }
  1129. List<dynamic> tchs = new List<dynamic>();
  1130. teachers.Select(x => new { x.id, x.name, x.picture, x.job, x.subjectIds, x.roles }).ToList().ForEach(x =>
  1131. {
  1132. if (coreUsers.Count > 0)
  1133. {
  1134. var coreUser = coreUsers.Find(c => c.id.Equals(x.id));
  1135. if (coreUser != null)
  1136. {
  1137. tchs.Add(new { x.id, coreUser.name, coreUser.picture, x.job, x.subjectIds, x.roles, coreUser.searchKey, school });
  1138. }
  1139. }
  1140. else
  1141. tchs.Add(new { x.id, x.name, x.picture, x.job, x.subjectIds, x.roles, school });
  1142. });
  1143. return new ResponseData<dynamic>() { code = RespondCode.Ok, msg = "成功", data = new { tchs, unjoined = unjoined.Select(x => new { id = x.id, name = x.name, picture = x.picture, searchKey = x.searchKey }).ToList(), unexist } };
  1144. }
  1145. catch (Exception ex)
  1146. {
  1147. //await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetTeacherList() 参数:bizId:{bizId},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  1148. return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务端异常" };
  1149. }
  1150. }
  1151. /// <summary>
  1152. /// 教师执教的班级和课程
  1153. /// [ApiToken(Auth = "1502", Name = "教师详细信息",TName ="",EName ="", RWN = "R", Limit = false)]
  1154. /// </summary>
  1155. /// <param name="_azureCosmos"></param>
  1156. /// <param name="_dingDing"></param>
  1157. /// <param name="bizId"></param>
  1158. /// <param name="school"></param>
  1159. /// <param name="json"></param>
  1160. /// <returns></returns>
  1161. public static async Task<ResponseData<dynamic>> GetTeacherTeach(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string school, JsonElement json)
  1162. {
  1163. try
  1164. {
  1165. if (json.TryGetProperty("tmdid", out JsonElement _tmdid))
  1166. {
  1167. json.TryGetProperty("period", out JsonElement _period);
  1168. List<OCourse> courses = new List<OCourse>();
  1169. var query = $"SELECT distinct c.code,c.id,c.no,c.name,c.period,c.subject,c.scope ,c['desc'] ,c.creatorId , c.year ,s as schedule FROM c join s in c.schedule where s.teacherId='{_tmdid}' ";
  1170. HashSet<string> classIds = new HashSet<string>();
  1171. if (!string.IsNullOrWhiteSpace($"{_period}"))
  1172. {
  1173. query = $"{query} and c.period.id ='{_period}'";
  1174. }
  1175. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<OCourse>(queryText: query,
  1176. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{school}") }))
  1177. {
  1178. if (!string.IsNullOrWhiteSpace(item.schedule?.stulist))
  1179. {
  1180. classIds.Add(item.schedule?.stulist);
  1181. }
  1182. if (!string.IsNullOrWhiteSpace(item.schedule?.classId))
  1183. {
  1184. classIds.Add(item.schedule?.classId);
  1185. }
  1186. courses.Add(item);
  1187. }
  1188. List<OGroupList> groupLists = new List<OGroupList>();
  1189. if (classIds.Any())
  1190. {
  1191. var tempGroupLists = await GroupListService.GetGroupListByListids(_azureCosmos.GetCosmosClient(), _dingDing, classIds.ToList(), school);
  1192. groupLists = tempGroupLists.Select(x => new OGroupList { id = x.id, name = x.name, type = x.type, periodId = x.periodId, school = x.school, scope = x.scope, year = x.year, expire = x.expire }).ToList();
  1193. }
  1194. var group = courses.GroupBy(x => x.id).Select(g => new { key = g.Key, list = g.ToList() });
  1195. List<Course> coursesR = new List<Course>();
  1196. group.ToList().ForEach(x =>
  1197. {
  1198. var first = x.list.First();
  1199. coursesR.Add(new Course
  1200. {
  1201. id = x.key,
  1202. name = first.name,
  1203. code = first.code,
  1204. no = first.no,
  1205. period = first.period,
  1206. subject = first.subject,
  1207. desc = first.desc,
  1208. creatorId = first.creatorId,
  1209. year = first.year,
  1210. schedule = x.list.Select(x => x.schedule).ToList()
  1211. });
  1212. });
  1213. return new ResponseData<dynamic>()
  1214. {
  1215. code = RespondCode.Ok,
  1216. data = new
  1217. {
  1218. courses = coursesR.Select(x => new
  1219. {
  1220. x.id,
  1221. school = school,
  1222. x.name,
  1223. x.no,
  1224. x.period,
  1225. x.subject,
  1226. x.desc,
  1227. x.creatorId,
  1228. x.year,
  1229. x.schedule
  1230. }),
  1231. groupLists
  1232. }
  1233. };
  1234. }
  1235. else
  1236. {
  1237. return new ResponseData<dynamic>() { code = RespondCode.ParamsError, msg = "参数错误" };
  1238. }
  1239. }
  1240. catch (Exception ex)
  1241. {
  1242. await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetTeacherTeach() 参数:bizId:{bizId},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  1243. return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务端异常" };
  1244. }
  1245. }
  1246. /// <summary>
  1247. /// 教师详细信息
  1248. /// [ApiToken(Auth = "1502", Name = "教师详细信息",TName ="",EName ="", RWN = "R", Limit = false)]
  1249. /// </summary>
  1250. /// <param name="_azureCosmos"></param>
  1251. /// <param name="_dingDing"></param>
  1252. /// <param name="bizId"></param>
  1253. /// <param name="school"></param>
  1254. /// <param name="json"></param>
  1255. /// <returns></returns>
  1256. public static async Task<ResponseData<dynamic>> GetTeacherInfo(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string school, JsonElement json)
  1257. {
  1258. try
  1259. {
  1260. var client = _azureCosmos.GetCosmosClient();
  1261. json.TryGetProperty("tmdid", out JsonElement _tmdid);
  1262. Response responseSchoolTch = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
  1263. .ReadItemStreamAsync($"{_tmdid}", new PartitionKey($"Teacher-{school}"));
  1264. Response responseTch = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher")
  1265. .ReadItemStreamAsync($"{_tmdid}", new PartitionKey($"Base"));
  1266. Teacher teacher = null;
  1267. if (responseTch.Status == 200)
  1268. {
  1269. teacher = JsonDocument.Parse(responseTch.Content).RootElement.Deserialize<Teacher>();
  1270. }
  1271. else
  1272. return new ResponseData<dynamic> { code = RespondCode.NotFound, msg = "账号未创建" };
  1273. if (responseSchoolTch.Status == 200 && teacher != null)
  1274. {
  1275. SchoolTeacher schoolTeacher = JsonDocument.Parse(responseSchoolTch.Content).RootElement.Deserialize<SchoolTeacher>();
  1276. return new ResponseData<dynamic> { code = RespondCode.Ok, msg = "成功", data = new { teacher.id, teacher.name, teacher.picture, schoolTeacher.job, schoolTeacher.status, schoolTeacher.roles, schoolTeacher.subjectIds, school = teacher.schools?.Find(x => x.schoolId.Equals(school)) } };
  1277. }
  1278. else
  1279. return new ResponseData<dynamic> { code = RespondCode.NotFound, msg = "教师未就职该学校" };
  1280. }
  1281. catch (Exception ex)
  1282. {
  1283. await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetTeacherInfo() 参数:bizId:{bizId},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  1284. return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务端异常" };
  1285. }
  1286. }
  1287. /// <summary>
  1288. /// 教师批量导入,并加入学校。可以导入学科,但需要填写学段id
  1289. /// [ApiToken(Auth = "1503", Name = "教师批量导入",TName ="",EName ="", RWN = "R", Limit = false)]
  1290. /// </summary>
  1291. /// <param name="_azureCosmos"></param>
  1292. /// <param name="_coreAPIHttpService"></param>
  1293. /// <param name="_dingDing"></param>
  1294. /// <param name="bizId"></param>
  1295. /// <param name="school"></param>
  1296. /// <param name="json"></param>
  1297. /// <returns></returns>
  1298. public static async Task<ResponseData<List<OTeachers>>> GetTeacherInfo(AzureCosmosFactory _azureCosmos, CoreAPIHttpService _coreAPIHttpService, DingDing _dingDing, string bizId, string school, ImportTechDto json)
  1299. {
  1300. try
  1301. {
  1302. //如果需要同时导入学科,则需要填写学段
  1303. List<ImportTech> impTeachers = json.teachers;
  1304. List<string> searchKey = impTeachers.Select(x => x.id).ToList();
  1305. string ujson = null;
  1306. var keys = searchKey.Where(x => !string.IsNullOrWhiteSpace(x));
  1307. if (keys.Any())
  1308. {
  1309. var content = new StringContent(keys.ToJsonString(), Encoding.UTF8, "application/json");
  1310. ujson = await _coreAPIHttpService.GetUserInfos(content);
  1311. }
  1312. List<CoreUser> coreUsers = new List<CoreUser>();
  1313. if (!string.IsNullOrWhiteSpace(ujson))
  1314. {
  1315. coreUsers = ujson.ToObject<List<CoreUser>>();
  1316. }
  1317. IEnumerable<string> unexist = new List<string>();
  1318. if (coreUsers.Any())
  1319. {
  1320. unexist = searchKey.Except(coreUsers.Select(x => x.id));
  1321. }
  1322. else
  1323. {
  1324. return new ResponseData<List<OTeachers>>() { code = RespondCode.NotFound, msg = "没有找到对应的教师信息" };
  1325. }
  1326. var exist = coreUsers.Select(x => x.id);
  1327. //注册了账号的教师
  1328. impTeachers = impTeachers.Where(x => exist.Contains(x.id)).ToList();
  1329. List<Teacher> teachersList = new List<Teacher>();
  1330. List<SchoolTeacher> schoolTeachers = new List<SchoolTeacher>();
  1331. string sql = $"select value(c) from c where c.id in ({string.Join(",", impTeachers.Select(x => $"'{x.id}'"))})";
  1332. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  1333. .GetItemQueryIterator<Teacher>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  1334. {
  1335. teachersList.Add(item);
  1336. }
  1337. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
  1338. .GetItemQueryIterator<SchoolTeacher>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Teacher-{school}") }))
  1339. {
  1340. schoolTeachers.Add(item);
  1341. }
  1342. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  1343. School data = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(school, new PartitionKey("Base"));
  1344. //学校学科发生变化。
  1345. List<SchoolTeacher> schoolTeachersAdd = new List<SchoolTeacher>();
  1346. bool baseChange = false;
  1347. foreach (var item in impTeachers)
  1348. {
  1349. var teacher = teachersList.Find(x => x.id.Equals(item.id));
  1350. var coreUser = coreUsers.Find(x => x.id.Equals(item.id));
  1351. if (teacher != null)
  1352. {
  1353. var sch = teacher.schools?.Find(x => x.schoolId.Equals(school));
  1354. if (sch == null)
  1355. {
  1356. if (teacher.schools.IsNotEmpty())
  1357. {
  1358. teacher.schools.Add(new Teacher.TeacherSchool { schoolId = school, name = data.name, status = "invite", time = now, picture = data.picture, areaId = data.areaId });
  1359. }
  1360. else
  1361. {
  1362. teacher.defaultSchool = school;
  1363. teacher.size = teacher.size + 1;
  1364. teacher.schools = new List<Teacher.TeacherSchool> { new Teacher.TeacherSchool { schoolId = school, name = data.name, status = "invite", time = now, picture = data.picture, areaId = data.areaId } };
  1365. }
  1366. }
  1367. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(teacher, teacher.id, new PartitionKey("Base"));
  1368. }
  1369. else
  1370. {
  1371. teacher = new Teacher
  1372. {
  1373. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  1374. id = coreUser.id,
  1375. name = coreUser.name,
  1376. picture = coreUser.picture,
  1377. defaultSchool = school,
  1378. size = 2,
  1379. code = "Base",
  1380. pk = "Base",
  1381. schools = new List<Teacher.TeacherSchool> { new Teacher.TeacherSchool { schoolId = school, name = data.name, status = "invite", time = now, picture = data.picture, areaId = data.areaId } }
  1382. };
  1383. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).CreateItemAsync(teacher, new PartitionKey("Base"));
  1384. }
  1385. var schoolTeacher = schoolTeachers.Find(x => x.id.Equals(item.id));
  1386. //处理导入的学科
  1387. List<string> subjectIds = new List<string>();
  1388. if (item.subjects.IsNotEmpty() && !string.IsNullOrWhiteSpace(item.periodId))
  1389. {
  1390. item.subjects.ForEach(s =>
  1391. {
  1392. //同名学科
  1393. var subject = data.period.Find(x => x.id.Equals(item.periodId))?.subjects?.Find(x => x.id.Equals(s.id));
  1394. if (subject == null)
  1395. {
  1396. subject = data.period.Find(x => x.id.Equals(item.periodId))?.subjects?.Find(x => x.name.Equals(s.name));
  1397. }
  1398. else
  1399. {
  1400. subjectIds.Add(subject.id);
  1401. }
  1402. if (subject == null)
  1403. {
  1404. var period = data.period.Find(x => x.id.Equals(item.periodId));
  1405. if (period != null)
  1406. {
  1407. period.subjects.Add(new Subject { id = s.id, name = s.name, type = 2 });
  1408. subjectIds.Add(s.id);
  1409. baseChange = true;
  1410. }
  1411. }
  1412. });
  1413. }
  1414. if (schoolTeacher == null)
  1415. {
  1416. schoolTeacher = new SchoolTeacher
  1417. {
  1418. id = item.id,
  1419. name = coreUser.name,
  1420. picture = coreUser.picture,
  1421. job = item.job,
  1422. subjectIds = subjectIds,
  1423. roles = new List<string> { "teacher" },
  1424. permissions = new List<string> { "content-read", "exercise-read", "knowledge-read", "syllabus-read" },
  1425. status = "invite",
  1426. code = $"Teacher-{school}",
  1427. pk = "Teacher",
  1428. createTime = now,
  1429. };
  1430. schoolTeachersAdd.Add(schoolTeacher);
  1431. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).CreateItemAsync(schoolTeacher, new PartitionKey(schoolTeacher.code));
  1432. }
  1433. else
  1434. {
  1435. if (subjectIds.IsNotEmpty())
  1436. {
  1437. subjectIds.ForEach(x =>
  1438. {
  1439. if (!schoolTeacher.subjectIds.Contains(x))
  1440. {
  1441. schoolTeacher.subjectIds.Add(x);
  1442. }
  1443. });
  1444. }
  1445. schoolTeacher.job = string.IsNullOrWhiteSpace(item.job) ? schoolTeacher.job : item.job;
  1446. schoolTeachersAdd.Add(schoolTeacher);
  1447. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(schoolTeacher, schoolTeacher.id, new PartitionKey(schoolTeacher.code));
  1448. }
  1449. }
  1450. if (baseChange)
  1451. {
  1452. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(data, data.id, new PartitionKey("Base"));
  1453. }
  1454. return new ResponseData<List<OTeachers>>() { code = RespondCode.Ok, msg = "成功", data = schoolTeachersAdd.Select(x => new OTeachers { id = x.id, name = x.name, picture = x.picture, job = x.job, subjectIds = x.subjectIds, roles = x.roles, school = school }).ToList() };
  1455. //return schoolTeachersAdd.Select(x => new OTeachers { id = x.id, name = x.name, picture = x.picture, job = x.job, subjectIds = x.subjectIds, roles = x.roles, school = school }).ToList();
  1456. }
  1457. catch (Exception ex)
  1458. {
  1459. await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetTeacherInfo() 参数:bizId:{bizId},school:{school},json:{json} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  1460. return new ResponseData<List<OTeachers>>() { code = RespondCode.Error, msg = "服务端异常" };
  1461. }
  1462. }
  1463. /// <summary>
  1464. /// 查找课纲
  1465. /// [ApiToken(Auth = "1601", Name = "查询课纲",TName ="",EName ="", RWN = "R", Limit = false)]
  1466. /// </summary>
  1467. /// <param name="_azureCosmos"></param>
  1468. /// <param name="json"></param>
  1469. /// <returns></returns>
  1470. public static async Task<ResponseData<List<OSyllabusTreeNode>>> GetSyllabus(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string school, JsonElement json)
  1471. {
  1472. try
  1473. {
  1474. if (!json.TryGetProperty("volumeId", out JsonElement volumeId)) return new ResponseData<List<OSyllabusTreeNode>>() { code = RespondCode.ParamsError, msg = "参数错误" };
  1475. //if (!json.TryGetProperty("volumeCode", out JsonElement volumeCode)) return new ResponseData<List<OSyllabusTreeNode>>() { code = RespondCode.ParamsError, msg = "参数错误" };
  1476. if (!json.TryGetProperty("scope", out JsonElement scope)) return new ResponseData<List<OSyllabusTreeNode>>() { code = RespondCode.ParamsError, msg = "参数错误" };
  1477. var client = _azureCosmos.GetCosmosClient();
  1478. OVolume volume = null;
  1479. List<OSyllabusTreeNode> treeNodes = new();
  1480. List<OSyllabusTreeNode> redt = new();
  1481. if ($"{scope}".Equals("school"))
  1482. {
  1483. List<OSyllabus> delSyllabus = new();
  1484. volume = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<OVolume>($"{volumeId}", new PartitionKey($"Volume-{school}"));
  1485. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<OSyllabus>(queryText: $"select value(c) from c where c.volumeId='{volumeId}'",
  1486. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Syllabus-{volume.school}") }))
  1487. {
  1488. if (item.children.IsEmpty())
  1489. {
  1490. delSyllabus.Add(item);
  1491. }
  1492. else
  1493. {
  1494. List<OSyllabusTree> trees = SyllabusService.OListToTree(item.children);
  1495. OSyllabusTreeNode otree = new() { id = item.id, scope = item.scope, trees = trees, volumeId = item.volumeId, codeval = volume.school };
  1496. treeNodes.Add(otree);
  1497. }
  1498. }
  1499. if (delSyllabus.IsNotEmpty())
  1500. {
  1501. await client.GetContainer(Constant.TEAMModelOS, "School").DeleteItemsAsync<OSyllabus>(delSyllabus.Select(x => x.id).ToList(), $"Syllabus-{volume.school}");
  1502. }
  1503. }
  1504. else
  1505. return new ResponseData<List<OSyllabusTreeNode>>() { code = RespondCode.ParamsError, msg = "参数错误" };
  1506. ResponseData<List<OSyllabusTreeNode>> responseData = new();
  1507. //对课纲树形结构排序
  1508. if (volume.syllabusIds.IsNotEmpty())
  1509. {
  1510. volume.syllabusIds.ForEach(x =>
  1511. {
  1512. for (int index = 0; index < treeNodes.Count; index++)
  1513. {
  1514. if (treeNodes[index].id == x)
  1515. {
  1516. redt.Add(treeNodes[index]);
  1517. treeNodes.RemoveAt(index);
  1518. }
  1519. }
  1520. });
  1521. redt.AddRange(treeNodes);
  1522. responseData = new ResponseData<List<OSyllabusTreeNode>>() { code = RespondCode.Ok, msg = "成功", data = redt };
  1523. }
  1524. else
  1525. {
  1526. responseData = new ResponseData<List<OSyllabusTreeNode>>() { code = RespondCode.Ok, msg = "成功", data = treeNodes };
  1527. }
  1528. return responseData;
  1529. }
  1530. catch (Exception ex)
  1531. {
  1532. await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetSyllabus() 参数:bizId:{bizId},school:{school},参数json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  1533. return new ResponseData<List<OSyllabusTreeNode>>() { code = RespondCode.Error, msg = "服务端异常" };
  1534. }
  1535. }
  1536. /// <summary>
  1537. /// 查询册别清单
  1538. /// [ApiToken(Auth = "1602", Name = "查询册别",TName ="",EName ="", RWN = "R", Limit = false)]
  1539. /// </summary>
  1540. /// <param name="_azureCosmos"></param>
  1541. /// <param name="_dingDing"></param>
  1542. /// <param name="json"></param>
  1543. /// <returns></returns>
  1544. public static async Task<ResponseData<List<OVolume>>> GetVolumes(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string school, JsonElement json)
  1545. {
  1546. try
  1547. {
  1548. ResponseData<List<OVolume>> responseData = new();
  1549. List<OVolume> ovolumes = new List<OVolume>();
  1550. json.TryGetProperty("periodId", out JsonElement periodCode);
  1551. json.TryGetProperty("subjectId", out JsonElement subjectCode);
  1552. json.TryGetProperty("status", out JsonElement status);
  1553. json.TryGetProperty("scope", out JsonElement scope);
  1554. if (scope.GetString().Equals("school"))
  1555. {
  1556. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<OVolume>(queryText: $"select value(c) from c where c.status = {status} and c.periodId = '{periodCode}' and c.subjectId = '{subjectCode}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Volume-{school}") }))
  1557. {
  1558. ovolumes.Add(item);
  1559. }
  1560. }
  1561. else { return new ResponseData<List<OVolume>>() { code = RespondCode.ParamsError, msg = "参数错误" }; };
  1562. if (ovolumes.Count > 0)
  1563. {
  1564. responseData = new ResponseData<List<OVolume>>() { code = RespondCode.Ok, msg = "成功", data = ovolumes };
  1565. }
  1566. else
  1567. responseData = new ResponseData<List<OVolume>>() { code = RespondCode.NotFound, msg = "未找到参数相关的数据" };
  1568. return responseData;
  1569. }
  1570. catch (Exception ex)
  1571. {
  1572. await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetVolumes() 参数:bizId:{bizId},school:{school},参数json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  1573. return new ResponseData<List<OVolume>>() { code = RespondCode.Error, msg = "服务端异常" };
  1574. }
  1575. }
  1576. /// <summary>
  1577. /// 查询知识
  1578. /// [ApiToken(Auth = "1701", Name = "查询知识点",TName ="",EName ="", RWN = "R", Limit = false)]
  1579. /// </summary>
  1580. /// <param name="_azureCosmos"></param>
  1581. /// <param name="_dingDing"></param>
  1582. /// <param name="json"></param>
  1583. /// <returns></returns>
  1584. public static async Task<ResponseData<dynamic>> GetKnowledges(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string school, JsonElement json)
  1585. {
  1586. try
  1587. {
  1588. ResponseData<dynamic> responseData = new();
  1589. var client = _azureCosmos.GetCosmosClient();
  1590. json.TryGetProperty("periodId", out JsonElement periodId);
  1591. if (!json.TryGetProperty("subjectId", out JsonElement subjectId)) return new ResponseData<dynamic>() { code = RespondCode.ParamsError, msg = "参数错误" };
  1592. //if (!json.TryGetProperty("school_code", out JsonElement school_code)) return new ResponseData<List<Knowledge>>() { code = RespondCode.ParamsError, msg = "参数错误" };
  1593. string code = $"Knowledge-{school}-{subjectId}";
  1594. StringBuilder sql = new($"select value(c) from c");
  1595. if (periodId.ValueKind.Equals(JsonValueKind.String))
  1596. {
  1597. sql.Append($" where c.periodId = '{periodId}'");
  1598. }
  1599. List<dynamic> knowledges = new();
  1600. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Knowledge>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{code}") }))
  1601. {
  1602. knowledges.Add(new { item.periodId, item.subjectId, item.points, item.blocks, item.id });
  1603. }
  1604. if (knowledges.Any())
  1605. {
  1606. var data = knowledges.Select(x => new { });
  1607. responseData = new() { code = RespondCode.Ok, msg = "成功", data = knowledges };
  1608. }
  1609. else
  1610. {
  1611. responseData = new() { code = RespondCode.NotFound, msg = "未找到相关" };
  1612. }
  1613. return responseData;
  1614. }
  1615. catch (Exception ex)
  1616. {
  1617. await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetKnowledges() 参数:bizId:{bizId},school:{school},参数json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  1618. return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务端异常" };
  1619. }
  1620. }
  1621. /// <summary>
  1622. /// 设置学生全面教育画像
  1623. ///[ApiToken(Auth = "1901", Name = "设置学生全面教育画像", TName = "設置學生全面教育畫像", EName = "Set up students overall education portrait", RWN = "W", Limit = false)]
  1624. /// </summary>
  1625. /// <param name="_azureCosmos"></param>
  1626. /// <param name="_dingDing"></param>
  1627. /// <param name="json"></param>
  1628. /// <returns></returns>
  1629. public static async Task<ResponseData<dynamic>> UpsertStudentPortrait(AzureCosmosFactory _azureCosmos, DingDing _dingDing,AzureRedisFactory _azureRedis , JsonElement json,string school=null)
  1630. {
  1631. try
  1632. {
  1633. ResponseData<dynamic> responseData = new();
  1634. var client = _azureCosmos.GetCosmosClient();
  1635. if (!json.TryGetProperty("schoolCode", out JsonElement schoolCode))
  1636. {
  1637. return responseData = new() { code = RespondCode.ParamsError, msg = "schoolCode为空" };
  1638. }
  1639. #if !DEBUG
  1640. if (!string.IsNullOrWhiteSpace(school) && !school.Equals($"{schoolCode}", StringComparison.OrdinalIgnoreCase)) {
  1641. return responseData = new() { code = RespondCode.ParamsError, msg = "授权学校与参数schoolCode不匹配" };
  1642. }
  1643. #endif
  1644. if (!json.TryGetProperty("periodId", out JsonElement periodId))
  1645. {
  1646. return responseData = new() { code = RespondCode.ParamsError, msg = "periodId为空" };
  1647. }
  1648. if (!json.TryGetProperty("subjectId", out JsonElement subjectId))
  1649. {
  1650. return responseData = new() { code = RespondCode.ParamsError, msg = "subjectId为空" };
  1651. }
  1652. if (!json.TryGetProperty("students", out JsonElement _students) && !_students.ValueKind.Equals(JsonValueKind.Array))
  1653. {
  1654. return responseData = new() { code = RespondCode.ParamsError, msg = "students为空或格式错误" };
  1655. }
  1656. if (!$"{subjectId}".Equals("subject_sport") && !$"{subjectId}".Equals("subject_virtue") && !$"{subjectId}".Equals("subject_labour")
  1657. && !$"{subjectId}".Equals("subject_intelligence")
  1658. && !$"{subjectId}".Equals("subject_art"))
  1659. {
  1660. return responseData = new() { code = RespondCode.ParamsError, msg = "当前subjectId未开放画像业务" };
  1661. }
  1662. School schoolBase = await client.GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>($"{schoolCode}", new PartitionKey("Base"));
  1663. List<PortraitStudent> students = _students.ToObject<List<PortraitStudent>>();
  1664. if (students.IsEmpty()) {
  1665. return responseData = new() { code = RespondCode.ParamsError, msg = "没有学生数据" };
  1666. }
  1667. List<(Student studentBase, PortraitStudent portrait)> studentsBases = new List<(Student, PortraitStudent)>();
  1668. //学生信息不匹配的
  1669. List<PortraitStudent> unmatchStuInfo = new List<PortraitStudent>();
  1670. //学期不匹配的
  1671. List<PortraitStudent> unmatchSemester = new List<PortraitStudent>();
  1672. List<PortraitStudent> upsertDatas = new List<PortraitStudent>();
  1673. //细项类型不匹配的
  1674. List<PortraitStudent> unmatchItemScoreType = new List<PortraitStudent>();
  1675. string stusql = $"select c.id,c.classId,c.name,c.year from c where c.id in ({string.Join(",", students.Select(f => $"'{f.studentId}'"))})";
  1676. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Student)
  1677. .GetItemQueryIterator<Student>(queryText: stusql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base-{schoolCode}") }))
  1678. {
  1679. var student = students.Find(x => x.studentId.Equals(item.id));
  1680. student.classId = item.classId;
  1681. studentsBases.Add((item, student));
  1682. //if ($"{item.classId}".Equals($"{student.classId}"))
  1683. //{
  1684. // studentsBases.Add((item,student));
  1685. //}
  1686. //else {
  1687. // unmatchStuInfo.Add(student);
  1688. //}
  1689. }
  1690. var unexist = students.FindAll(z => !studentsBases.Select(z => z.studentBase.id).Contains(z.studentId));
  1691. if (unexist.Any())
  1692. {
  1693. unmatchStuInfo.AddRange(unexist);
  1694. }
  1695. Period period = schoolBase.period.Find(x => x.id.Equals($"{periodId}"));
  1696. if (period == null)
  1697. {
  1698. return responseData = new() { code = RespondCode.NotFound, msg = "periodId不存在" };
  1699. }
  1700. else
  1701. {
  1702. bool periodChange = false;
  1703. if (!period.semesters.Any())
  1704. {
  1705. //未设置学期则默认
  1706. period.semesters.Add(new Semester
  1707. {
  1708. id = Guid.NewGuid().ToString(),
  1709. name = "第一学期",
  1710. start = 1,
  1711. month = 9,
  1712. day = 1
  1713. }); period.semesters.Add(new Semester
  1714. {
  1715. id = Guid.NewGuid().ToString(),
  1716. name = "第二学期",
  1717. start = 0,
  1718. month = 3,
  1719. day = 1
  1720. });
  1721. periodChange = true;
  1722. }
  1723. //是否需要创建科目
  1724. if (!$"{subjectId}".Equals("subject_art", StringComparison.OrdinalIgnoreCase) || !$"{subjectId}".Equals("subject_intelligence", StringComparison.OrdinalIgnoreCase))
  1725. {
  1726. var bind = period.subjects.Find(x => !string.IsNullOrWhiteSpace(x.bindId) && x.bindId.Equals($"{subjectId}", StringComparison.OrdinalIgnoreCase));
  1727. if (bind == null)
  1728. {
  1729. string subjectName = "";
  1730. switch (true)
  1731. {
  1732. case bool when $"{subjectId}".Equals("subject_sport"):
  1733. subjectName = "体育";
  1734. break;
  1735. case bool when $"{subjectId}".Equals("subject_virtue"):
  1736. subjectName = "德育";
  1737. break;
  1738. case bool when $"{subjectId}".Equals("subject_labour"):
  1739. subjectName = "劳动";
  1740. break;
  1741. //case bool when $"{subjectId}".Equals("subject_music"):
  1742. // subjectName = "音乐";
  1743. // break;
  1744. //case bool when $"{subjectId}".Equals("subject_painting"):
  1745. // subjectName = "美术";
  1746. // break;
  1747. }
  1748. if (!string.IsNullOrWhiteSpace(subjectName))
  1749. {
  1750. var subName = period.subjects.Find(z => z.name.Contains(subjectName));
  1751. if (subName != null)
  1752. {
  1753. subName.bindId = $"{subjectId}";
  1754. }
  1755. else
  1756. {
  1757. period.subjects.Add(new Subject { id = Guid.NewGuid().ToString(), name = subjectName, bindId = $"{subjectId}", type = 1 });
  1758. }
  1759. periodChange = true;
  1760. }
  1761. }
  1762. }
  1763. //是否要创建艺术类的 音乐,美术科目
  1764. if ($"{subjectId}".Equals("subject_art", StringComparison.OrdinalIgnoreCase))
  1765. {
  1766. var bind_music = period.subjects.Find(x => !string.IsNullOrWhiteSpace(x.bindId) && x.bindId.Equals("subject_music", StringComparison.OrdinalIgnoreCase));
  1767. if (bind_music != null)
  1768. {
  1769. string subjectName = "音乐";
  1770. var subName = period.subjects.Find(z => z.name.Contains(subjectName));
  1771. if (subName != null)
  1772. {
  1773. subName.bindId = "subject_music";
  1774. }
  1775. else
  1776. {
  1777. period.subjects.Add(new Subject { id = Guid.NewGuid().ToString(), name = subjectName, bindId = "subject_music", type = 1 });
  1778. }
  1779. periodChange = true;
  1780. }
  1781. var bind_painting = period.subjects.Find(x => !string.IsNullOrWhiteSpace(x.bindId) && x.bindId.Equals("subject_painting", StringComparison.OrdinalIgnoreCase));
  1782. if (bind_painting != null)
  1783. {
  1784. string subjectName = "美术";
  1785. var subName = period.subjects.Find(z => z.name.Contains(subjectName));
  1786. if (subName != null)
  1787. {
  1788. subName.bindId = "subject_painting";
  1789. }
  1790. else
  1791. {
  1792. period.subjects.Add(new Subject { id = Guid.NewGuid().ToString(), name = subjectName, bindId = "subject_painting", type = 1 });
  1793. }
  1794. periodChange = true;
  1795. }
  1796. }
  1797. if (periodChange)
  1798. {
  1799. await client.GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync<School>(schoolBase, $"{schoolCode}", new PartitionKey("Base"));
  1800. }
  1801. List<Semester> sortedSemesters = SchoolService.SortSemester(period.semesters);
  1802. foreach (var studentInfo in studentsBases)
  1803. {
  1804. Student student = studentInfo.studentBase;
  1805. string studentId = studentInfo.studentBase.id;
  1806. string classId = studentInfo.studentBase.classId;
  1807. List<SemesterData> semesterDatas = studentInfo.portrait.semesterData;
  1808. if (semesterDatas.Any())
  1809. {
  1810. semesterDatas.ForEach(data =>
  1811. {
  1812. if (!string.IsNullOrWhiteSpace(data.semesterId))
  1813. {
  1814. var semester = period.semesters.Find(s => s.id.Equals(data.semesterId));
  1815. //如果找到对应的semesterId则直接使用当前semesterId
  1816. if (semester == null)
  1817. {
  1818. //先处理,最后再检查。
  1819. data.semesterId = $"{data.semesterId}--semesterId学期无效";
  1820. if (data.semester > 0)
  1821. {
  1822. int count = period.semesters.Count();
  1823. if (count >= data.semester)
  1824. {
  1825. data.semesterId = sortedSemesters[data.semester - 1].id;
  1826. }
  1827. else
  1828. {
  1829. data.semesterId = $"{data.semester}--semester学期无效";
  1830. }
  1831. }
  1832. else
  1833. {
  1834. data.semesterId = $"{data.semester}--semester学期无效";
  1835. //无效的学期数
  1836. }
  1837. }
  1838. }
  1839. else
  1840. {
  1841. data.semesterId = $"{data.semesterId}--semesterId学期无效";
  1842. if (data.semester > 0)
  1843. {
  1844. int count = period.semesters.Count();
  1845. if (count >= data.semester)
  1846. {
  1847. data.semesterId = sortedSemesters[data.semester - 1].id;
  1848. }
  1849. else
  1850. {
  1851. data.semesterId = $"{data.semester}--semester学期无效";
  1852. }
  1853. }
  1854. else
  1855. {
  1856. data.semesterId = $"{data.semester}--semester学期无效";
  1857. //无效的学期数
  1858. }
  1859. }
  1860. });
  1861. var noSemesterDatas = semesterDatas.Where(z => z.semesterId.Contains("学期无效")).ToList();
  1862. if (noSemesterDatas.Any())
  1863. {
  1864. unmatchSemester.Add(new PortraitStudent
  1865. {
  1866. studentId = studentInfo.portrait.studentId,
  1867. name = studentInfo.portrait.name,
  1868. classId = studentInfo.portrait.classId,
  1869. semesterData = noSemesterDatas,
  1870. });
  1871. }
  1872. var okSemesterDatas = semesterDatas.Where(z => !z.semesterId.Contains("学期无效"));
  1873. if (okSemesterDatas.Any())
  1874. {
  1875. upsertDatas.Add(new PortraitStudent
  1876. {
  1877. studentId = studentInfo.portrait.studentId,
  1878. name = studentInfo.portrait.name,
  1879. classId = studentInfo.portrait.classId,
  1880. semesterData = okSemesterDatas.ToList(),
  1881. });
  1882. }
  1883. var ids = okSemesterDatas.Select(k => $"{k.year}-{k.semesterId}-{studentId}");
  1884. if (ids.Any())
  1885. {
  1886. List<OverallEducation> overallEducations = new List<OverallEducation>();
  1887. string sql = $"select value c from c where c.id in ({string.Join(",", ids.Select(f => $"'{f}'"))})" +
  1888. $" and c.studentId ='{studentId}' and c.schoolCode='{schoolCode}' and c.periodId='{periodId}' and c.classId='{classId}'";
  1889. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Student)
  1890. .GetItemQueryIterator<OverallEducation>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"OverallEducation-{schoolCode}") }))
  1891. {
  1892. overallEducations.Add(item);
  1893. }
  1894. var nodbids = ids.Except(overallEducations.Select(x => x.id));
  1895. var newDatas = semesterDatas.FindAll(k => nodbids.Contains($"{k.year}-{k.semesterId}-{studentId}"));
  1896. var updateDatas = semesterDatas.FindAll(k => overallEducations.Select(z => z.id).Contains($"{k.year}-{k.semesterId}-{studentId}"));
  1897. List<OverallEducation> newOverallEducations = new List<OverallEducation>();
  1898. newDatas.ForEach(z =>
  1899. {
  1900. //处理新增的学生学期画像
  1901. var overallEducation = newOverallEducations.Find(o => o.id.Equals($"{z.year}-{z.semesterId}-{studentId}") && o.code.Equals($"OverallEducation-{schoolCode}"));
  1902. if (overallEducation == null)
  1903. {
  1904. overallEducation = new OverallEducation
  1905. {
  1906. id = $"{z.year}-{z.semesterId}-{studentId}",
  1907. code = $"OverallEducation-{schoolCode}",
  1908. pk = "OverallEducation",
  1909. ttl = -1,
  1910. name = student.name,
  1911. classId = student.classId,
  1912. schoolCode = $"{schoolCode}",
  1913. semesterId = z.semesterId,
  1914. year = z.year,
  1915. periodId = $"{periodId}",
  1916. stuYear = student.year,
  1917. studentId = student.id,
  1918. };
  1919. newOverallEducations.Add(overallEducation);
  1920. }
  1921. });
  1922. if (newOverallEducations.Any())
  1923. {
  1924. (newOverallEducations, unmatchItemScoreType) = FillSemesterData(studentId, $"{subjectId}", newOverallEducations, unmatchItemScoreType, newDatas,period);
  1925. foreach (var edu in newOverallEducations)
  1926. {
  1927. await client.GetContainer(Constant.TEAMModelOS, Constant.Student).CreateItemAsync(edu, new PartitionKey(edu.code));
  1928. string key = $"OverallEducation:{edu.schoolCode}:{edu.periodId}:{edu.year}:{edu.semesterId}:{edu.classId}";
  1929. await _azureRedis.GetRedisClient(8).HashSetAsync(key, edu.studentId, edu.ToJsonString());
  1930. await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, new TimeSpan(180 * 24, 0, 0));
  1931. }
  1932. }
  1933. if (overallEducations.Any())
  1934. {
  1935. (overallEducations, unmatchItemScoreType) = FillSemesterData(studentId, $"{subjectId}", overallEducations, unmatchItemScoreType, updateDatas, period);
  1936. foreach (var edu in overallEducations)
  1937. {
  1938. await client.GetContainer(Constant.TEAMModelOS, Constant.Student).ReplaceItemAsync(edu, edu.id, new PartitionKey(edu.code));
  1939. string key = $"OverallEducation:{edu.schoolCode}:{edu.periodId}:{edu.year}:{edu.semesterId}:{edu.classId}";
  1940. await _azureRedis.GetRedisClient(8).HashSetAsync(key, edu.studentId, edu.ToJsonString());
  1941. await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, new TimeSpan(180 * 24, 0, 0));
  1942. }
  1943. }
  1944. }
  1945. }
  1946. }
  1947. }
  1948. return responseData = new() { data = new { unmatchStuInfo, unmatchSemester, unmatchItemScoreType, upsertDatas }, code = RespondCode.Ok, msg = "成功" };
  1949. }
  1950. catch (CosmosException cex) when (cex.Status == 404)
  1951. {
  1952. return new ResponseData<dynamic>() { code = RespondCode.NotFound, msg = "学校编码不存在" };
  1953. }
  1954. catch (Exception ex)
  1955. {
  1956. await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/UpsertStudentPortrait() ,参数json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  1957. return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务端异常" };
  1958. }
  1959. }
  1960. public static (List<OverallEducation> overallEducations, List<PortraitStudent> unmatchItemScoreType) FillSemesterData(string studentId, string subjectId, List<OverallEducation> overallEducations,List<PortraitStudent> unmatchItemScoreType, List<SemesterData> semestersDatas,Period period)
  1961. {
  1962. foreach (var z in semestersDatas)
  1963. {
  1964. var oedu = overallEducations.Find(x => x.id.Equals($"{z.year}-{z.semesterId}-{studentId}"));
  1965. if (oedu != null)
  1966. {
  1967. List<EducationScore> educationScores = null;
  1968. switch (true)
  1969. {
  1970. case bool when $"{subjectId}".Equals("subject_sport"):
  1971. educationScores = oedu.sports;
  1972. break;
  1973. case bool when $"{subjectId}".Equals("subject_virtue"):
  1974. educationScores = oedu.virtue;
  1975. break;
  1976. case bool when $"{subjectId}".Equals("subject_labour"):
  1977. educationScores = oedu.labour;
  1978. break;
  1979. case bool when $"{subjectId}".Equals("subject_intelligence"):
  1980. {
  1981. educationScores = oedu.intelligence;
  1982. //对评测需要验证 细项的具体信息
  1983. bool isunmatch = false;
  1984. foreach (var v in z.itemScore)
  1985. {
  1986. var subject = period.subjects.Find(b => b.id.Equals(v.type));
  1987. if (subject == null)
  1988. {
  1989. isunmatch = true;
  1990. }
  1991. }
  1992. if (isunmatch)
  1993. {
  1994. unmatchItemScoreType.Add(new PortraitStudent { classId = oedu.classId, name = oedu.name, studentId = oedu.studentId, semesterData = new List<SemesterData> { z } });
  1995. continue;
  1996. }
  1997. break;
  1998. }
  1999. case bool when $"{subjectId}".Equals("subject_art"):
  2000. {
  2001. educationScores = oedu.art;
  2002. //对艺术评测需要验证 细项的具体信息
  2003. bool isunmatch = false;
  2004. foreach (var v in z.itemScore)
  2005. {
  2006. var subject = period.subjects.Find(b =>!string .IsNullOrWhiteSpace(b.bindId) && b.bindId.Equals(v.type));
  2007. if (subject == null)
  2008. {
  2009. isunmatch = true;
  2010. }
  2011. }
  2012. if (isunmatch)
  2013. {
  2014. unmatchItemScoreType.Add(new PortraitStudent { classId = oedu.classId, name = oedu.name, studentId = oedu.studentId, semesterData = new List<SemesterData> { z } });
  2015. continue;
  2016. }
  2017. break;
  2018. }
  2019. default:
  2020. educationScores = new List<EducationScore>();
  2021. break;
  2022. }
  2023. var edu = educationScores.Find(m => m.examId.Equals(z.examId));
  2024. z.totalScore = z.totalScore <= 0 ? 100 : z.totalScore;
  2025. if (edu == null)
  2026. {
  2027. edu = new EducationScore();
  2028. educationScores.Add(edu);
  2029. }
  2030. edu.examId = z.examId;
  2031. edu.examDate = z.examDate;
  2032. edu.examName = z.examName;
  2033. edu.examType = z.examType;
  2034. edu.excellenceRate = z.excellenceRate;
  2035. edu.totalScore = z.totalScore;
  2036. edu.rate = z.sumScore / z.totalScore;
  2037. edu.level = z.sumScore / z.totalScore;
  2038. edu.sumScore = z.sumScore;
  2039. edu.passRate = z.passRate;
  2040. edu.itemScore = z.itemScore;
  2041. }
  2042. }
  2043. return (overallEducations, unmatchItemScoreType);
  2044. }
  2045. public static void GenApiTableRecord(AzureStorageFactory azureStorage)
  2046. {
  2047. //在开发模式时,自检 [ApiToken(Auth = "1")] 有重复的接口 https://teammodelos.table.core.chinacloudapi.cn/IESOpenApi
  2048. (List<OpenApi> openApis, List<ApiTokenAttribute> attributes) = ReflectorExtensions.GetOpenApi(new string[] { "TEAMModelOS" });
  2049. openApis.GroupBy(x => $"{x.PartitionKey}{x.RowKey}").ToList().ForEach(x =>
  2050. {
  2051. if (x.Count() > 1)
  2052. {
  2053. throw new Exception($"接口Auth重复定义{x.ToList()}");
  2054. }
  2055. });
  2056. var table = azureStorage.GetCloudTableClient().GetTableReference("IESOpenApi");
  2057. openApis = openApis.OrderBy(x => x.RowKey).ToList();
  2058. string tbqurey = $"PartitionKey {QueryComparisons.Equal} 'IES5-API' and RowKey {QueryComparisons.GreaterThanOrEqual} '{openApis.First().RowKey}' and RowKey {QueryComparisons.LessThanOrEqual} '{openApis.Last().RowKey}' ";
  2059. var apiResult = table.ExecuteQuerySegmented(new TableQuery<OpenApi>().Where(tbqurey), null);
  2060. List<OpenApi> apis = apiResult.Results;
  2061. //数据库历史数据处理
  2062. apis.ForEach(x =>
  2063. {
  2064. var api = openApis.Find(z => z.RowKey.Equals(x.RowKey));
  2065. if (api != null)
  2066. {
  2067. x.auth = api.auth;
  2068. x.name = api.name;
  2069. x.type = api.type;
  2070. x.url = api.url;
  2071. x.method = api.method;
  2072. }
  2073. });
  2074. openApis.RemoveAll(x => apis.Select(z => z.RowKey).Contains(x.RowKey));
  2075. openApis.AddRange(apis);
  2076. _ = table.SaveOrUpdateAll<OpenApi>(openApis);
  2077. string dataopenApis = openApis.ToJsonString();
  2078. (List<WebHook> webHooks, List<ApiTokenAttribute> _attributes) = ReflectorExtensions.GetWebHook(new string[] { "TEAMModelOS.SDK" });
  2079. webHooks.GroupBy(x => $"{x.PartitionKey}{x.RowKey}").ToList().ForEach(x =>
  2080. {
  2081. if (x.Count() > 1)
  2082. {
  2083. throw new Exception($"接口Auth重复定义{x.ToList()}");
  2084. }
  2085. });
  2086. webHooks = webHooks.OrderBy(x => x.RowKey).ToList();
  2087. tbqurey = $"PartitionKey {QueryComparisons.Equal} 'IES5-WEBHOOK' and RowKey {QueryComparisons.GreaterThanOrEqual} '{webHooks.First().RowKey}' and RowKey {QueryComparisons.LessThanOrEqual} '{webHooks.Last().RowKey}' ";
  2088. var hookResult = table.ExecuteQuerySegmented(new TableQuery<WebHook>().Where(tbqurey), null);
  2089. List<WebHook> hooks = hookResult.Results;
  2090. //数据库历史数据处理
  2091. hooks.ForEach(x =>
  2092. {
  2093. var api = webHooks.Find(z => z.RowKey.Equals(x.RowKey));
  2094. if (api != null)
  2095. {
  2096. x.auth = api.auth;
  2097. x.name = api.name;
  2098. x.ename = api.ename;
  2099. x.tname = api.tname;
  2100. x.type = api.type;
  2101. x.url = api.url;
  2102. x.method = api.method;
  2103. x.notice = api.notice;
  2104. }
  2105. });
  2106. webHooks.RemoveAll(x => hooks.Select(z => z.RowKey).Contains(x.RowKey));
  2107. webHooks.AddRange(hooks);
  2108. _ = table.SaveOrUpdateAll<WebHook>(webHooks);
  2109. string datawebHooks = webHooks.ToJsonString();
  2110. }
  2111. /// <summary>
  2112. /// 学生登录信息
  2113. /// </summary>
  2114. /// <param name="_azureCosmos"></param>
  2115. /// <param name="_dingDing"></param>
  2116. /// <param name="bizId"></param>
  2117. /// <param name="school"></param>
  2118. /// <param name="json"></param>
  2119. /// <returns></returns>
  2120. public static async Task<ResponseData<dynamic>> GetLoginStuInfo(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string bizId, string school, JsonElement json)
  2121. {
  2122. if (!json.TryGetProperty("idToken", out JsonElement _idToken)) return new ResponseData<dynamic>() { code = RespondCode.ParamsError, msg = "idToken参数错误", data = null };
  2123. JwtSecurityToken jwt = new($"{_idToken}");
  2124. var iss = jwt.Payload.Iss;
  2125. var stuId = jwt.Payload.Sub;
  2126. var scId = jwt.Payload.Azp;
  2127. try
  2128. {
  2129. var client = _azureCosmos.GetCosmosClient();
  2130. //if (!string.IsNullOrWhiteSpace($"{_idToken}") && JwtAuthExtension.ValidateApiToken($"{_idToken}", _option.JwtSecretKey))
  2131. //{
  2132. // JwtSecurityToken jwt = new($"{_idToken}");
  2133. //}
  2134. OStudent student = new();
  2135. jwt.Payload.TryGetValue("name", out object stuName);
  2136. jwt.Payload.TryGetValue("picture", out object stuPicture);
  2137. if (!jwt.Payload.TryGetValue("scope", out object scope)) return new ResponseData<dynamic>() { code = RespondCode.ParamsError, msg = "参数错误:scope", data = null };
  2138. if (!jwt.Payload.TryGetValue("roles", out object _roles)) return new ResponseData<dynamic>() { code = RespondCode.ParamsError, msg = "参数错误:roles", data = null };
  2139. jwt.Payload.TryGetValue("permissions", out object permissions);
  2140. jwt.Payload.TryGetValue("standard", out object standard);
  2141. jwt.Payload.TryGetValue("area", out object area);
  2142. jwt.Payload.TryGetValue("website", out object website);
  2143. List<string> roles = $"{_roles}".ToObject<List<string>>();
  2144. if (roles.Contains("student") && $"{scope}".Equals("student"))
  2145. {
  2146. if (!string.IsNullOrEmpty(stuId) && !string.IsNullOrEmpty(scId))
  2147. {
  2148. if (school.Equals(scId))
  2149. {
  2150. var responseStu = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemStreamAsync(stuId, new PartitionKey($"Base-{scId}"));
  2151. if (responseStu.Status == 200)
  2152. {
  2153. JsonDocument jsonD = JsonDocument.Parse(responseStu.Content);
  2154. student = jsonD.RootElement.ToObject<OStudent>();
  2155. switch (student.gender)
  2156. {
  2157. case "M":
  2158. student.gender = "男";
  2159. break;
  2160. case "F":
  2161. student.gender = "女";
  2162. break;
  2163. case "N":
  2164. student.gender = "保密";
  2165. break;
  2166. }
  2167. }
  2168. else
  2169. { return new ResponseData<dynamic>() { code = RespondCode.NotFound, msg = "未找到该学生", data = new { id = stuId, schoolId = scId } }; }
  2170. }
  2171. else
  2172. { return new ResponseData<dynamic>() { code = RespondCode.NotFound, msg = "headers和idToken中的学校ID不匹配", data = null }; }
  2173. }
  2174. else
  2175. { return new ResponseData<dynamic>() { code = RespondCode.ParamsError, msg = "参数错误:Sub/scId", data = null }; }
  2176. }
  2177. else
  2178. { return new ResponseData<dynamic>() { code = RespondCode.ParamsError, msg = "参数错误:roles/Azp", data = null }; }
  2179. return new ResponseData<dynamic>() { code = RespondCode.Ok, msg = "成功", data = student };
  2180. }
  2181. catch (Exception ex)
  2182. {
  2183. await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetLoginStuInfo() 参数:stu:{stuId},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  2184. return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务器错误" };
  2185. }
  2186. }
  2187. /// <summary>
  2188. /// 获取学生详细信息
  2189. /// </summary>
  2190. /// <param name="_azureCosmos"></param>
  2191. /// <param name="_dingDing"></param>
  2192. /// <param name="bizId"></param>
  2193. /// <param name="school"></param>
  2194. /// <param name="json"></param>
  2195. /// <returns></returns>
  2196. public static async Task<ResponseData<dynamic>> GetStudentInfo(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string school, JsonElement json)
  2197. {
  2198. if (!json.TryGetProperty("ids", out JsonElement _ids)) return new ResponseData<dynamic>() { code = RespondCode.ParamsError, msg = "idToken参数错误", data = null };
  2199. try
  2200. {
  2201. List<string> ids = _ids.ToObject<List<string>>();
  2202. List<OStudent> student = new();
  2203. //List<OStudent> tmdId = new();
  2204. string sqlStu = $"select value(c) from c ";
  2205. if (ids.Count > 0)
  2206. sqlStu = $"select value(c) from c where c.id in ({string.Join(",", ids.Select(s => $"'{s}'"))})";
  2207. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<OStudent>(queryText: sqlStu, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{school}") }))
  2208. {
  2209. student.Add(item);
  2210. }
  2211. //string sqlTmd = $"select value(c) from c join s in c.schools where c.id in ({string.Join(",", ids.Select(s => $"'{s}'"))}) and s.schoolId='{school}'";
  2212. //await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<OStudent>(queryText: sqlTmd, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  2213. //{
  2214. // tmdId.Add(item);
  2215. //}
  2216. return new ResponseData<dynamic>() { code = RespondCode.Ok, msg = "成功", data = student };
  2217. }
  2218. catch (Exception ex)
  2219. {
  2220. await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetLoginStuInfo() 参数:学生id集合:{_ids},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  2221. return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务器错误" };
  2222. }
  2223. }
  2224. public static async Task<ResponseData<dynamic>> UpsertSchoolItem(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureRedisFactory azureRedis, JsonElement jsonElement, string school)
  2225. {
  2226. return new ResponseData<dynamic>() { };
  2227. }
  2228. }
  2229. /*
  2230. {
  2231. "id": "", //题目id,id值为空则新增,不为空尝试更新,更新失败则新增
  2232. "level": 1, //1-5题目难度
  2233. "knowledge": [
  2234. "知识点1",
  2235. "知识点2"
  2236. ], //知识点
  2237. "answer": [
  2238. "答案1",
  2239. "答案2"
  2240. ], //答案, "单选题","多选题","有序多选题","判断题"等的答案为[A,B,C,D,E]等数组,如果是填空题答案为字符串数组,问答题答案为字符串。
  2241. "explain": "解析",
  2242. "type": "single", //题目类型,"single": "单选题", "multiple": "多选题", "sortmultiple": "有序多选题", "judge": "判断题", "complete": "填空题", "subjective": "问答题", "compose": "综合题"
  2243. "pid": "综合题父级题目id",
  2244. "field": 1, //布鲁姆认知层次 1:记忆|2:理解|3:应用|4:分析|:5评价|6:创造
  2245. "subject": "语文", //学科,语文/数学/英语/物理/化学/地理/历史/生物/政治, 如果有其他学科,按学科名称传递即可。
  2246. "grade": [
  2247. "1",
  2248. "2",
  2249. "3",
  2250. "4"
  2251. ], //年级,1-6年级/1-5年级(小学),7-9年级/6-9年级(初中),10-12年级(高中)
  2252. "question": "题干信息",
  2253. "option":[{"code":"A","value":"选项A的内容"},{ "code":"B","value":"选项B的内容"}],//单选,多选,有序多选题,判断题的选项。其中判断题可为[{"code":"A","value":"正确/对"},{"code":"B","value":"错误/错"}]
  2254. "children":[
  2255. {}//子题目,包含题型"单选题", "多选题", "有序多选题", "判断题", "填空题", "问答题"
  2256. ]
  2257. }
  2258. **/
  2259. /// <summary>
  2260. ///
  2261. ///
  2262. /// </summary>
  2263. public class OItem
  2264. {
  2265. /// <summary>
  2266. /// //题目id,id值为空则新增,不为空尝试更新,更新失败则新增
  2267. /// </summary>
  2268. public string id { get; set; }
  2269. /// <summary>
  2270. /// 1-5题目难度
  2271. /// </summary>
  2272. public int level { get; set; }
  2273. /// <summary>
  2274. /// 知识点
  2275. /// </summary>
  2276. public List<string> knowledge { get; set; } = new List<string>();
  2277. /// <summary>
  2278. /// 答案, "单选题","多选题","有序多选题","判断题"等的答案为[A,B,C,D,E]等数组,如果是填空题答案为字符串数组,问答题答案为字符串。
  2279. /// </summary>
  2280. public List<string> answer { get; set; } = new List<string>();
  2281. /// <summary>
  2282. /// 解析
  2283. /// </summary>
  2284. public string explain { get; set; }
  2285. /// <summary>
  2286. /// 题目类型,"single": "单选题", "multiple": "多选题", "sortmultiple": "有序多选题", "judge": "判断题", "complete": "填空题", "subjective": "问答题", "compose": "综合题"
  2287. /// </summary>
  2288. public string type { get; set; }
  2289. /// <summary>
  2290. /// 综合题父级题目id,当前题目是某一综合题的子题时才填写,否则为null,
  2291. /// </summary>
  2292. public string pid { get; set; }
  2293. /// <summary>
  2294. /// 布鲁姆认知层次 1:记忆|2:理解|3:应用|4:分析|:5评价|6:创造
  2295. /// </summary>
  2296. public int field { get; set; } = 1;
  2297. /// <summary>
  2298. /// 学科,语文/数学/英语/物理/化学/地理/历史/生物/政治, 如果有其他学科,按学科名称传递即可。
  2299. /// </summary>
  2300. public string subject { get; set; }
  2301. /// <summary>
  2302. /// 年级,1-6年级/1-5年级(小学),7-9年级/6-9年级(初中),10-12年级(高中)
  2303. /// </summary>
  2304. public List<int> grade { get; set; } = new List<int>();
  2305. /// <summary>
  2306. /// 题干信息
  2307. /// </summary>
  2308. public string question { get; set; }
  2309. /// <summary>
  2310. /// 单选,多选,有序多选题,判断题的选项。其中判断题可为[{"code":"A","value":"正确/对"},{"code":"B","value":"错误/错"}]
  2311. /// </summary>
  2312. public List<CodeValue> option { get; set; } = new List<CodeValue>();
  2313. /// <summary>
  2314. /// 子题目,包含题型"单选题", "多选题", "有序多选题", "判断题", "填空题", "问答题"
  2315. /// </summary>
  2316. public List<OItem> children { get; set; } = new List<OItem>();
  2317. }
  2318. public class OCourseBase
  2319. {
  2320. public string tmdname { get; set; }
  2321. public string courseName { get; set; }
  2322. public int attendCount { get; set; }
  2323. public int mCount { get; set; }
  2324. public List<string> groups { get; set; }
  2325. public long time { get; set; }
  2326. public List<Events> eves { get; set; }
  2327. public List<Videos> videos { get; set; }
  2328. }
  2329. public class Events
  2330. {
  2331. public string @event { get; set; }
  2332. public int freq { get; set; }
  2333. public long createTime { get; set; }
  2334. }
  2335. public class Videos
  2336. {
  2337. public string videoName { get; set; }
  2338. public string video { get; set; }
  2339. public int duration { get; set; }
  2340. public long startTime { get; set; }
  2341. }
  2342. }