ActiveTaskTopic.cs 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  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. //名单变动修改学生研修关联信息
  498. await ActivityService.FixActivity(client, _dingDing, groupChange, "Study");
  499. //名单变动修改学生简易评测关联信息
  500. await ActivityService.FixActivity(client, _dingDing, groupChange, "ExamLite");
  501. //TODO学习活动
  502. //await FixActivity(client, stuListChange, "Learn");
  503. //名单变动修改学生作业活动信息
  504. await ActivityService.FixActivity(client, _dingDing, groupChange, "Homework");
  505. if (groupChange.type == null || !groupChange.type.Equals("research") || !groupChange.type.Equals("yxtrain") || !groupChange.type.Equals("activity"))
  506. {
  507. //课程名单变动修改学生课程关联信息
  508. await ActivityService.FixStuCourse(client, _dingDing, groupChange);
  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. if (servicesProductSumOrg.Count > 0)
  664. {
  665. foreach (SchoolProductSumData servicesProductSumOrgRow in servicesProductSumOrg)
  666. {
  667. //更新學校空間
  668. if (servicesProductSumOrgRow.prodCode.Equals("IPALJ6NY"))
  669. {
  670. School school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{schoolId}", new PartitionKey("Base"));
  671. school.size = (servicesProductSumOrgRow.avaliable < 1) ? 1 : servicesProductSumOrgRow.avaliable;
  672. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, $"{schoolId}", new PartitionKey("Base"));
  673. }
  674. }
  675. }
  676. ////硬體
  677. List<SchoolProductSumDataHard> hardsProductSumOrg = new List<SchoolProductSumDataHard>();
  678. strQuery = $"SELECT * FROM c WHERE c.dataType = 'hard'";
  679. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Product-{schoolId}") }))
  680. {
  681. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  682. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  683. {
  684. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  685. {
  686. SchoolProductHard hardInfo = obj.ToObject<SchoolProductHard>();
  687. SchoolProductSumData hardProd = hardsProductSumOrg.Where(sp => sp.prodCode == hardInfo.prodCode).FirstOrDefault();
  688. if (hardProd == null)
  689. {
  690. SchoolProductSumDataHard hardProdAdd = new SchoolProductSumDataHard();
  691. hardProdAdd.prodCode = hardInfo.prodCode;
  692. hardProdAdd.model = hardInfo.model;
  693. hardProdAdd.ids.Add(hardInfo.id);
  694. hardProdAdd.avaliable = hardProdAdd.ids.Count;
  695. hardsProductSumOrg.Add(hardProdAdd);
  696. }
  697. else
  698. {
  699. if (!hardProd.ids.Contains(hardInfo.id))
  700. {
  701. hardProd.ids.Add(hardInfo.id);
  702. }
  703. hardProd.avaliable = hardProd.ids.Count;
  704. }
  705. }
  706. }
  707. }
  708. //更新學校產品一覽表
  709. SchoolProductSum prodSum = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolProductSum>(schoolId.ToString(), new PartitionKey($"ProductSum"));
  710. prodSum.serial = serialsProductSumOrg;
  711. prodSum.service = servicesProductSumOrg;
  712. prodSum.hard = hardsProductSumOrg;
  713. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolProductSum>(prodSum, prodSum.id, new PartitionKey($"{prodSum.code}"));
  714. }
  715. catch (CosmosException ex)
  716. {
  717. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Product()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  718. }
  719. catch (Exception ex)
  720. {
  721. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Product()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  722. }
  723. }
  724. /// <summary>
  725. /// 批量复制文件
  726. /// </summary>
  727. /// <param name="msg"></param>
  728. /// <returns></returns>
  729. [Function("CopyStandardFile")]
  730. public async Task BatchCopyBlobFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "copy-standard-file", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  731. {
  732. try
  733. {
  734. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-Blob复制文件-CopyStandardFile\n{msg}", GroupNames.成都开发測試群組);
  735. var jsonMsg = JsonDocument.Parse(msg);
  736. BatchCopyFile bIBatchCopyFile = msg.ToObject<BatchCopyFile>();
  737. //批量复制文件
  738. var result = await BatchCopyFileService.CopyFile(_dingDing, _azureStorage, bIBatchCopyFile);
  739. if (result == 200)
  740. {
  741. //发送消息实体
  742. Notification notification = new Notification
  743. {
  744. hubName = "hita",
  745. type = "msg",
  746. from = $"BI:{_option.Location}:private",
  747. to = bIBatchCopyFile.tmdIds,
  748. label = $"{bIBatchCopyFile.codeKey}_finish",
  749. body = new { location = _option.Location, biz = $"{bIBatchCopyFile.codeKey}", tmdid = $"{bIBatchCopyFile.tmdid}", tmdname = $"{bIBatchCopyFile.tmdName}", status = 1, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString(),
  750. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  751. };
  752. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  753. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  754. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  755. var location = _option.Location;
  756. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //站内发送消息
  757. }
  758. }
  759. catch (Exception ex)
  760. {
  761. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-Blob复制文件-CopyStandardFile\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.成都开发測試群組);
  762. }
  763. }
  764. /// <summary>
  765. /// 更新开课数据事件
  766. /// </summary>
  767. /// <param name="msg"></param>
  768. /// <returns></returns>
  769. [Function("LessonRecordEvent")]
  770. public async Task LessonRecordFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "lesson-record-event", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  771. {
  772. JsonElement data = msg.ToObject<JsonElement>();
  773. string scope = "";
  774. string tmdid = "";
  775. string lessonId;
  776. string school;
  777. string tbname;
  778. string code;
  779. string blobname;
  780. List<LessonUpdate> updates = new List<LessonUpdate>();
  781. //更新课堂记录
  782. if (data.TryGetProperty("lesson_id", out JsonElement _lessonId) && !string.IsNullOrEmpty($"{_lessonId}"))
  783. {
  784. if (!data.TryGetProperty("tmdid", out JsonElement _tmdid)) return;
  785. if (!data.TryGetProperty("scope", out JsonElement _scope)) return;
  786. if (!data.TryGetProperty("grant_types", out JsonElement _grant_types)) return;
  787. data.TryGetProperty("school", out JsonElement _school);
  788. school = $"{_school}";
  789. scope = $"{_scope}";
  790. tmdid = $"{_tmdid}";
  791. lessonId = $"{_lessonId}";
  792. updates = _grant_types.ToObject<List<LessonUpdate>>();
  793. }//创建课堂记录
  794. else if (data.TryGetProperty("id", out JsonElement _id) && !string.IsNullOrEmpty($"{_id}")
  795. && data.TryGetProperty("tmdid", out JsonElement _tmdid) && !string.IsNullOrEmpty($"{_tmdid}")
  796. && data.TryGetProperty("scope", out JsonElement _scope) && !string.IsNullOrEmpty($"{_scope}"))
  797. {
  798. data.TryGetProperty("school", out JsonElement _school);
  799. school = $"{_school}";
  800. scope = $"{_scope}";
  801. tmdid = $"{_tmdid}";
  802. lessonId = $"{_id}";
  803. updates.Add(new LessonUpdate { grant_type = "create" });
  804. }//删除课堂记录
  805. else if (data.TryGetProperty("delete_id", out JsonElement _delete_id) && !string.IsNullOrEmpty($"{_delete_id}")
  806. && data.TryGetProperty("tmdid", out JsonElement _dtmdid) && !string.IsNullOrEmpty($"{_dtmdid}")
  807. && data.TryGetProperty("scope", out JsonElement _dscope) && !string.IsNullOrEmpty($"{_dscope}")
  808. && data.TryGetProperty("opt", out JsonElement _opt) && !string.IsNullOrEmpty($"{_opt}"))
  809. {
  810. data.TryGetProperty("school", out JsonElement _dschool);
  811. school = $"{_dschool}";
  812. if ($"{_opt}".Equals("delete"))
  813. {
  814. scope = $"{_dscope}";
  815. tmdid = $"{_dtmdid}";
  816. lessonId = $"{_delete_id}";
  817. updates.Add(new LessonUpdate { grant_type = "delete" });
  818. }
  819. else { return; }
  820. }
  821. else
  822. {
  823. return;
  824. }
  825. var client = _azureCosmos.GetCosmosClient();
  826. if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
  827. {
  828. blobname = $"{school}";
  829. code = $"LessonRecord-{school}";
  830. tbname = "School";
  831. }
  832. else if ($"{scope}".Equals("private"))
  833. {
  834. blobname = $"{tmdid}";
  835. code = $"LessonRecord-{tmdid}";
  836. tbname = "Teacher";
  837. }
  838. else
  839. {
  840. return;
  841. }
  842. LessonDis lessonDis = new LessonDis();
  843. List<LessonUpdate> msgs = new List<LessonUpdate>();
  844. try
  845. {
  846. LessonRecord oldlessonRecord = null;
  847. LessonRecord lessonRecord = null;
  848. Azure.Response response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
  849. if (response.Status == 200)
  850. {
  851. var doc = JsonDocument.Parse(response.ContentStream);
  852. lessonRecord = doc.RootElement.ToObject<LessonRecord>();
  853. oldlessonRecord = doc.RootElement.ToObject<LessonRecord>();
  854. }
  855. else
  856. {
  857. lessonRecord = null;
  858. }
  859. bool isReplace = true;
  860. if (updates.IsNotEmpty())
  861. {
  862. foreach (LessonUpdate update in updates)
  863. {
  864. switch (update.grant_type)
  865. {
  866. //更新课堂时长
  867. case "up-duration":
  868. var duration = double.Parse($"{update.data}");
  869. lessonRecord.duration = duration;
  870. msgs.Add(update);
  871. try {
  872. BlobDownloadResult Recording = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"records/{_lessonId}/Record/.Recording.json").DownloadContentAsync();
  873. var RecordingJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(Recording.Content.ToString()))).RootElement;
  874. if (RecordingJson.TryGetProperty("duration",out JsonElement _duration) && _duration.ValueKind.Equals(JsonValueKind.Number)) {
  875. var durationFile = double.Parse($"{_duration}");
  876. if (duration < durationFile) {
  877. lessonRecord.duration = durationFile;
  878. }
  879. }
  880. if (RecordingJson.TryGetProperty("streamUrl", out JsonElement _streamUrl) &&!string.IsNullOrWhiteSpace($"{_streamUrl}"))
  881. {
  882. lessonRecord.hasVideo = 1;
  883. }
  884. }
  885. catch (Exception ex ) {
  886. // await _dingDing.SendBotMsg($"{_option.Location}/LessonRecordEvent/课堂记录更新课堂时长出错records/{_lessonId}/Record/.Recording.json\n{ex.Message}{ex.StackTrace}{msg}", GroupNames.成都开发測試群組);
  887. }
  888. isReplace = true;
  889. break;
  890. //更新T分
  891. case "up-tScore":
  892. var tScore = int.Parse($"{update.data}");
  893. lessonRecord.tScore = tScore;
  894. msgs.Add(update);
  895. break;
  896. //更新课P分
  897. case "up-pScore":
  898. var pScore = int.Parse($"{update.data}");
  899. lessonRecord.pScore = pScore;
  900. msgs.Add(update);
  901. break;
  902. //更新 学生人数
  903. case "up-mCount":
  904. var mCount = int.Parse($"{update.data}");
  905. lessonRecord.mCount = mCount;
  906. msgs.Add(update);
  907. break;
  908. //更新 议课次数
  909. case "up-techCount":
  910. var techCount = int.Parse($"{update.data}");
  911. lessonRecord.mCount = techCount;
  912. msgs.Add(update);
  913. break;
  914. //更新 时间线
  915. case "up-TimeLine":
  916. //BlobDownloadResult TimeLineblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/TimeLine.json").DownloadContentAsync();
  917. //var timeline = TimeLineblobDownload.Content.ToObjectFromJson<List<LessonTimeLine>>();
  918. msgs.Add(update);
  919. break;
  920. //更新 课堂总览信息
  921. case "up-ActivityInfo":
  922. //BlobDownloadResult ActivityInfoblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/ActivityInfo.json").DownloadContentAsync();
  923. //var activityInfos = ActivityInfoblobDownload.Content.ToObjectFromJson<List<LessonActivityInfo>>();
  924. msgs.Add(update);
  925. break;
  926. case "up-baseinfo":
  927. if (updates.Count > 1)
  928. {
  929. isReplace = true;
  930. }
  931. else {
  932. isReplace = false;
  933. }
  934. msgs.Add(update);
  935. break;
  936. case "delete":
  937. try
  938. {
  939. await client.GetContainer(Constant.TEAMModelOS, tbname).DeleteItemAsync<LessonRecord>(lessonId, new PartitionKey(code));
  940. msgs.Add(update);
  941. }
  942. catch (CosmosException ex)
  943. {
  944. msgs.Add(update);
  945. }
  946. lessonRecord = null;
  947. isReplace = false;
  948. break;
  949. case "create":
  950. oldlessonRecord = null;
  951. //处理课堂选用的课程信息
  952. if (!string.IsNullOrEmpty(lessonRecord.courseId))
  953. {
  954. Course course = null;
  955. try
  956. {
  957. var cresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.school}"));
  958. if (cresponse.Status == 200)
  959. {
  960. using var cJson = await JsonDocument.ParseAsync(cresponse.ContentStream);
  961. course = cJson.ToObject<Course>();
  962. }
  963. else
  964. {
  965. var sresponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
  966. if (sresponse.Status == 200)
  967. {
  968. using var cJson = await JsonDocument.ParseAsync(sresponse.ContentStream);
  969. course = cJson.ToObject<Course>();
  970. }
  971. else
  972. {
  973. course = null;
  974. }
  975. }
  976. }
  977. catch (Exception ex) {
  978. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-查询课程-CosmosDB异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  979. }
  980. /*catch (CosmosException ex) when (ex.Status != 404)
  981. {
  982. try
  983. {
  984. course = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Course>(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
  985. }
  986. catch (CosmosException e) when (e.Status != 404)
  987. {
  988. course = null;
  989. }
  990. }*/
  991. if (course != null)
  992. {
  993. lessonRecord.periodId = course.period?.id;
  994. lessonRecord.subjectId = course.subject?.id;
  995. }
  996. }
  997. //处理课堂选用的名单
  998. if (lessonRecord.groupIds.IsNotEmpty())
  999. {
  1000. HashSet<string> grades = new HashSet<string>();
  1001. List<GroupListDto> groups = await GroupListService.GetGroupListListids(client, _dingDing, lessonRecord.groupIds, lessonRecord.school);
  1002. List<GroupListDto> groupLists = groups?.FindAll(x => !string.IsNullOrEmpty(x.periodId) && x.year > 0 && !string.IsNullOrEmpty(x.school));
  1003. if (groupLists.IsNotEmpty() && !string.IsNullOrEmpty(lessonRecord.periodId))
  1004. {
  1005. School schoolObj = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(lessonRecord.school, new PartitionKey("Base"));
  1006. //年级算法
  1007. int? Count = schoolObj.period.Find(x => x.id.Equals(lessonRecord.periodId)).grades?.Count;
  1008. if (Count.HasValue)
  1009. {
  1010. int Month = DateTimeOffset.UtcNow.Month;
  1011. int Year = DateTimeOffset.UtcNow.Year;
  1012. foreach (int year in groupLists.Select(x => x.year))
  1013. {
  1014. int grade;
  1015. if (Month >= 1 && Month <= 6)
  1016. {
  1017. grade = (Year - year + 1) / Count.Value;
  1018. }
  1019. else
  1020. {
  1021. grade = (Year - year) / Count.Value;
  1022. }
  1023. grades.Add($"{grade}");
  1024. }
  1025. }
  1026. }
  1027. lessonRecord.grade.AddRange(grades);
  1028. }
  1029. msgs.Add(update);
  1030. break;
  1031. default:
  1032. break;
  1033. }
  1034. }
  1035. //如果被删除则不能再被更新
  1036. if (isReplace) {
  1037. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(lessonRecord, lessonId, new PartitionKey(code));
  1038. }
  1039. //计算课堂更新前后的差值
  1040. lessonDis = LessonService.DisLessonCount(oldlessonRecord, lessonRecord, lessonDis);
  1041. await LessonService.FixLessonCount(client, _dingDing, lessonRecord, oldlessonRecord, lessonDis);
  1042. }
  1043. }
  1044. catch (CosmosException e)
  1045. {
  1046. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错-CosmosDB异常{e.Message}\n{e.StackTrace}", GroupNames.成都开发測試群組);
  1047. }
  1048. catch (Exception ex)
  1049. {
  1050. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错\n{ex.Message}\n{ex.StackTrace}\n{data}\n{code}\n", GroupNames.成都开发測試群組);
  1051. }
  1052. }
  1053. /// <summary>
  1054. /// 完善课程变更
  1055. /// </summary>
  1056. /// <data msg>
  1057. /// CourseChange
  1058. ///// </data>
  1059. /// <param name="msg"></param>
  1060. /// <returns></returns>
  1061. [Function("Course")]
  1062. public async Task CourseFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "course", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  1063. {
  1064. var client = _azureCosmos.GetCosmosClient();
  1065. try
  1066. {
  1067. //await _dingDing.SendBotMsg($"ServiceBus,CourseChange:{msg}", GroupNames.醍摩豆服務運維群組);
  1068. var jsonMsg = JsonDocument.Parse(msg);
  1069. CourseChange courseChange = msg.ToObject<CourseChange>();
  1070. if (courseChange == null)
  1071. {
  1072. return;
  1073. }
  1074. foreach (var cls in courseChange.addClass)
  1075. {
  1076. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { cls }, courseChange.school);
  1077. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  1078. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  1079. foreach (var stu in addStudentsCls)
  1080. {
  1081. try
  1082. {
  1083. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1084. if (!stuCourse.Value.classId.Contains(cls))
  1085. {
  1086. stuCourse.Value.classId.Add(cls);
  1087. }
  1088. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1089. }
  1090. catch (CosmosException ex)
  1091. {
  1092. if (ex.Response.Status == 404)
  1093. {
  1094. var course = new StuCourse
  1095. {
  1096. id = courseChange.id,
  1097. scode = courseChange.code,
  1098. name = courseChange.name,
  1099. code = $"StuCourse-{courseChange.school}-{stu.id}",
  1100. scope = courseChange.scope,
  1101. school = courseChange.school,
  1102. creatorId = courseChange.creatorId,
  1103. classId = new List<string> { cls },
  1104. pk = "StuCourse",
  1105. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1106. };
  1107. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1108. }
  1109. else
  1110. {
  1111. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1112. }
  1113. }
  1114. }
  1115. foreach (var tmd in addTmdidsCls)
  1116. {
  1117. try
  1118. {
  1119. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1120. if (!stuCourse.Value.classId.Contains(cls))
  1121. {
  1122. stuCourse.Value.classId.Add(cls);
  1123. }
  1124. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1125. }
  1126. catch (CosmosException ex)
  1127. {
  1128. if (ex.Response.Status == 404)
  1129. {
  1130. var course = new StuCourse
  1131. {
  1132. id = courseChange.id,
  1133. scode = courseChange.code,
  1134. name = courseChange.name,
  1135. code = $"StuCourse-{tmd.id}",
  1136. scope = courseChange.scope,
  1137. school = courseChange.school,
  1138. creatorId = courseChange.creatorId,
  1139. classId = new List<string> { cls },
  1140. pk = "StuCourse",
  1141. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1142. };
  1143. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1144. }
  1145. else
  1146. {
  1147. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1148. }
  1149. }
  1150. }
  1151. }
  1152. foreach (var list in courseChange.addList)
  1153. {
  1154. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { list }, courseChange.school);
  1155. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  1156. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  1157. foreach (var stu in addStudentsCls)
  1158. {
  1159. try
  1160. {
  1161. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
  1162. if (!stuCourse.Value.stulist.Contains(list))
  1163. {
  1164. stuCourse.Value.stulist.Add(list);
  1165. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
  1166. }
  1167. }
  1168. catch (CosmosException ex)
  1169. {
  1170. if (ex.Response.Status == 404)
  1171. {
  1172. var course = new StuCourse
  1173. {
  1174. id = courseChange.id,
  1175. scode = courseChange.code,
  1176. name = courseChange.name,
  1177. code = $"StuCourse-{courseChange.school}-{stu.id}",
  1178. scope = courseChange.scope,
  1179. school = courseChange.school,
  1180. creatorId = courseChange.creatorId,
  1181. stulist = new List<string> { list },
  1182. pk = "StuCourse",
  1183. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1184. };
  1185. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1186. }
  1187. else
  1188. {
  1189. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1190. }
  1191. }
  1192. }
  1193. foreach (var tmd in addTmdidsCls)
  1194. {
  1195. try
  1196. {
  1197. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1198. if (!stuCourse.Value.stulist.Contains(list))
  1199. {
  1200. stuCourse.Value.stulist.Add(list);
  1201. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1202. }
  1203. }
  1204. catch (CosmosException ex)
  1205. {
  1206. if (ex.Response.Status == 404)
  1207. {
  1208. var course = new StuCourse
  1209. {
  1210. id = courseChange.id,
  1211. scode = courseChange.code,
  1212. name = courseChange.name,
  1213. code = $"StuCourse-{tmd.id}",
  1214. scope = courseChange.scope,
  1215. school = courseChange.school,
  1216. creatorId = courseChange.creatorId,
  1217. stulist = new List<string> { list },
  1218. pk = "StuCourse",
  1219. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1220. };
  1221. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1222. }
  1223. else
  1224. {
  1225. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1226. }
  1227. }
  1228. }
  1229. }
  1230. foreach (var delCls in courseChange.delClass)
  1231. {
  1232. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { delCls }, courseChange.school);
  1233. var delStudentsCls = tchList.FindAll(x => x.type == 2);
  1234. var delTmdidsCls = tchList.FindAll(x => x.type == 1);
  1235. foreach (var stu in delStudentsCls)
  1236. {
  1237. try
  1238. {
  1239. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1240. if (stuCourse.Value.classId.Contains(delCls))
  1241. {
  1242. stuCourse.Value.classId.Remove(delCls);
  1243. }
  1244. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1245. {
  1246. //当两个列表都不存在时则直接删除
  1247. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1248. }
  1249. else
  1250. {
  1251. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1252. }
  1253. }
  1254. catch (CosmosException ex)
  1255. {
  1256. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1257. }
  1258. }
  1259. foreach (var tmd in delTmdidsCls)
  1260. {
  1261. try
  1262. {
  1263. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1264. if (stuCourse.Value.classId.Contains(delCls))
  1265. {
  1266. stuCourse.Value.classId.Remove(delCls);
  1267. }
  1268. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1269. {
  1270. //当两个列表都不存在时则直接删除
  1271. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1272. }
  1273. else
  1274. {
  1275. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1276. }
  1277. }
  1278. catch (CosmosException ex)
  1279. {
  1280. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1281. }
  1282. }
  1283. }
  1284. foreach (var delList in courseChange.delList)
  1285. {
  1286. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { delList }, courseChange.school);
  1287. var delStudentsCls = tchList.FindAll(x => x.type == 2);
  1288. var delTmdidsCls = tchList.FindAll(x => x.type == 1);
  1289. foreach (var stu in delStudentsCls)
  1290. {
  1291. try
  1292. {
  1293. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1294. if (stuCourse.Value.stulist.Contains(delList))
  1295. {
  1296. stuCourse.Value.stulist.Remove(delList);
  1297. }
  1298. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1299. {
  1300. //当两个列表都不存在时则直接删除
  1301. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1302. }
  1303. else
  1304. {
  1305. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1306. }
  1307. }
  1308. catch (CosmosException ex)
  1309. {
  1310. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1311. }
  1312. }
  1313. foreach (var tmd in delTmdidsCls)
  1314. {
  1315. try
  1316. {
  1317. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1318. if (stuCourse.Value.stulist.Contains(delList))
  1319. {
  1320. stuCourse.Value.stulist.Remove(delList);
  1321. }
  1322. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1323. {
  1324. //当两个列表都不存在时则直接删除
  1325. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1326. }
  1327. else
  1328. {
  1329. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1330. }
  1331. }
  1332. catch (CosmosException ex)
  1333. {
  1334. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1335. }
  1336. }
  1337. }
  1338. }
  1339. catch (Exception ex)
  1340. {
  1341. await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -Course\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  1342. }
  1343. }
  1344. }
  1345. }