OpenApiService.cs 132 KB

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