ActiveTaskTopic.cs 79 KB

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