OpenApiService.cs 131 KB

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