ActiveTaskTopic.cs 81 KB

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