ActiveTaskTopic.cs 84 KB

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