ActiveTaskTopic.cs 84 KB

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