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