ActiveTaskTopic.cs 81 KB

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