ActiveTaskTopic.cs 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Text.Json;
  5. using System.Threading.Tasks;
  6. using Azure.Cosmos;
  7. using Azure.Messaging.ServiceBus;
  8. using Microsoft.Extensions.Logging;
  9. using StackExchange.Redis;
  10. using TEAMModelOS.SDK.DI;
  11. using TEAMModelOS.SDK.Extension;
  12. using TEAMModelOS.SDK;
  13. using TEAMModelOS.SDK.Models;
  14. using TEAMModelOS.SDK.Models.Cosmos;
  15. using TEAMModelOS.SDK.Models.Cosmos.Common;
  16. using System.Linq;
  17. using TEAMModelOS.SDK.Models.Service;
  18. using TEAMModelOS.SDK.Models.Cosmos.BI;
  19. using TEAMModelOS.Models;
  20. using Microsoft.Extensions.Options;
  21. using Microsoft.Extensions.Configuration;
  22. using HTEXLib.COMM.Helpers;
  23. using Microsoft.Azure.Functions.Worker;
  24. using TEAMModelOS.SDK.Services;
  25. using Azure.Storage.Blobs.Models;
  26. using System.IO;
  27. namespace TEAMModelOS.FunctionV4.ServiceBus
  28. {
  29. public class ActiveTaskTopic
  30. {
  31. private readonly AzureCosmosFactory _azureCosmos;
  32. private readonly DingDing _dingDing;
  33. private readonly AzureStorageFactory _azureStorage;
  34. private readonly AzureRedisFactory _azureRedis;
  35. private readonly AzureServiceBusFactory _serviceBus;
  36. private readonly Option _option;
  37. private readonly NotificationService _notificationService;
  38. private readonly CoreAPIHttpService _coreAPIHttpService;
  39. private readonly IConfiguration _configuration;
  40. public ActiveTaskTopic(CoreAPIHttpService coreAPIHttpService,AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, AzureServiceBusFactory serviceBus, IOptionsSnapshot<Option> option, NotificationService notificationService, IConfiguration configuration)
  41. {
  42. _azureCosmos = azureCosmos;
  43. _dingDing = dingDing;
  44. _azureStorage = azureStorage;
  45. _azureRedis = azureRedis;
  46. _serviceBus = serviceBus;
  47. _option = option?.Value;
  48. _notificationService = notificationService;
  49. _configuration = configuration;
  50. _coreAPIHttpService = coreAPIHttpService;
  51. }
  52. [Function("Exam")]
  53. public async Task ExamFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "exam", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  54. {
  55. try
  56. {
  57. var json = JsonDocument.Parse(msg);
  58. json.RootElement.TryGetProperty("id", out JsonElement id);
  59. json.RootElement.TryGetProperty("progress", out JsonElement progress);
  60. json.RootElement.TryGetProperty("code", out JsonElement code);
  61. //Dictionary<string, object> keyValuePairs = mySbMsg.ToObject<Dictionary<string, object>>();
  62. var client = _azureCosmos.GetCosmosClient();
  63. ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{code}"));
  64. exam.progress = progress.ToString();
  65. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"{code}"));
  66. }
  67. catch (CosmosException e)
  68. {
  69. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamBus()-CosmosDB异常{e.Message}\n{e.Status}", GroupNames.成都开发測試群組);
  70. }
  71. catch (Exception ex)
  72. {
  73. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamBus()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  74. }
  75. }
  76. [Function("Vote")]
  77. public async Task VoteFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "vote", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  78. {
  79. try
  80. {
  81. var jsonMsg = JsonDocument.Parse(msg);
  82. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  83. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  84. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  85. var client = _azureCosmos.GetCosmosClient();
  86. Vote vote = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Vote>(id.ToString(), new PartitionKey($"{code}"));
  87. vote.progress = progress.ToString();
  88. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(vote, id.ToString(), new PartitionKey($"{code}"));
  89. }
  90. catch (CosmosException e)
  91. {
  92. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,VoteBus()-CosmosDB异常{e.Message}\n{e.Status}", GroupNames.成都开发測試群組);
  93. }
  94. catch (Exception ex)
  95. {
  96. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,VoteBus()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  97. }
  98. }
  99. [Function("Correct")]
  100. public async Task CorrectFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "correct", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  101. {
  102. try
  103. {
  104. var jsonMsg = JsonDocument.Parse(msg);
  105. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  106. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  107. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  108. var client = _azureCosmos.GetCosmosClient();
  109. Correct correct = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Correct>(id.ToString(), new PartitionKey($"{code}"));
  110. correct.progress = progress.ToString();
  111. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(correct, id.ToString(), new PartitionKey($"{code}"));
  112. }
  113. catch (CosmosException e)
  114. {
  115. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Correct()-CosmosDB异常{e.Message}\n{e.Status}", GroupNames.成都开发測試群組);
  116. }
  117. catch (Exception ex)
  118. {
  119. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Correct()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  120. }
  121. }
  122. [Function("Survey")]
  123. public async Task SurveyFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "survey", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  124. {
  125. try
  126. {
  127. var jsonMsg = JsonDocument.Parse(msg);
  128. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  129. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  130. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  131. //Dictionary<string, object> keyValuePairs = mySbMsg.ToObject<Dictionary<string, object>>();
  132. var client = _azureCosmos.GetCosmosClient();
  133. Survey survey = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Survey>(id.ToString(), new PartitionKey($"{code}"));
  134. survey.progress = progress.ToString();
  135. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(survey, id.ToString(), new PartitionKey($"{code}"));
  136. }
  137. catch (CosmosException e)
  138. {
  139. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,SurveyBus()-CosmosDB异常{e.Message}\n{e.Status}", GroupNames.成都开发測試群組);
  140. }
  141. catch (Exception ex)
  142. {
  143. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,SurveyBus()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  144. }
  145. }
  146. [Function("Homework")]
  147. public async Task HomeworkFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "homework", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  148. {
  149. try
  150. {
  151. var jsonMsg = JsonDocument.Parse(msg);
  152. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  153. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  154. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  155. var client = _azureCosmos.GetCosmosClient();
  156. Homework homework = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Homework>(id.ToString(), new PartitionKey($"{code}"));
  157. homework.progress = progress.ToString();
  158. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(homework, id.ToString(), new PartitionKey($"{code}"));
  159. }
  160. catch (CosmosException e)
  161. {
  162. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Homework()-CosmosDB异常{e.Message}\n{e.Status}", GroupNames.成都开发測試群組);
  163. }
  164. catch (Exception ex)
  165. {
  166. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Homework()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  167. }
  168. }
  169. [Function("Study")]
  170. public async Task StudyFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "study", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  171. {
  172. try
  173. {
  174. var jsonMsg = JsonDocument.Parse(msg);
  175. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  176. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  177. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  178. var client = _azureCosmos.GetCosmosClient();
  179. Study study = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Study>(id.ToString(), new PartitionKey($"{code}"));
  180. study.progress = progress.ToString();
  181. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(study, id.ToString(), new PartitionKey($"{code}"));
  182. }
  183. catch (CosmosException e)
  184. {
  185. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Study()-CosmosDB异常{e.Message}\n{e.Status}", GroupNames.成都开发測試群組);
  186. }
  187. catch (Exception ex)
  188. {
  189. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Study()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  190. }
  191. }
  192. [Function("ExamLite")]
  193. public async Task ExamLiteFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "examlite", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  194. {
  195. try
  196. {
  197. var jsonMsg = JsonDocument.Parse(msg);
  198. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  199. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  200. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  201. var client = _azureCosmos.GetCosmosClient();
  202. ExamLite lite = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamLite>(id.ToString(), new PartitionKey($"{code}"));
  203. lite.progress = progress.ToString();
  204. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(lite, id.ToString(), new PartitionKey($"{code}"));
  205. }
  206. catch (CosmosException e)
  207. {
  208. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamLite()-CosmosDB异常{e.Message}\n{e.Status}", GroupNames.成都开发測試群組);
  209. }
  210. catch (Exception ex)
  211. {
  212. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamLite()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  213. }
  214. }
  215. /// <summary>
  216. /// 根据容器的根目录刷新redis并获取redis的最新使用情况
  217. /// </summary>
  218. /// <param name="msg"></param>
  219. /// <returns></returns>
  220. [Function("BlobRoot")]
  221. public async Task BlobRootFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "blobroot", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  222. {
  223. try
  224. {
  225. var jsonMsg = JsonDocument.Parse(msg);
  226. if (jsonMsg.RootElement.TryGetProperty("name", out JsonElement _name) && _name.ValueKind == JsonValueKind.String
  227. && jsonMsg.RootElement.TryGetProperty("root", out JsonElement root) && root.ValueKind == JsonValueKind.String)
  228. {
  229. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob() 容器:触发变更,{jsonMsg.ToJsonString()}",
  230. // GroupNames.成都开发測試群組);
  231. List<Dictionary<string, double?>> list = new List<Dictionary<string, double?>>();
  232. string[] uls = System.Web.HttpUtility.UrlDecode($"{root}", Encoding.UTF8).Split("/");
  233. string u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
  234. string name = $"{_name}";
  235. string lockKey = $"Blob:Lock:{name}:{u}";
  236. bool exist = await _azureRedis.GetRedisClient(8).KeyExistsAsync(lockKey);
  237. if (!exist)
  238. { ///key不存在则正常进行计算
  239. bool condition = false;
  240. TimeSpan timeSpan = new TimeSpan(DateTimeOffset.UtcNow.AddMinutes(5).Ticks);
  241. timeSpan = timeSpan - new TimeSpan(DateTimeOffset.UtcNow.Ticks);
  242. //准备处理Blob刷新时间
  243. long action = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  244. await _azureRedis.GetRedisClient(8).StringSetAsync(lockKey, action, expiry: timeSpan);
  245. await RefreshBlob(name, u);
  246. //将action 与Redis最新的时间进行比较,如果
  247. var rds = await CheckLockKey(lockKey, action);
  248. condition = rds.condition;
  249. exist = rds.exist;
  250. if (condition || !exist)
  251. {
  252. await RefreshBlob(name, u);
  253. }
  254. //使用 CancellationToken
  255. //while (condition || !exist)
  256. //{
  257. //}
  258. }
  259. else
  260. {
  261. ///key存在则,则刷新key对应的值
  262. TimeSpan timeSpan = new TimeSpan(DateTimeOffset.UtcNow.AddMinutes(5).Ticks);
  263. timeSpan = timeSpan - new TimeSpan(DateTimeOffset.UtcNow.Ticks);
  264. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  265. await _azureRedis.GetRedisClient(8).StringSetAsync(lockKey, now, expiry: timeSpan);
  266. }
  267. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob() 容器:{name}使用:{u},文件分类:{list.ToJsonString()}",
  268. // GroupNames.成都开发測試群組);
  269. }
  270. }
  271. catch (Exception ex)
  272. {
  273. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  274. }
  275. }
  276. private async Task<(bool condition, bool exist)> CheckLockKey(string lockKey, long nowTime)
  277. {
  278. //Redis的最新时间
  279. long newestTime = 0;
  280. RedisValue value = await _azureRedis.GetRedisClient(8).StringGetAsync(lockKey);
  281. if (value != default && !value.IsNullOrEmpty)
  282. {
  283. JsonElement record = value.ToString().ToObject<JsonElement>();
  284. if (record.TryGetInt64(out newestTime))
  285. {
  286. }
  287. }
  288. //说明key已经不存在
  289. if (newestTime == 0)
  290. {
  291. return (false, true);
  292. }
  293. //说明key存在
  294. else
  295. {
  296. //说明Redis记录了最新的时间戳
  297. if (nowTime != newestTime)
  298. {
  299. return (true, false);
  300. }
  301. //时间相同,没有被再次记录最新的时间戳
  302. else
  303. {
  304. await _azureRedis.GetRedisClient(8).KeyDeleteAsync(lockKey);
  305. return (false, true);
  306. }
  307. }
  308. }
  309. private async Task RefreshBlob(string name, string u)
  310. {
  311. long statr = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  312. var client = _azureStorage.GetBlobContainerClient(name);
  313. var size = await client.GetBlobsSize(u);
  314. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", u);
  315. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", u, size.HasValue ? size.Value : 0);
  316. var scores = await _azureRedis.GetRedisClient(8).SortedSetRangeByRankWithScoresAsync($"Blob:Catalog:{name}");
  317. double blobsize = 0;
  318. if (scores != default && scores != null)
  319. {
  320. foreach (var score in scores)
  321. {
  322. blobsize = blobsize + score.Score;
  323. }
  324. }
  325. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", new RedisValue(name), new RedisValue($"{blobsize}"));
  326. long end = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  327. long dis = (end - statr) / 1000;
  328. long timeout = 10;
  329. if (dis > timeout)
  330. {
  331. await _dingDing.SendBotMsg($"ServiceBus,RefreshBlob:空间计算已经超过{timeout}秒\n容器名:{name}\n文件夹:{u}\n计算时长:{dis}", GroupNames.醍摩豆服務運維群組);
  332. }
  333. }
  334. /// <summary>
  335. /// 完善课程变更,StuListChange, originCode是学校编码 则表示名单是学校自定义名单,如果是tmdid则表示醍摩豆的私有名单,scope=school,private。
  336. /// </summary>
  337. /// <data msg>
  338. /// CourseChange
  339. ///// </data>
  340. /// <param name="msg"></param>
  341. /// <returns></returns>
  342. [Function("TeacherTrainChange")]
  343. public async Task TeacherTrainChangeFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "teacher-train-change", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  344. {
  345. try
  346. {
  347. // await _dingDing.SendBotMsg($"teacher-train-change\n{msg}",GroupNames.成都开发測試群組);
  348. TeacherTrainChange change = msg.ToObject<TeacherTrainChange>();
  349. if (change.update == null || change.update.Count <= 0 || change.tmdids.IsEmpty())
  350. {
  351. return;
  352. }
  353. var client = _azureCosmos.GetCosmosClient();
  354. string insql = $"where c.id in ({string.Join(",", change.tmdids.Select(x => $"'{x}'"))})";
  355. string selsql = $"select value(c) from c {insql} ";
  356. List<TeacherTrain> teacherTrains = new List<TeacherTrain>();
  357. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<TeacherTrain>(queryText: selsql,
  358. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"TeacherTrain-{change.school}") }))
  359. {
  360. teacherTrains.Add(item);
  361. }
  362. if (change.statistics != 1)
  363. {
  364. List<Task<ItemResponse<TeacherTrain>>> task = new List<Task<ItemResponse<TeacherTrain>>>();
  365. teacherTrains.ForEach(x =>
  366. {
  367. x.update.UnionWith(change.update);
  368. task.Add(client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<TeacherTrain>(x, x.id, new PartitionKey($"TeacherTrain-{change.school}")));
  369. });
  370. await task.TaskPage(5);
  371. var unchange = change.tmdids.Except(teacherTrains.Select(x => x.id));
  372. if (unchange != null)
  373. {
  374. task.Clear();
  375. unchange.ToList().ForEach(x =>
  376. {
  377. TeacherTrain teacherTrain = new TeacherTrain
  378. {
  379. pk = "TeacherTrain",
  380. id = x,
  381. code = $"TeacherTrain-{change.school}",
  382. tmdid = x,
  383. school = change.school,
  384. update = new HashSet<string> { StatisticsService.TeacherAbility,
  385. StatisticsService.TeacherClass, StatisticsService.OfflineRecord }
  386. };
  387. teacherTrain.update.UnionWith(change.update);
  388. task.Add(client.GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync<TeacherTrain>(teacherTrain, new PartitionKey($"TeacherTrain-{change.school}")));
  389. });
  390. await task.TaskPage(1);
  391. }
  392. }
  393. else
  394. {
  395. Area area = null;
  396. string sql = $"select value(c) from c where c.standard='{change.standard}'";
  397. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<Area>(queryText: sql,
  398. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-Area") }))
  399. {
  400. area = item;
  401. }
  402. AreaSetting setting = null;
  403. if (area != null)
  404. {
  405. try
  406. {
  407. //优先找校级
  408. setting = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<AreaSetting>(change.school, new PartitionKey("AreaSetting"));
  409. }
  410. catch (CosmosException)
  411. {
  412. try
  413. {
  414. setting = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<AreaSetting>(area.id, new PartitionKey("AreaSetting"));
  415. }
  416. catch (CosmosException)
  417. {
  418. setting = null;
  419. }
  420. }
  421. }
  422. if (setting == null)
  423. {
  424. setting = new AreaSetting
  425. {
  426. allTime = 50,
  427. classTime = 5,
  428. submitTime = 15,
  429. onlineTime = 20,
  430. offlineTime = 10,
  431. lessonMinutes = 45,
  432. };
  433. }
  434. List<Task<TeacherTrain>> task = new List<Task<TeacherTrain>>();
  435. teacherTrains.ForEach(x =>
  436. {
  437. x.update.UnionWith(change.update);
  438. task.Add(StatisticsService.StatisticsTeacher(x, setting, area, client, null));
  439. });
  440. await task.TaskPage(1);
  441. var unchange = change.tmdids.Except(teacherTrains.Select(x => x.id));
  442. if (unchange != null)
  443. {
  444. task.Clear();
  445. unchange.ToList().ForEach(x =>
  446. {
  447. task.Add(StatisticsService.StatisticsTeacher(new TeacherTrain
  448. {
  449. pk = "TeacherTrain",
  450. id = x,
  451. code = $"TeacherTrain-{change.school}",
  452. tmdid = x,
  453. school = change.school,
  454. update = new HashSet<string> { StatisticsService.TeacherAbility,
  455. StatisticsService.TeacherClass, StatisticsService.OfflineRecord }
  456. }, setting, area, client, null));
  457. });
  458. await task.TaskPage(1);
  459. }
  460. }
  461. }
  462. catch (CosmosException ex)
  463. {
  464. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-研修数据变更,重新统计-TeacherTrainChange\n{msg}\n{ex.Message}\n{ex.StackTrace}CosmosException{ex.Status}", GroupNames.成都开发測試群組);
  465. }
  466. catch (Exception ex)
  467. {
  468. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-研修数据变更,重新统计-TeacherTrainChange\n{msg}\n{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  469. }
  470. }
  471. /// <summary>
  472. /// 完善课程变更,StuListChange, originCode是学校编码 则表示名单是学校自定义名单,如果是tmdid则表示醍摩豆的私有名单,scope=school,private。
  473. /// </summary>
  474. /// <data msg>
  475. /// CourseChange
  476. ///// </data>
  477. /// <param name="msg"></param>
  478. /// <returns></returns>
  479. [Function("GroupChange")]
  480. public async Task GroupChangeFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "group-change", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  481. {
  482. var client = _azureCosmos.GetCosmosClient();
  483. try
  484. {
  485. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-名单成员变更-GroupChange\n{msg}", GroupNames.成都开发測試群組);
  486. var jsonMsg = JsonDocument.Parse(msg);
  487. GroupChange groupChange = msg.ToObject<GroupChange>();
  488. //名单变动修改学生课程关联信息
  489. //await StuListService.FixStuCourse(client, stuListChange);
  490. //Vote投票 Survey问卷 Exam评测 Learn学习活动 Homework作业活动
  491. //名单变动修改学生问卷关联信息
  492. await ActivityService.FixActivity(client, _dingDing, groupChange, "Survey");
  493. //名单变动修改学生投票关联信息
  494. await ActivityService.FixActivity(client, _dingDing, groupChange, "Vote");
  495. //名单变动修改学生评测关联信息
  496. await ActivityService.FixActivity(client, _dingDing, groupChange, "Exam");
  497. //TODO学习活动
  498. //await FixActivity(client, stuListChange, "Learn");
  499. if (groupChange.type == null || !groupChange.type.Equals("research") || !groupChange.type.Equals("yxtrain") || !groupChange.type.Equals("activity"))
  500. {
  501. //课程名单变动修改学生课程关联信息
  502. await ActivityService.FixStuCourse(client, _dingDing, groupChange);
  503. //名单变动修改学生研修关联信息
  504. await ActivityService.FixActivity(client, _dingDing, groupChange, "Study");
  505. //名单变动修改学生简易评测关联信息
  506. await ActivityService.FixActivity(client, _dingDing, groupChange, "ExamLite");
  507. //名单变动修改学生作业活动信息
  508. await ActivityService.FixActivity(client, _dingDing, groupChange, "Homework");
  509. }
  510. }
  511. catch (Exception ex)
  512. {
  513. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-GroupChange-GroupChange\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.成都开发測試群組);
  514. }
  515. }
  516. [Function("ItemCond")]
  517. public async Task ItemCondFunc([ServiceBusTrigger("%Azure:ServiceBus:ItemCondQueue%", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  518. {
  519. try
  520. {
  521. var client = _azureCosmos.GetCosmosClient();
  522. var jsonMsg = JsonDocument.Parse(msg);
  523. List<ItemCondDto> itemCondDtos = msg.ToObject<List<ItemCondDto>>();
  524. foreach (var itemCondDto in itemCondDtos)
  525. {
  526. if (itemCondDto.scope.Equals("school"))
  527. {
  528. ItemCond itemCond = null;
  529. List<ItemInfo> items = new List<ItemInfo>();
  530. var queryslt = $"SELECT c.gradeIds,c.subjectId,c.periodId,c.type,c.level,c.field ,c.scope FROM c where c.periodId='{itemCondDto.filed}' and c.pid= null ";
  531. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{itemCondDto.key}") }))
  532. {
  533. items.Add(item);
  534. }
  535. itemCond = new ItemCond()
  536. {
  537. id = $"{itemCondDto.filed}",
  538. code = $"ItemCond-{itemCondDto.key}",
  539. pk = "ItemCond",
  540. ttl = -1,
  541. count = items.Count,
  542. grades = new List<GradeCount>(),
  543. subjects = new List<SubjectItemCount>()
  544. };
  545. items.ForEach(z =>
  546. {
  547. if (!string.IsNullOrEmpty(z.type))
  548. {
  549. ItemService.CountItemCond(z, null, itemCond);
  550. }
  551. });
  552. await _azureRedis.GetRedisClient(8).HashSetAsync($"ItemCond:{itemCondDto.key}", $"{itemCondDto.filed}", itemCond.ToJsonString());
  553. }
  554. else
  555. {
  556. ItemCond itemCond = null;
  557. List<ItemInfo> items = new List<ItemInfo>();
  558. var queryslt = $"SELECT c.gradeIds,c.subjectId,c.periodId,c.type,c.level,c.field ,c.scope FROM c where c.pid= null ";
  559. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{itemCondDto.filed}") }))
  560. {
  561. items.Add(item);
  562. }
  563. itemCond = new ItemCond() { id = $"{itemCondDto.filed}", code = $"ItemCond", pk = "ItemCond", ttl = -1, count = items.Count };
  564. items.ForEach(z =>
  565. {
  566. if (!string.IsNullOrEmpty(z.type))
  567. {
  568. ItemService.CountItemCond(z, null, itemCond);
  569. }
  570. });
  571. await _azureRedis.GetRedisClient(8).HashSetAsync($"ItemCond:ItemCond", $"{itemCondDto.filed}", itemCond.ToJsonString());
  572. }
  573. }
  574. }
  575. catch (CosmosException ex)
  576. {
  577. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ItemCond()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  578. }
  579. catch (Exception ex)
  580. {
  581. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ItemCond()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  582. }
  583. }
  584. //更新產品一覽表
  585. [Function("Product")]
  586. public async Task ProductFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "product", Connection = "Azure:ServiceBus:ConnectionString")] string msg, ILogger log)
  587. {
  588. try
  589. {
  590. var jsonMsg = JsonDocument.Parse(msg);
  591. jsonMsg.RootElement.TryGetProperty("method", out JsonElement method);
  592. jsonMsg.RootElement.TryGetProperty("schoolId", out JsonElement schoolId);
  593. jsonMsg.RootElement.TryGetProperty("prodCode", out JsonElement prodCode);
  594. jsonMsg.RootElement.TryGetProperty("prodId", out JsonElement prodId);
  595. var client = _azureCosmos.GetCosmosClient();
  596. string strQuery = string.Empty;
  597. //取得所有學校產品
  598. ////序號
  599. List<SchoolProductSumData> serialsProductSumOrg = new List<SchoolProductSumData>();
  600. strQuery = $"SELECT * FROM c WHERE c.dataType = 'serial'";
  601. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Product-{schoolId}") }))
  602. {
  603. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  604. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  605. {
  606. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  607. {
  608. SchoolProductSerial serialInfo = obj.ToObject<SchoolProductSerial>();
  609. SchoolProductSumData serialProd = serialsProductSumOrg.Where(sp => sp.prodCode == serialInfo.prodCode).FirstOrDefault();
  610. if (serialProd == null)
  611. {
  612. SchoolProductSumData serialProdAdd = new SchoolProductSumData();
  613. serialProdAdd.prodCode = serialInfo.prodCode;
  614. serialProdAdd.ids.Add(serialInfo.id);
  615. serialProdAdd.avaliable = serialProdAdd.ids.Count;
  616. serialsProductSumOrg.Add(serialProdAdd);
  617. }
  618. else
  619. {
  620. if (!serialProd.ids.Contains(serialInfo.id))
  621. {
  622. serialProd.ids.Add(serialInfo.id);
  623. }
  624. serialProd.avaliable = serialProd.ids.Count;
  625. }
  626. }
  627. }
  628. }
  629. ////服務
  630. List<SchoolProductSumData> servicesProductSumOrg = new List<SchoolProductSumData>();
  631. long timestampToday = DateTimeOffset.UtcNow.AddSeconds(1).ToUnixTimeSeconds(); //比現實時間延遲1秒
  632. strQuery = $"SELECT * FROM c WHERE c.dataType = 'service' AND c.startDate <= {timestampToday} AND {timestampToday} <= c.endDate AND c.ttl < 0"; //在授權期間、ttl < 0 才取
  633. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Product-{schoolId}") }))
  634. {
  635. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  636. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  637. {
  638. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  639. {
  640. SchoolProductService serviceInfo = obj.ToObject<SchoolProductService>();
  641. SchoolProductSumData serviceProd = servicesProductSumOrg.Where(sp => sp.prodCode == serviceInfo.prodCode).FirstOrDefault();
  642. if (serviceProd == null)
  643. {
  644. SchoolProductSumData serviceProdAdd = new SchoolProductSumData();
  645. serviceProdAdd.prodCode = serviceInfo.prodCode;
  646. serviceProdAdd.avaliable = 0;
  647. serviceProdAdd.ids.Add(serviceInfo.id);
  648. serviceProdAdd.avaliable += serviceInfo.number;
  649. servicesProductSumOrg.Add(serviceProdAdd);
  650. }
  651. else
  652. {
  653. if (!serviceProd.ids.Contains(serviceInfo.id))
  654. {
  655. serviceProd.ids.Add(serviceInfo.id);
  656. serviceProd.avaliable += serviceInfo.number;
  657. }
  658. }
  659. }
  660. }
  661. }
  662. ////服務產品特別對應項
  663. School school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{schoolId}", new PartitionKey("Base")); //學校基本資料取得
  664. bool updSchool = false; //是否變更學校基本資料
  665. int chgSchSizeCnt = 0; //變更學校空間的次數 若為0表示現時間點沒有任何空間可使用 => 回復學校空間為初始值
  666. int schoolDefaultSize = 1; //學校空間初始值:1
  667. if (!string.IsNullOrWhiteSpace(school.id))
  668. {
  669. if (servicesProductSumOrg.Count > 0)
  670. {
  671. foreach (SchoolProductSumData servicesProductSumOrgRow in servicesProductSumOrg)
  672. {
  673. //更新學校空間
  674. if (servicesProductSumOrgRow.prodCode.Equals("IPALJ6NY"))
  675. {
  676. school.size = (servicesProductSumOrgRow.avaliable < 1) ? 1 : servicesProductSumOrgRow.avaliable;
  677. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, $"{schoolId}", new PartitionKey("Base"));
  678. updSchool = true;
  679. chgSchSizeCnt++;
  680. }
  681. }
  682. }
  683. if(chgSchSizeCnt.Equals(0) && !school.size.Equals(schoolDefaultSize))
  684. {
  685. school.size = schoolDefaultSize;
  686. //updSchool = true; //關於學校空間初始式樣未定,目前暫定:若需要Reset空間,則先維持原空間數不更動
  687. updSchool = false;
  688. }
  689. }
  690. //變更學校基本資料
  691. if(updSchool)
  692. {
  693. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, $"{schoolId}", new PartitionKey("Base"));
  694. }
  695. ////硬體
  696. List<SchoolProductSumDataHard> hardsProductSumOrg = new List<SchoolProductSumDataHard>();
  697. strQuery = $"SELECT * FROM c WHERE c.dataType = 'hard'";
  698. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Product-{schoolId}") }))
  699. {
  700. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  701. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  702. {
  703. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  704. {
  705. SchoolProductHard hardInfo = obj.ToObject<SchoolProductHard>();
  706. SchoolProductSumData hardProd = hardsProductSumOrg.Where(sp => sp.prodCode == hardInfo.prodCode).FirstOrDefault();
  707. if (hardProd == null)
  708. {
  709. SchoolProductSumDataHard hardProdAdd = new SchoolProductSumDataHard();
  710. hardProdAdd.prodCode = hardInfo.prodCode;
  711. hardProdAdd.model = hardInfo.model;
  712. hardProdAdd.ids.Add(hardInfo.id);
  713. hardProdAdd.avaliable = hardProdAdd.ids.Count;
  714. hardsProductSumOrg.Add(hardProdAdd);
  715. }
  716. else
  717. {
  718. if (!hardProd.ids.Contains(hardInfo.id))
  719. {
  720. hardProd.ids.Add(hardInfo.id);
  721. }
  722. hardProd.avaliable = hardProd.ids.Count;
  723. }
  724. }
  725. }
  726. }
  727. //更新學校產品一覽表
  728. SchoolProductSum prodSum = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolProductSum>(schoolId.ToString(), new PartitionKey($"ProductSum"));
  729. prodSum.serial = serialsProductSumOrg;
  730. prodSum.service = servicesProductSumOrg;
  731. prodSum.hard = hardsProductSumOrg;
  732. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolProductSum>(prodSum, prodSum.id, new PartitionKey($"{prodSum.code}"));
  733. }
  734. catch (CosmosException ex)
  735. {
  736. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Product()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  737. }
  738. catch (Exception ex)
  739. {
  740. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Product()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  741. }
  742. }
  743. /// <summary>
  744. /// 批量复制文件
  745. /// </summary>
  746. /// <param name="msg"></param>
  747. /// <returns></returns>
  748. [Function("CopyStandardFile")]
  749. public async Task BatchCopyBlobFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "copy-standard-file", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  750. {
  751. try
  752. {
  753. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-Blob复制文件-CopyStandardFile\n{msg}", GroupNames.成都开发測試群組);
  754. var jsonMsg = JsonDocument.Parse(msg);
  755. BatchCopyFile bIBatchCopyFile = msg.ToObject<BatchCopyFile>();
  756. //批量复制文件
  757. var result = await BatchCopyFileService.CopyFile(_dingDing, _azureStorage, bIBatchCopyFile);
  758. if (result == 200)
  759. {
  760. //发送消息实体
  761. Notification notification = new Notification
  762. {
  763. hubName = "hita",
  764. type = "msg",
  765. from = $"BI:{_option.Location}:private",
  766. to = bIBatchCopyFile.tmdIds,
  767. label = $"{bIBatchCopyFile.codeKey}_finish",
  768. body = new { location = _option.Location, biz = $"{bIBatchCopyFile.codeKey}", tmdid = $"{bIBatchCopyFile.tmdid}", tmdname = $"{bIBatchCopyFile.tmdName}", status = 1, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString(),
  769. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  770. };
  771. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  772. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  773. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  774. var location = _option.Location;
  775. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //站内发送消息
  776. }
  777. }
  778. catch (Exception ex)
  779. {
  780. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-Blob复制文件-CopyStandardFile\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.成都开发測試群組);
  781. }
  782. }
  783. /// <summary>
  784. /// 更新开课数据事件
  785. /// </summary>
  786. /// <param name="msg"></param>
  787. /// <returns></returns>
  788. [Function("LessonRecordEvent")]
  789. public async Task LessonRecordFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "lesson-record-event", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  790. {
  791. JsonElement data = msg.ToObject<JsonElement>();
  792. string scope = "";
  793. string tmdid = "";
  794. string lessonId;
  795. string school;
  796. string tbname;
  797. string code;
  798. string blobname;
  799. List<LessonUpdate> updates = new List<LessonUpdate>();
  800. //更新课堂记录
  801. if (data.TryGetProperty("lesson_id", out JsonElement _lessonId) && !string.IsNullOrEmpty($"{_lessonId}"))
  802. {
  803. if (!data.TryGetProperty("tmdid", out JsonElement _tmdid)) return;
  804. if (!data.TryGetProperty("scope", out JsonElement _scope)) return;
  805. if (!data.TryGetProperty("grant_types", out JsonElement _grant_types)) return;
  806. data.TryGetProperty("school", out JsonElement _school);
  807. school = $"{_school}";
  808. scope = $"{_scope}";
  809. tmdid = $"{_tmdid}";
  810. lessonId = $"{_lessonId}";
  811. updates = _grant_types.ToObject<List<LessonUpdate>>();
  812. }//创建课堂记录
  813. else if (data.TryGetProperty("id", out JsonElement _id) && !string.IsNullOrEmpty($"{_id}")
  814. && data.TryGetProperty("tmdid", out JsonElement _tmdid) && !string.IsNullOrEmpty($"{_tmdid}")
  815. && data.TryGetProperty("scope", out JsonElement _scope) && !string.IsNullOrEmpty($"{_scope}"))
  816. {
  817. data.TryGetProperty("school", out JsonElement _school);
  818. school = $"{_school}";
  819. scope = $"{_scope}";
  820. tmdid = $"{_tmdid}";
  821. lessonId = $"{_id}";
  822. updates.Add(new LessonUpdate { grant_type = "create" });
  823. }//删除课堂记录
  824. else if (data.TryGetProperty("delete_id", out JsonElement _delete_id) && !string.IsNullOrEmpty($"{_delete_id}")
  825. && data.TryGetProperty("tmdid", out JsonElement _dtmdid) && !string.IsNullOrEmpty($"{_dtmdid}")
  826. && data.TryGetProperty("scope", out JsonElement _dscope) && !string.IsNullOrEmpty($"{_dscope}")
  827. && data.TryGetProperty("opt", out JsonElement _opt) && !string.IsNullOrEmpty($"{_opt}"))
  828. {
  829. data.TryGetProperty("school", out JsonElement _dschool);
  830. school = $"{_dschool}";
  831. if ($"{_opt}".Equals("delete"))
  832. {
  833. scope = $"{_dscope}";
  834. tmdid = $"{_dtmdid}";
  835. lessonId = $"{_delete_id}";
  836. updates.Add(new LessonUpdate { grant_type = "delete" });
  837. }
  838. else { return; }
  839. }
  840. else
  841. {
  842. return;
  843. }
  844. var client = _azureCosmos.GetCosmosClient();
  845. if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
  846. {
  847. blobname = $"{school}";
  848. code = $"LessonRecord-{school}";
  849. tbname = "School";
  850. }
  851. else if ($"{scope}".Equals("private"))
  852. {
  853. blobname = $"{tmdid}";
  854. code = $"LessonRecord-{tmdid}";
  855. tbname = "Teacher";
  856. }
  857. else
  858. {
  859. return;
  860. }
  861. LessonDis lessonDis = new LessonDis();
  862. List<LessonUpdate> msgs = new List<LessonUpdate>();
  863. try
  864. {
  865. LessonRecord oldlessonRecord = null;
  866. LessonRecord lessonRecord = null;
  867. Azure.Response response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
  868. if (response.Status == 200)
  869. {
  870. var doc = JsonDocument.Parse(response.ContentStream);
  871. lessonRecord = doc.RootElement.ToObject<LessonRecord>();
  872. oldlessonRecord = doc.RootElement.ToObject<LessonRecord>();
  873. }
  874. else
  875. {
  876. lessonRecord = null;
  877. }
  878. bool isReplace = true;
  879. if (updates.IsNotEmpty())
  880. {
  881. foreach (LessonUpdate update in updates)
  882. {
  883. switch (update.grant_type)
  884. {
  885. //更新课堂时长
  886. case "up-duration":
  887. var duration = double.Parse($"{update.data}");
  888. lessonRecord.duration = duration;
  889. msgs.Add(update);
  890. try {
  891. BlobDownloadResult Recording = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"records/{_lessonId}/Record/.Recording.json").DownloadContentAsync();
  892. var RecordingJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(Recording.Content.ToString()))).RootElement;
  893. if (RecordingJson.TryGetProperty("duration",out JsonElement _duration) && _duration.ValueKind.Equals(JsonValueKind.Number)) {
  894. var durationFile = double.Parse($"{_duration}");
  895. if (duration < durationFile) {
  896. lessonRecord.duration = durationFile;
  897. }
  898. }
  899. if (RecordingJson.TryGetProperty("streamUrl", out JsonElement _streamUrl) &&!string.IsNullOrWhiteSpace($"{_streamUrl}"))
  900. {
  901. lessonRecord.hasVideo = 1;
  902. }
  903. }
  904. catch (Exception ex ) {
  905. // await _dingDing.SendBotMsg($"{_option.Location}/LessonRecordEvent/课堂记录更新课堂时长出错records/{_lessonId}/Record/.Recording.json\n{ex.Message}{ex.StackTrace}{msg}", GroupNames.成都开发測試群組);
  906. }
  907. isReplace = true;
  908. break;
  909. //更新T分
  910. case "up-tScore":
  911. var tScore = int.Parse($"{update.data}");
  912. lessonRecord.tScore = tScore;
  913. msgs.Add(update);
  914. break;
  915. //更新课P分
  916. case "up-pScore":
  917. var pScore = int.Parse($"{update.data}");
  918. lessonRecord.pScore = pScore;
  919. msgs.Add(update);
  920. break;
  921. //更新 学生人数
  922. case "up-mCount":
  923. var mCount = int.Parse($"{update.data}");
  924. lessonRecord.mCount = mCount;
  925. msgs.Add(update);
  926. break;
  927. //更新 议课次数
  928. case "up-techCount":
  929. var techCount = int.Parse($"{update.data}");
  930. lessonRecord.mCount = techCount;
  931. msgs.Add(update);
  932. break;
  933. //更新 基础统计信息
  934. case "up-base":
  935. try {
  936. BlobDownloadResult baseblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/base.json").DownloadContentAsync();
  937. LessonBase lessonBase = baseblobDownload.Content.ToObjectFromJson<LessonBase>();
  938. if (lessonBase != null) {
  939. lessonRecord.attendCount = lessonRecord.attendCount;
  940. lessonRecord.clientCount = lessonRecord.clientCount;
  941. lessonRecord.attendRate = lessonRecord.attendRate;
  942. lessonRecord.groupCount = lessonRecord.groupCount;
  943. lessonRecord.collateTaskCount = lessonRecord.collateTaskCount;
  944. lessonRecord.collateCount = lessonRecord.collateCount;
  945. lessonRecord.pushCount = lessonRecord.pushCount;
  946. lessonRecord.totalPoint = lessonRecord.totalPoint;
  947. lessonRecord.examQuizCount = lessonRecord.examQuizCount;
  948. lessonRecord.interactionCount = lessonRecord.interactionCount;
  949. lessonRecord.examPointRate = lessonRecord.examPointRate;
  950. lessonRecord.clientInteractionCount = lessonRecord.clientInteractionCount;
  951. lessonRecord.clientInteractionAverge = lessonRecord.clientInteractionAverge;
  952. }
  953. msgs.Add(update);
  954. } catch (Exception ex) {
  955. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}课程读取base.json,{_lessonId}\n{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  956. }
  957. break;
  958. //更新 时间线
  959. case "up-TimeLine":
  960. //BlobDownloadResult TimeLineblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/TimeLine.json").DownloadContentAsync();
  961. //var timeline = TimeLineblobDownload.Content.ToObjectFromJson<List<LessonTimeLine>>();
  962. msgs.Add(update);
  963. break;
  964. //更新 课堂总览信息
  965. case "up-ActivityInfo":
  966. //BlobDownloadResult ActivityInfoblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/ActivityInfo.json").DownloadContentAsync();
  967. //var activityInfos = ActivityInfoblobDownload.Content.ToObjectFromJson<List<LessonActivityInfo>>();
  968. msgs.Add(update);
  969. break;
  970. //case "up-baseinfo":
  971. // if (updates.Count > 1)
  972. // {
  973. // isReplace = true;
  974. // }
  975. // else {
  976. // isReplace = false;
  977. // }
  978. // msgs.Add(update);
  979. // break;
  980. case "delete":
  981. try
  982. {
  983. await client.GetContainer(Constant.TEAMModelOS, tbname).DeleteItemAsync<LessonRecord>(lessonId, new PartitionKey(code));
  984. msgs.Add(update);
  985. }
  986. catch (CosmosException ex)
  987. {
  988. msgs.Add(update);
  989. }
  990. lessonRecord = null;
  991. isReplace = false;
  992. break;
  993. case "create":
  994. oldlessonRecord = null;
  995. //处理课堂选用的课程信息
  996. if (!string.IsNullOrEmpty(lessonRecord.courseId))
  997. {
  998. Course course = null;
  999. try
  1000. {
  1001. var cresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.school}"));
  1002. if (cresponse.Status == 200)
  1003. {
  1004. using var cJson = await JsonDocument.ParseAsync(cresponse.ContentStream);
  1005. course = cJson.ToObject<Course>();
  1006. }
  1007. else
  1008. {
  1009. var sresponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
  1010. if (sresponse.Status == 200)
  1011. {
  1012. using var cJson = await JsonDocument.ParseAsync(sresponse.ContentStream);
  1013. course = cJson.ToObject<Course>();
  1014. }
  1015. else
  1016. {
  1017. course = null;
  1018. }
  1019. }
  1020. }
  1021. catch (Exception ex) {
  1022. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-查询课程-CosmosDB异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  1023. }
  1024. /*catch (CosmosException ex) when (ex.Status != 404)
  1025. {
  1026. try
  1027. {
  1028. course = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Course>(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
  1029. }
  1030. catch (CosmosException e) when (e.Status != 404)
  1031. {
  1032. course = null;
  1033. }
  1034. }*/
  1035. if (course != null)
  1036. {
  1037. lessonRecord.periodId = course.period?.id;
  1038. lessonRecord.subjectId = course.subject?.id;
  1039. }
  1040. }
  1041. //处理课堂选用的名单
  1042. if (lessonRecord.groupIds.IsNotEmpty())
  1043. {
  1044. HashSet<string> grades = new HashSet<string>();
  1045. List<GroupListDto> groups = await GroupListService.GetGroupListListids(client, _dingDing, lessonRecord.groupIds, lessonRecord.school);
  1046. List<GroupListDto> groupLists = groups?.FindAll(x => !string.IsNullOrEmpty(x.periodId) && x.year > 0 && !string.IsNullOrEmpty(x.school));
  1047. if (groupLists.IsNotEmpty() && !string.IsNullOrWhiteSpace(lessonRecord.periodId))
  1048. {
  1049. School schoolObj = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(lessonRecord.school, new PartitionKey("Base"));
  1050. //年级算法
  1051. int? Count = schoolObj.period.Find(x => x.id.Equals(lessonRecord.periodId)).grades?.Count;
  1052. if (Count.HasValue)
  1053. {
  1054. int Month = DateTimeOffset.UtcNow.Month;
  1055. int Year = DateTimeOffset.UtcNow.Year;
  1056. foreach (int year in groupLists.Select(x => x.year))
  1057. {
  1058. int grade;
  1059. if (Month >= 1 && Month <= 6)
  1060. {
  1061. grade = (Year - year + 1) / Count.Value;
  1062. }
  1063. else
  1064. {
  1065. grade = (Year - year) / Count.Value;
  1066. }
  1067. grades.Add($"{grade}");
  1068. }
  1069. }
  1070. }
  1071. lessonRecord.grade.AddRange(grades);
  1072. }
  1073. msgs.Add(update);
  1074. break;
  1075. default:
  1076. break;
  1077. }
  1078. }
  1079. //如果被删除则不能再被更新
  1080. if (isReplace) {
  1081. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(lessonRecord, lessonId, new PartitionKey(code));
  1082. }
  1083. //计算课堂更新前后的差值
  1084. lessonDis = LessonService.DisLessonCount(oldlessonRecord, lessonRecord, lessonDis);
  1085. await LessonService.FixLessonCount(client, _dingDing, lessonRecord, oldlessonRecord, lessonDis);
  1086. }
  1087. }
  1088. catch (CosmosException e)
  1089. {
  1090. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错-CosmosDB异常{e.Message}\n{e.StackTrace}", GroupNames.成都开发測試群組);
  1091. }
  1092. catch (Exception ex)
  1093. {
  1094. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错\n{ex.Message}\n{ex.StackTrace}\n{data}\n{code}\n", GroupNames.成都开发測試群組);
  1095. }
  1096. }
  1097. /// <summary>
  1098. /// 完善课程变更
  1099. /// </summary>
  1100. /// <data msg>
  1101. /// CourseChange
  1102. ///// </data>
  1103. /// <param name="msg"></param>
  1104. /// <returns></returns>
  1105. [Function("Course")]
  1106. public async Task CourseFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "course", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  1107. {
  1108. var client = _azureCosmos.GetCosmosClient();
  1109. try
  1110. {
  1111. //await _dingDing.SendBotMsg($"ServiceBus,CourseChange:{msg}", GroupNames.醍摩豆服務運維群組);
  1112. var jsonMsg = JsonDocument.Parse(msg);
  1113. CourseChange courseChange = msg.ToObject<CourseChange>();
  1114. if (courseChange == null)
  1115. {
  1116. return;
  1117. }
  1118. foreach (var cls in courseChange.addClass)
  1119. {
  1120. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { cls }, courseChange.school);
  1121. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  1122. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  1123. foreach (var stu in addStudentsCls)
  1124. {
  1125. try
  1126. {
  1127. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1128. if (!stuCourse.Value.classId.Contains(cls))
  1129. {
  1130. stuCourse.Value.classId.Add(cls);
  1131. }
  1132. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1133. }
  1134. catch (CosmosException ex)
  1135. {
  1136. if (ex.Response.Status == 404)
  1137. {
  1138. var course = new StuCourse
  1139. {
  1140. id = courseChange.id,
  1141. scode = courseChange.code,
  1142. name = courseChange.name,
  1143. code = $"StuCourse-{courseChange.school}-{stu.id}",
  1144. scope = courseChange.scope,
  1145. school = courseChange.school,
  1146. creatorId = courseChange.creatorId,
  1147. classId = new List<string> { cls },
  1148. pk = "StuCourse",
  1149. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1150. };
  1151. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1152. }
  1153. else
  1154. {
  1155. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1156. }
  1157. }
  1158. }
  1159. foreach (var tmd in addTmdidsCls)
  1160. {
  1161. try
  1162. {
  1163. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1164. if (!stuCourse.Value.classId.Contains(cls))
  1165. {
  1166. stuCourse.Value.classId.Add(cls);
  1167. }
  1168. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1169. }
  1170. catch (CosmosException ex)
  1171. {
  1172. if (ex.Response.Status == 404)
  1173. {
  1174. var course = new StuCourse
  1175. {
  1176. id = courseChange.id,
  1177. scode = courseChange.code,
  1178. name = courseChange.name,
  1179. code = $"StuCourse-{tmd.id}",
  1180. scope = courseChange.scope,
  1181. school = courseChange.school,
  1182. creatorId = courseChange.creatorId,
  1183. classId = new List<string> { cls },
  1184. pk = "StuCourse",
  1185. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1186. };
  1187. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1188. }
  1189. else
  1190. {
  1191. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1192. }
  1193. }
  1194. }
  1195. }
  1196. foreach (var list in courseChange.addList)
  1197. {
  1198. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { list }, courseChange.school);
  1199. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  1200. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  1201. foreach (var stu in addStudentsCls)
  1202. {
  1203. try
  1204. {
  1205. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
  1206. if (!stuCourse.Value.stulist.Contains(list))
  1207. {
  1208. stuCourse.Value.stulist.Add(list);
  1209. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
  1210. }
  1211. }
  1212. catch (CosmosException ex)
  1213. {
  1214. if (ex.Response.Status == 404)
  1215. {
  1216. var course = new StuCourse
  1217. {
  1218. id = courseChange.id,
  1219. scode = courseChange.code,
  1220. name = courseChange.name,
  1221. code = $"StuCourse-{courseChange.school}-{stu.id}",
  1222. scope = courseChange.scope,
  1223. school = courseChange.school,
  1224. creatorId = courseChange.creatorId,
  1225. stulist = new List<string> { list },
  1226. pk = "StuCourse",
  1227. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1228. };
  1229. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1230. }
  1231. else
  1232. {
  1233. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1234. }
  1235. }
  1236. }
  1237. foreach (var tmd in addTmdidsCls)
  1238. {
  1239. try
  1240. {
  1241. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1242. if (!stuCourse.Value.stulist.Contains(list))
  1243. {
  1244. stuCourse.Value.stulist.Add(list);
  1245. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1246. }
  1247. }
  1248. catch (CosmosException ex)
  1249. {
  1250. if (ex.Response.Status == 404)
  1251. {
  1252. var course = new StuCourse
  1253. {
  1254. id = courseChange.id,
  1255. scode = courseChange.code,
  1256. name = courseChange.name,
  1257. code = $"StuCourse-{tmd.id}",
  1258. scope = courseChange.scope,
  1259. school = courseChange.school,
  1260. creatorId = courseChange.creatorId,
  1261. stulist = new List<string> { list },
  1262. pk = "StuCourse",
  1263. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1264. };
  1265. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1266. }
  1267. else
  1268. {
  1269. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1270. }
  1271. }
  1272. }
  1273. }
  1274. foreach (var delCls in courseChange.delClass)
  1275. {
  1276. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { delCls }, courseChange.school);
  1277. var delStudentsCls = tchList.FindAll(x => x.type == 2);
  1278. var delTmdidsCls = tchList.FindAll(x => x.type == 1);
  1279. foreach (var stu in delStudentsCls)
  1280. {
  1281. try
  1282. {
  1283. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1284. if (stuCourse.Value.classId.Contains(delCls))
  1285. {
  1286. stuCourse.Value.classId.Remove(delCls);
  1287. }
  1288. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1289. {
  1290. //当两个列表都不存在时则直接删除
  1291. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1292. }
  1293. else
  1294. {
  1295. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1296. }
  1297. }
  1298. catch (CosmosException ex)
  1299. {
  1300. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1301. }
  1302. }
  1303. foreach (var tmd in delTmdidsCls)
  1304. {
  1305. try
  1306. {
  1307. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1308. if (stuCourse.Value.classId.Contains(delCls))
  1309. {
  1310. stuCourse.Value.classId.Remove(delCls);
  1311. }
  1312. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1313. {
  1314. //当两个列表都不存在时则直接删除
  1315. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1316. }
  1317. else
  1318. {
  1319. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1320. }
  1321. }
  1322. catch (CosmosException ex)
  1323. {
  1324. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1325. }
  1326. }
  1327. }
  1328. foreach (var delList in courseChange.delList)
  1329. {
  1330. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { delList }, courseChange.school);
  1331. var delStudentsCls = tchList.FindAll(x => x.type == 2);
  1332. var delTmdidsCls = tchList.FindAll(x => x.type == 1);
  1333. foreach (var stu in delStudentsCls)
  1334. {
  1335. try
  1336. {
  1337. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1338. if (stuCourse.Value.stulist.Contains(delList))
  1339. {
  1340. stuCourse.Value.stulist.Remove(delList);
  1341. }
  1342. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1343. {
  1344. //当两个列表都不存在时则直接删除
  1345. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1346. }
  1347. else
  1348. {
  1349. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1350. }
  1351. }
  1352. catch (CosmosException ex)
  1353. {
  1354. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1355. }
  1356. }
  1357. foreach (var tmd in delTmdidsCls)
  1358. {
  1359. try
  1360. {
  1361. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1362. if (stuCourse.Value.stulist.Contains(delList))
  1363. {
  1364. stuCourse.Value.stulist.Remove(delList);
  1365. }
  1366. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1367. {
  1368. //当两个列表都不存在时则直接删除
  1369. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1370. }
  1371. else
  1372. {
  1373. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1374. }
  1375. }
  1376. catch (CosmosException ex)
  1377. {
  1378. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1379. }
  1380. }
  1381. }
  1382. }
  1383. catch (Exception ex)
  1384. {
  1385. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -Course\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1386. }
  1387. }
  1388. }
  1389. }