ActiveTaskTopic.cs 82 KB

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