ActiveTaskTopic.cs 122 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994
  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. using static TEAMModelOS.SDK.Models.Service.LessonService;
  29. using DinkToPdf.Contracts;
  30. using TEAMModelOS.SDK.Helper.Common.DateTimeHelper;
  31. namespace TEAMModelOS.FunctionV4.ServiceBus
  32. {
  33. public class ActiveTaskTopic
  34. {
  35. private readonly AzureCosmosFactory _azureCosmos;
  36. private readonly DingDing _dingDing;
  37. private readonly AzureStorageFactory _azureStorage;
  38. private readonly AzureRedisFactory _azureRedis;
  39. private readonly AzureServiceBusFactory _serviceBus;
  40. private readonly Option _option;
  41. private readonly NotificationService _notificationService;
  42. private readonly CoreAPIHttpService _coreAPIHttpService;
  43. private readonly IConfiguration _configuration;
  44. private readonly IConverter _converter;
  45. public ActiveTaskTopic(IConverter converter, CoreAPIHttpService coreAPIHttpService, AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, AzureServiceBusFactory serviceBus, IOptionsSnapshot<Option> option, NotificationService notificationService, IConfiguration configuration)
  46. {
  47. _azureCosmos = azureCosmos;
  48. _dingDing = dingDing;
  49. _azureStorage = azureStorage;
  50. _azureRedis = azureRedis;
  51. _serviceBus = serviceBus;
  52. _option = option?.Value;
  53. _notificationService = notificationService;
  54. _configuration = configuration;
  55. _coreAPIHttpService = coreAPIHttpService;
  56. _converter = converter;
  57. }
  58. [Function("Exam")]
  59. public async Task ExamFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "exam", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  60. {
  61. try
  62. {
  63. var json = JsonDocument.Parse(msg);
  64. json.RootElement.TryGetProperty("id", out JsonElement id);
  65. json.RootElement.TryGetProperty("progress", out JsonElement progress);
  66. json.RootElement.TryGetProperty("code", out JsonElement code);
  67. //Dictionary<string, object> keyValuePairs = mySbMsg.ToObject<Dictionary<string, object>>();
  68. var client = _azureCosmos.GetCosmosClient();
  69. ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{code}"));
  70. exam.progress = progress.ToString();
  71. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"{code}"));
  72. }
  73. catch (CosmosException e)
  74. {
  75. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamBus()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.Status}\n{msg}", GroupNames.醍摩豆服務運維群組);
  76. }
  77. catch (Exception ex)
  78. {
  79. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamBus()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  80. }
  81. }
  82. [Function("Vote")]
  83. public async Task VoteFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "vote", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  84. {
  85. try
  86. {
  87. var jsonMsg = JsonDocument.Parse(msg);
  88. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  89. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  90. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  91. var client = _azureCosmos.GetCosmosClient();
  92. Vote vote = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Vote>(id.ToString(), new PartitionKey($"{code}"));
  93. vote.progress = progress.ToString();
  94. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(vote, id.ToString(), new PartitionKey($"{code}"));
  95. }
  96. catch (CosmosException e)
  97. {
  98. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,VoteBus()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.Status}\n{msg}", GroupNames.醍摩豆服務運維群組);
  99. }
  100. catch (Exception ex)
  101. {
  102. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,VoteBus()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  103. }
  104. }
  105. [Function("Correct")]
  106. public async Task CorrectFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "correct", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  107. {
  108. try
  109. {
  110. var jsonMsg = JsonDocument.Parse(msg);
  111. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  112. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  113. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  114. var client = _azureCosmos.GetCosmosClient();
  115. Correct correct = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Correct>(id.ToString(), new PartitionKey($"{code}"));
  116. correct.progress = progress.ToString();
  117. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(correct, id.ToString(), new PartitionKey($"{code}"));
  118. }
  119. catch (CosmosException e)
  120. {
  121. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Correct()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.Status}\n{msg}", GroupNames.醍摩豆服務運維群組);
  122. }
  123. catch (Exception ex)
  124. {
  125. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Correct()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  126. }
  127. }
  128. [Function("Survey")]
  129. public async Task SurveyFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "survey", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  130. {
  131. try
  132. {
  133. var jsonMsg = JsonDocument.Parse(msg);
  134. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  135. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  136. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  137. //Dictionary<string, object> keyValuePairs = mySbMsg.ToObject<Dictionary<string, object>>();
  138. var client = _azureCosmos.GetCosmosClient();
  139. Survey survey = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Survey>(id.ToString(), new PartitionKey($"{code}"));
  140. survey.progress = progress.ToString();
  141. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(survey, id.ToString(), new PartitionKey($"{code}"));
  142. }
  143. catch (CosmosException e)
  144. {
  145. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,SurveyBus()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.Status}\n{msg}", GroupNames.醍摩豆服務運維群組);
  146. }
  147. catch (Exception ex)
  148. {
  149. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,SurveyBus()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  150. }
  151. }
  152. [Function("Homework")]
  153. public async Task HomeworkFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "homework", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  154. {
  155. try
  156. {
  157. var jsonMsg = JsonDocument.Parse(msg);
  158. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  159. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  160. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  161. var client = _azureCosmos.GetCosmosClient();
  162. Homework homework = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Homework>(id.ToString(), new PartitionKey($"{code}"));
  163. homework.progress = progress.ToString();
  164. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(homework, id.ToString(), new PartitionKey($"{code}"));
  165. }
  166. catch (CosmosException e)
  167. {
  168. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Homework()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.Status}\n{msg}", GroupNames.醍摩豆服務運維群組);
  169. }
  170. catch (Exception ex)
  171. {
  172. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Homework()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  173. }
  174. }
  175. [Function("Study")]
  176. public async Task StudyFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "study", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  177. {
  178. string activityId = string.Empty;
  179. try
  180. {
  181. var jsonMsg = JsonDocument.Parse(msg);
  182. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  183. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  184. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  185. var client = _azureCosmos.GetCosmosClient();
  186. Study study = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Study>(id.ToString(), new PartitionKey($"{code}"));
  187. study.progress = progress.ToString();
  188. activityId = id.ToString();
  189. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(study, id.ToString(), new PartitionKey($"{code}"));
  190. }
  191. catch (CosmosException e)
  192. {
  193. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Study()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.Status}\n{msg}", GroupNames.醍摩豆服務運維群組);
  194. }
  195. catch (Exception ex)
  196. {
  197. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Study()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  198. }
  199. }
  200. [Function("ExamLite")]
  201. public async Task ExamLiteFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "examlite", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  202. {
  203. try
  204. {
  205. var jsonMsg = JsonDocument.Parse(msg);
  206. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  207. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  208. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  209. var client = _azureCosmos.GetCosmosClient();
  210. ExamLite lite = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamLite>(id.ToString(), new PartitionKey($"{code}"));
  211. lite.progress = progress.ToString();
  212. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(lite, id.ToString(), new PartitionKey($"{code}"));
  213. }
  214. catch (CosmosException e)
  215. {
  216. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamLite()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.Status}\n{msg}", GroupNames.醍摩豆服務運維群組);
  217. }
  218. catch (Exception ex)
  219. {
  220. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamLite()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  221. }
  222. }
  223. /// <summary>
  224. /// 根据容器的根目录刷新redis并获取redis的最新使用情况
  225. /// </summary>
  226. /// <param name="msg"></param>
  227. /// <returns></returns>
  228. [Function("BlobRoot")]
  229. public async Task BlobRootFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "blobroot", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  230. {
  231. try
  232. {
  233. var jsonMsg = JsonDocument.Parse(msg);
  234. if (jsonMsg.RootElement.TryGetProperty("name", out JsonElement _name) && _name.ValueKind == JsonValueKind.String
  235. && jsonMsg.RootElement.TryGetProperty("root", out JsonElement root) && root.ValueKind == JsonValueKind.String)
  236. {
  237. List<Dictionary<string, double?>> list = new List<Dictionary<string, double?>>();
  238. string[] uls = System.Web.HttpUtility.UrlDecode($"{root}", Encoding.UTF8).Split("/");
  239. string u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
  240. string name = $"{_name}";
  241. string lockKey = $"Blob:Lock:{name}:{u}";
  242. bool exist = await _azureRedis.GetRedisClient(8).KeyExistsAsync(lockKey);
  243. if (!exist)
  244. { ///key不存在则正常进行计算
  245. bool condition = false;
  246. TimeSpan timeSpan = new TimeSpan(DateTimeOffset.UtcNow.AddMinutes(5).Ticks);
  247. timeSpan = timeSpan - new TimeSpan(DateTimeOffset.UtcNow.Ticks);
  248. //准备处理Blob刷新时间
  249. long action = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  250. await _azureRedis.GetRedisClient(8).StringSetAsync(lockKey, action, expiry: timeSpan);
  251. await RefreshBlob(name, u);
  252. //将action 与Redis最新的时间进行比较,如果
  253. var rds = await CheckLockKey(lockKey, action);
  254. condition = rds.condition;
  255. exist = rds.exist;
  256. if (condition || !exist)
  257. {
  258. await RefreshBlob(name, u);
  259. }
  260. //使用 CancellationToken
  261. //while (condition || !exist)
  262. //{
  263. //}
  264. }
  265. else
  266. {
  267. ///key存在则,则刷新key对应的值
  268. TimeSpan timeSpan = new TimeSpan(DateTimeOffset.UtcNow.AddMinutes(5).Ticks);
  269. timeSpan = timeSpan - new TimeSpan(DateTimeOffset.UtcNow.Ticks);
  270. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  271. await _azureRedis.GetRedisClient(8).StringSetAsync(lockKey, now, expiry: timeSpan);
  272. }
  273. }
  274. }
  275. catch (Exception ex)
  276. {
  277. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  278. }
  279. }
  280. private async Task<(bool condition, bool exist)> CheckLockKey(string lockKey, long nowTime)
  281. {
  282. //Redis的最新时间
  283. long newestTime = 0;
  284. RedisValue value = await _azureRedis.GetRedisClient(8).StringGetAsync(lockKey);
  285. if (value != default && !value.IsNullOrEmpty)
  286. {
  287. JsonElement record = value.ToString().ToObject<JsonElement>();
  288. if (record.TryGetInt64(out newestTime))
  289. {
  290. }
  291. }
  292. //说明key已经不存在
  293. if (newestTime == 0)
  294. {
  295. return (false, true);
  296. }
  297. //说明key存在
  298. else
  299. {
  300. //说明Redis记录了最新的时间戳
  301. if (nowTime != newestTime)
  302. {
  303. return (true, false);
  304. }
  305. //时间相同,没有被再次记录最新的时间戳
  306. else
  307. {
  308. await _azureRedis.GetRedisClient(8).KeyDeleteAsync(lockKey);
  309. return (false, true);
  310. }
  311. }
  312. }
  313. private async Task RefreshBlob(string name, string u)
  314. {
  315. long statr = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  316. var client = _azureStorage.GetBlobContainerClient(name);
  317. var size = await client.GetBlobsSize(u);
  318. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", u);
  319. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", u, size.HasValue ? size.Value : 0);
  320. var scores = await _azureRedis.GetRedisClient(8).SortedSetRangeByRankWithScoresAsync($"Blob:Catalog:{name}");
  321. double blobsize = 0;
  322. if (scores != default && scores != null)
  323. {
  324. foreach (var score in scores)
  325. {
  326. blobsize = blobsize + score.Score;
  327. }
  328. }
  329. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", new RedisValue(name), new RedisValue($"{blobsize}"));
  330. long end = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  331. long dis = (end - statr) / 1000;
  332. long timeout = 60 * 5;
  333. if (dis > timeout)
  334. {
  335. await _dingDing.SendBotMsg($"ServiceBus,RefreshBlob:空间计算已经超过{timeout}秒\n容器名:{name}\n文件夹:{u}\n计算时长:{dis}", GroupNames.醍摩豆服務運維群組);
  336. }
  337. }
  338. /// <param name="msg"></param>
  339. /// <returns></returns>
  340. [Function("TeacherTrainChange")]
  341. public async Task TeacherTrainChangeFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "teacher-train-change", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  342. {
  343. }
  344. /// <param name="msg"></param>
  345. /// <returns></returns>
  346. //[Function("TeacherTrainChange")]
  347. public async Task TeacherTrainChangeFuncBak([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "teacher-train-change", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  348. {
  349. try
  350. {
  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. setting = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<AreaSetting>(change.school, new PartitionKey("AreaSetting"));
  411. }
  412. catch (CosmosException)
  413. {
  414. try
  415. {
  416. setting = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<AreaSetting>(area.id, new PartitionKey("AreaSetting"));
  417. }
  418. catch (CosmosException)
  419. {
  420. setting = null;
  421. }
  422. }
  423. }
  424. if (setting == null)
  425. {
  426. setting = new AreaSetting
  427. {
  428. allTime = 50,
  429. classTime = 5,
  430. submitTime = 15,
  431. onlineTime = 20,
  432. offlineTime = 10,
  433. lessonMinutes = 45,
  434. };
  435. }
  436. List<Task<TeacherTrain>> task = new List<Task<TeacherTrain>>();
  437. teacherTrains.ForEach(x =>
  438. {
  439. x.update.UnionWith(change.update);
  440. task.Add(StatisticsService.StatisticsTeacher(x, setting, area, client, null));
  441. });
  442. await task.TaskPage(1);
  443. var unchange = change.tmdids.Except(teacherTrains.Select(x => x.id));
  444. if (unchange != null)
  445. {
  446. task.Clear();
  447. unchange.ToList().ForEach(x =>
  448. {
  449. task.Add(StatisticsService.StatisticsTeacher(new TeacherTrain
  450. {
  451. pk = "TeacherTrain",
  452. id = x,
  453. code = $"TeacherTrain-{change.school}",
  454. tmdid = x,
  455. school = change.school,
  456. update = new HashSet<string> { StatisticsService.TeacherAbility,
  457. StatisticsService.TeacherClass, StatisticsService.OfflineRecord }
  458. }, setting, area, client, null));
  459. });
  460. await task.TaskPage(1);
  461. }
  462. }
  463. }
  464. catch (CosmosException ex)
  465. {
  466. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-研修数据变更,重新统计-TeacherTrainChange\n{msg}\n{ex.Message}\n{ex.StackTrace}\nCosmosException{ex.Status}", GroupNames.醍摩豆服務運維群組);
  467. }
  468. catch (Exception ex)
  469. {
  470. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-研修数据变更,重新统计-TeacherTrainChange\n{msg}\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  471. }
  472. }
  473. /// <summary>
  474. /// 完善课程变更,StuListChange, originCode是学校编码 则表示名单是学校自定义名单,如果是tmdid则表示醍摩豆的私有名单,scope=school,private。
  475. /// </summary>
  476. /// <data msg>
  477. /// CourseChange
  478. ///// </data>
  479. /// <param name="msg"></param>
  480. /// <returns></returns>
  481. [Function("GroupChange")]
  482. public async Task GroupChangeFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "group-change", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  483. {
  484. var client = _azureCosmos.GetCosmosClient();
  485. try
  486. {
  487. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-名单成员变更-GroupChange\n{msg}", GroupNames.醍摩豆服務運維群組);
  488. var jsonMsg = JsonDocument.Parse(msg);
  489. GroupChange groupChange = msg.ToObject<GroupChange>();
  490. //名单变动修改学生课程关联信息
  491. //await StuListService.FixStuCourse(client, stuListChange);
  492. //Vote投票 Survey问卷 Exam评测 Learn学习活动 Homework作业活动
  493. //名单变动修改学生问卷关联信息
  494. await ActivityService.FixActivity(client, _dingDing, groupChange, "Survey");
  495. //名单变动修改学生投票关联信息
  496. await ActivityService.FixActivity(client, _dingDing, groupChange, "Vote");
  497. //名单变动修改学生评测关联信息
  498. await ActivityService.FixActivity(client, _dingDing, groupChange, "Exam");
  499. //名单变动修改学生研修关联信息
  500. await ActivityService.FixActivity(client, _dingDing, groupChange, "Study");
  501. //名单变动修改学生简易评测关联信息
  502. await ActivityService.FixActivity(client, _dingDing, groupChange, "ExamLite");
  503. //名单变动修改学生作业活动信息
  504. await ActivityService.FixActivity(client, _dingDing, groupChange, "Homework");
  505. //TODO学习活动
  506. //await FixActivity(client, stuListChange, "Learn");
  507. if (groupChange.type == null || !groupChange.type.Equals("research") || !groupChange.type.Equals("yxtrain") || !groupChange.type.Equals("activity"))
  508. {
  509. //课程名单变动修改学生课程关联信息
  510. await ActivityService.FixStuCourse(client, _dingDing, groupChange);
  511. //名单变动修改课例关联信息
  512. //await ActivityService.FixLessonRecord(client, _dingDing, groupChange);
  513. }
  514. }
  515. catch (Exception ex)
  516. {
  517. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-GroupChange-GroupChange\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  518. }
  519. }
  520. [Function("ItemCond")]
  521. public async Task ItemCondFunc([ServiceBusTrigger("%Azure:ServiceBus:ItemCondQueue%", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  522. {
  523. try
  524. {
  525. var client = _azureCosmos.GetCosmosClient();
  526. var jsonMsg = JsonDocument.Parse(msg);
  527. List<ItemCondDto> itemCondDtos = msg.ToObject<List<ItemCondDto>>();
  528. foreach (var itemCondDto in itemCondDtos)
  529. {
  530. if (itemCondDto.scope.Equals("school"))
  531. {
  532. ItemCond itemCond = null;
  533. List<ItemInfo> items = new List<ItemInfo>();
  534. 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 ";
  535. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{itemCondDto.key}") }))
  536. {
  537. items.Add(item);
  538. }
  539. itemCond = new ItemCond()
  540. {
  541. id = $"{itemCondDto.filed}",
  542. code = $"ItemCond-{itemCondDto.key}",
  543. pk = "ItemCond",
  544. ttl = -1,
  545. count = items.Count,
  546. grades = new List<GradeCount>(),
  547. subjects = new List<SubjectItemCount>()
  548. };
  549. items.ForEach(z =>
  550. {
  551. if (!string.IsNullOrEmpty(z.type))
  552. {
  553. ItemService.CountItemCond(z, null, itemCond);
  554. }
  555. });
  556. await _azureRedis.GetRedisClient(8).HashSetAsync($"ItemCond:{itemCondDto.key}", $"{itemCondDto.filed}", itemCond.ToJsonString());
  557. }
  558. else
  559. {
  560. ItemCond itemCond = null;
  561. List<ItemInfo> items = new List<ItemInfo>();
  562. var queryslt = $"SELECT c.gradeIds,c.subjectId,c.periodId,c.type,c.level,c.field ,c.scope FROM c where c.pid= null ";
  563. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{itemCondDto.filed}") }))
  564. {
  565. items.Add(item);
  566. }
  567. itemCond = new ItemCond() { id = $"{itemCondDto.filed}", code = $"ItemCond", pk = "ItemCond", ttl = -1, count = items.Count };
  568. items.ForEach(z =>
  569. {
  570. if (!string.IsNullOrEmpty(z.type))
  571. {
  572. ItemService.CountItemCond(z, null, itemCond);
  573. }
  574. });
  575. await _azureRedis.GetRedisClient(8).HashSetAsync($"ItemCond:ItemCond", $"{itemCondDto.filed}", itemCond.ToJsonString());
  576. }
  577. }
  578. }
  579. catch (CosmosException ex)
  580. {
  581. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ItemCond()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  582. }
  583. catch (Exception ex)
  584. {
  585. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ItemCond()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  586. }
  587. }
  588. [Function("GenPdf")]
  589. public async Task GenPdfFunc([ServiceBusTrigger("%Azure:ServiceBus:GenPdfQueue%", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  590. {
  591. try
  592. {
  593. var client = _azureCosmos.GetCosmosClient();
  594. /* var jsonMsg = JsonDocument.Parse(msg);
  595. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  596. //jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);*/
  597. List<Study> studies = new();
  598. JsonElement element = msg.ToObject<JsonElement>();
  599. element.TryGetProperty("id", out JsonElement ids);
  600. List<string> tIds = ids.ToObject<List<string>>();
  601. element.TryGetProperty("school", out JsonElement code);
  602. string sname = string.Empty;
  603. var scquery = $"SELECT c.name from c where c.id = '{code}'";
  604. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: scquery, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  605. {
  606. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  607. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  608. {
  609. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  610. while (accounts.MoveNext())
  611. {
  612. JsonElement account = accounts.Current;
  613. sname = account.GetProperty("name").ToString();
  614. }
  615. }
  616. }
  617. foreach (string id in tIds)
  618. {
  619. List<(List<string> tch, List<Dictionary<string, List<string>>> groupLists)> tchInfo = new();
  620. var query = $"SELECT top 1 c.tchLists,c.groupLists FROM c where array_contains(c.teacIds, '{id}') order by c.createTime desc";
  621. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Study-{code}") }))
  622. {
  623. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  624. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  625. {
  626. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  627. while (accounts.MoveNext())
  628. {
  629. JsonElement account = accounts.Current;
  630. List<string> tchId = new();
  631. List<Dictionary<string, List<string>>> groupLists = new();
  632. if (account.TryGetProperty("tchLists", out JsonElement tchLists))
  633. {
  634. tchId = tchLists.ToObject<List<string>>();
  635. };
  636. if (account.TryGetProperty("groupLists", out JsonElement group))
  637. {
  638. groupLists = group.ToObject<List<Dictionary<string, List<string>>>>();
  639. };
  640. tchInfo.Add((tchId, groupLists));
  641. }
  642. }
  643. }
  644. string cname = string.Empty;
  645. string gname = string.Empty;
  646. foreach (var (tch, groupLists) in tchInfo)
  647. {
  648. List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
  649. if (groupLists.Count > 0)
  650. {
  651. var group = groupLists;
  652. foreach (var gp in group)
  653. {
  654. foreach (KeyValuePair<string, List<string>> pp in gp)
  655. {
  656. ps.Add((pp.Key, pp.Value));
  657. }
  658. }
  659. }
  660. (List<RMember> tchList, List<RGroupList> classInfos) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, tch, code.GetString(), ps);
  661. gname = tchList.Where(c => c.id == id).FirstOrDefault().groupName;
  662. cname = tchList.Where(c => c.id == id).FirstOrDefault().name;
  663. }
  664. var queryInfo = $"select c.id,c.name,c.type,c.hour,c.startTime,c.endTime,c.presenter,c.topic,c.settings,c.desc from c where (c.status<>404 or IS_DEFINED(c.status) = false and array_contains(c.teacIds, '{id}') )";
  665. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<Study>(queryText: queryInfo, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Study-{code}") }))
  666. {
  667. studies.Add(item);
  668. }
  669. List<string> details = new();
  670. StringBuilder stringBuilder = new StringBuilder();
  671. foreach (Study study in studies)
  672. {
  673. var start = DateTimeHelper.FromUnixTimestamp(study.startTime).ToString("yyyy/MM/dd HH:mm:ss");
  674. var end = DateTimeHelper.FromUnixTimestamp(study.endTime).ToString("yyyy/MM/dd HH:mm:ss");
  675. string tname = string.Empty;
  676. List<string> setName = new();
  677. foreach (string setting in study.settings)
  678. {
  679. if (setting.Equals("sign"))
  680. {
  681. setName.Add("扫码签到");
  682. }
  683. else if (setting.Equals("hw"))
  684. {
  685. setName.Add("作业提交");
  686. }
  687. else if (setting.Equals("survey"))
  688. {
  689. setName.Add("问卷反馈");
  690. }
  691. else if (setting.Equals("exam"))
  692. {
  693. setName.Add("评测活动");
  694. }
  695. }
  696. switch (study.type)
  697. {
  698. case 1:
  699. tname = "信息化教学案例展示与分享";
  700. break;
  701. case 2:
  702. tname = "专家专题培训";
  703. break;
  704. case 3:
  705. tname = "同课同构";
  706. break;
  707. case 4:
  708. tname = "同课异构";
  709. break;
  710. case 5:
  711. tname = "校本2.0培训";
  712. break;
  713. case 6:
  714. tname = "自定义活动";
  715. break;
  716. };
  717. stringBuilder.Append($@"<tr>
  718. <td> {study.topic} </td>
  719. <td> {tname} </td >
  720. <td> {study.hour} </td >
  721. <td> 1 </td >
  722. <td> {start} 到 {end} </td>
  723. <td>{study.desc}</td>
  724. <td> {string.Join("、", setName.Select(x => $"{x}\n"))} </td>
  725. <td> 已完成 </td >
  726. </tr> ");
  727. }
  728. string blob = await StudyService.GenPdf(cname, sname, gname, stringBuilder.ToString(), _converter);
  729. }
  730. /*var query = $"select c.id,c.name,c.type,c.hour,c.startTime,c.endTime,c.presenter,c.topic from c where (c.status<>404 or IS_DEFINED(c.status) = false and array_contains(c.teacIds, '{id}') )";
  731. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<Study>(queryText: query, requestOptions: new QueryRequestOptions() {PartitionKey = new PartitionKey($"Study-{code}") }))
  732. {
  733. studies.Add(item);
  734. }*/
  735. //(List<StuActivity> datas, string continuationToken) = await ActivityStudentService.FindActivity(element, null, null, _azureCosmos, _azureRedis);
  736. // string blob = await StudyService.GenPdf(cname,sname,gname,"", _converter);
  737. }
  738. catch (CosmosException ex)
  739. {
  740. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,GenPdfFunc()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  741. }
  742. catch (Exception ex)
  743. {
  744. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,GenPdfFunc()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  745. }
  746. }
  747. //更新學校產品一覽表
  748. //處理內容:取得所有序號購買紀錄,服務週期、硬體購買紀錄後,更新ProductSum
  749. [Function("Product")]
  750. public async Task ProductFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "product", Connection = "Azure:ServiceBus:ConnectionString")] string msg, ILogger log)
  751. {
  752. try
  753. {
  754. var jsonMsg = JsonDocument.Parse(msg);
  755. jsonMsg.RootElement.TryGetProperty("method", out JsonElement method);
  756. jsonMsg.RootElement.TryGetProperty("schoolId", out JsonElement schoolId);
  757. jsonMsg.RootElement.TryGetProperty("prodCode", out JsonElement prodCode);
  758. jsonMsg.RootElement.TryGetProperty("prodId", out JsonElement prodId);
  759. var client = _azureCosmos.GetCosmosClient();
  760. string strQuery = string.Empty;
  761. //取得所有學校產品
  762. ////序號
  763. List<SchoolProductSumData> serialsProductSumOrg = new List<SchoolProductSumData>();
  764. strQuery = $"SELECT * FROM c WHERE c.dataType = 'serial'";
  765. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Product-{schoolId}") }))
  766. {
  767. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  768. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  769. {
  770. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  771. {
  772. SchoolProductSerial serialInfo = obj.ToObject<SchoolProductSerial>();
  773. SchoolProductSumData serialProd = serialsProductSumOrg.Where(sp => sp.prodCode == serialInfo.prodCode).FirstOrDefault();
  774. if (serialProd == null)
  775. {
  776. SchoolProductSumData serialProdAdd = new SchoolProductSumData();
  777. serialProdAdd.prodCode = serialInfo.prodCode;
  778. serialProdAdd.ids.Add(serialInfo.id);
  779. serialProdAdd.avaliable = serialProdAdd.ids.Count;
  780. serialsProductSumOrg.Add(serialProdAdd);
  781. }
  782. else
  783. {
  784. if (!serialProd.ids.Contains(serialInfo.id))
  785. {
  786. serialProd.ids.Add(serialInfo.id);
  787. }
  788. serialProd.avaliable = serialProd.ids.Count;
  789. }
  790. }
  791. }
  792. }
  793. ////服務
  794. List<SchoolProductSumDataService> servicesProductSumOrg = new List<SchoolProductSumDataService>();
  795. //////取得學校產品 授權週期:授權中 條件: startDate <= now <= endDate
  796. long timestampToday = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
  797. string strQueryM = $"SELECT * FROM c WHERE c.dataType = 'servicePeriod' AND c.startDate <= {timestampToday} AND {timestampToday} <= c.endDate AND c.ttl < 0";
  798. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQueryM, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Product-{schoolId}") }))
  799. {
  800. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  801. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  802. {
  803. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  804. {
  805. SchoolProductServicePeriod servicePeriodInfo = obj.ToObject<SchoolProductServicePeriod>();
  806. SchoolProductSumDataService serviceProd = servicesProductSumOrg.Where(sp => sp.prodCode == servicePeriodInfo.prodCode).FirstOrDefault();
  807. if (serviceProd == null)
  808. {
  809. SchoolProductSumDataService serviceProdAdd = new SchoolProductSumDataService();
  810. serviceProdAdd.prodCode = servicePeriodInfo.prodCode;
  811. serviceProdAdd.avaliable = 0;
  812. serviceProdAdd.ids.Add(servicePeriodInfo.id);
  813. serviceProdAdd.avaliable += servicePeriodInfo.number;
  814. serviceProdAdd.startDate = servicePeriodInfo.startDate;
  815. serviceProdAdd.endDate = servicePeriodInfo.endDate;
  816. servicesProductSumOrg.Add(serviceProdAdd);
  817. }
  818. else
  819. {
  820. serviceProd.ids = new List<string>();
  821. serviceProd.ids.Add(servicePeriodInfo.id);
  822. serviceProd.startDate = servicePeriodInfo.startDate;
  823. serviceProd.endDate = servicePeriodInfo.endDate;
  824. }
  825. }
  826. }
  827. }
  828. ////服務產品特別對應項
  829. School school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{schoolId}", new PartitionKey("Base")); //學校基本資料取得
  830. bool updSchool = false; //是否變更學校基本資料
  831. int chgSchSizeCnt = 0; //變更學校空間的次數 若為0表示現時間點沒有任何空間可使用 => 回復學校空間為初始值
  832. int schoolDefaultSize = 1; //學校空間初始值:1
  833. if (!string.IsNullOrWhiteSpace(school.id))
  834. {
  835. if (servicesProductSumOrg.Count > 0)
  836. {
  837. foreach (SchoolProductSumDataService servicesProductSumOrgRow in servicesProductSumOrg)
  838. {
  839. //更新學校空間
  840. if (servicesProductSumOrgRow.prodCode.Equals("IPALJ6NY"))
  841. {
  842. school.size = (servicesProductSumOrgRow.avaliable < 1) ? 1 : servicesProductSumOrgRow.avaliable;
  843. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, $"{schoolId}", new PartitionKey("Base"));
  844. updSchool = true;
  845. chgSchSizeCnt++;
  846. }
  847. }
  848. }
  849. if (chgSchSizeCnt.Equals(0) && !school.size.Equals(schoolDefaultSize))
  850. {
  851. school.size = schoolDefaultSize;
  852. //updSchool = true; //關於學校空間初始式樣未定,目前暫定:若需要Reset空間,則先維持原空間數不更動
  853. updSchool = false;
  854. }
  855. }
  856. //變更學校基本資料
  857. if (updSchool)
  858. {
  859. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, $"{schoolId}", new PartitionKey("Base"));
  860. }
  861. ////硬體
  862. List<SchoolProductSumDataHard> hardsProductSumOrg = new List<SchoolProductSumDataHard>();
  863. strQuery = $"SELECT * FROM c WHERE c.dataType = 'hard'";
  864. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Product-{schoolId}") }))
  865. {
  866. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  867. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  868. {
  869. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  870. {
  871. SchoolProductHard hardInfo = obj.ToObject<SchoolProductHard>();
  872. SchoolProductSumData hardProd = hardsProductSumOrg.Where(sp => sp.prodCode == hardInfo.prodCode).FirstOrDefault();
  873. if (hardProd == null)
  874. {
  875. SchoolProductSumDataHard hardProdAdd = new SchoolProductSumDataHard();
  876. hardProdAdd.prodCode = hardInfo.prodCode;
  877. hardProdAdd.model = hardInfo.model;
  878. hardProdAdd.ids.Add(hardInfo.id);
  879. hardProdAdd.avaliable = hardProdAdd.ids.Count;
  880. hardsProductSumOrg.Add(hardProdAdd);
  881. }
  882. else
  883. {
  884. if (!hardProd.ids.Contains(hardInfo.id))
  885. {
  886. hardProd.ids.Add(hardInfo.id);
  887. }
  888. hardProd.avaliable = hardProd.ids.Count;
  889. }
  890. }
  891. }
  892. }
  893. //更新學校產品一覽表
  894. SchoolProductSum prodSum = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolProductSum>(schoolId.ToString(), new PartitionKey($"ProductSum"));
  895. prodSum.serial = serialsProductSumOrg;
  896. prodSum.service = servicesProductSumOrg;
  897. prodSum.hard = hardsProductSumOrg;
  898. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolProductSum>(prodSum, prodSum.id, new PartitionKey($"{prodSum.code}"));
  899. }
  900. catch (CosmosException ex)
  901. {
  902. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Product()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  903. }
  904. catch (Exception ex)
  905. {
  906. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Product()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  907. }
  908. }
  909. /// <summary>
  910. /// 批量复制文件
  911. /// </summary>
  912. /// <param name="msg"></param>
  913. /// <returns></returns>
  914. [Function("CopyStandardFile")]
  915. public async Task BatchCopyBlobFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "copy-standard-file", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  916. {
  917. try
  918. {
  919. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-Blob复制文件-CopyStandardFile\n{msg}", GroupNames.醍摩豆服務運維群組);
  920. var jsonMsg = JsonDocument.Parse(msg);
  921. BatchCopyFile bIBatchCopyFile = msg.ToObject<BatchCopyFile>();
  922. //批量复制文件
  923. var result = await BatchCopyFileService.CopyFile(_dingDing, _azureStorage, bIBatchCopyFile);
  924. if (result == 200)
  925. {
  926. //发送消息实体
  927. Notification notification = new Notification
  928. {
  929. hubName = "hita",
  930. type = "msg",
  931. from = $"BI:{_option.Location}:private",
  932. to = bIBatchCopyFile.tmdIds,
  933. label = $"{bIBatchCopyFile.codeKey}_finish",
  934. body = new { location = $"{Environment.GetEnvironmentVariable("Option:Location")}", biz = $"{bIBatchCopyFile.codeKey}", tmdid = $"{bIBatchCopyFile.tmdid}", tmdname = $"{bIBatchCopyFile.tmdName}", status = 1, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString(),
  935. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  936. };
  937. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  938. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  939. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  940. var location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
  941. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //站内发送消息
  942. }
  943. }
  944. catch (Exception ex)
  945. {
  946. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-Blob复制文件-CopyStandardFile\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  947. }
  948. }
  949. /// <summary>
  950. /// 更新开课数据事件
  951. /// </summary>
  952. /// <param name="msg"></param>
  953. /// <returns></returns>
  954. [Function("LessonRecordEvent")]
  955. public async Task LessonRecordFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "lesson-record-event", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  956. {
  957. JsonElement data = msg.ToObject<JsonElement>();
  958. string scope = "";
  959. string tmdid = "";
  960. string lessonId;
  961. string school;
  962. string tbname;
  963. string code;
  964. string blobname;
  965. List<LessonUpdate> updates = new List<LessonUpdate>();
  966. //更新课堂记录
  967. if (data.TryGetProperty("lesson_id", out JsonElement _lessonId) && !string.IsNullOrEmpty($"{_lessonId}"))
  968. {
  969. if (!data.TryGetProperty("tmdid", out JsonElement _tmdid)) return;
  970. if (!data.TryGetProperty("scope", out JsonElement _scope)) return;
  971. if (!data.TryGetProperty("grant_types", out JsonElement _grant_types)) return;
  972. data.TryGetProperty("school", out JsonElement _school);
  973. school = $"{_school}";
  974. scope = $"{_scope}";
  975. tmdid = $"{_tmdid}";
  976. lessonId = $"{_lessonId}";
  977. updates = _grant_types.ToObject<List<LessonUpdate>>();
  978. }//创建课堂记录
  979. else if (data.TryGetProperty("id", out JsonElement _id) && !string.IsNullOrEmpty($"{_id}")
  980. && data.TryGetProperty("tmdid", out JsonElement _tmdid) && !string.IsNullOrEmpty($"{_tmdid}")
  981. && data.TryGetProperty("scope", out JsonElement _scope) && !string.IsNullOrEmpty($"{_scope}"))
  982. {
  983. data.TryGetProperty("school", out JsonElement _school);
  984. school = $"{_school}";
  985. scope = $"{_scope}";
  986. tmdid = $"{_tmdid}";
  987. lessonId = $"{_id}";
  988. updates.Add(new LessonUpdate { grant_type = "create" });
  989. }//删除课堂记录
  990. else if (data.TryGetProperty("delete_id", out JsonElement _delete_id) && !string.IsNullOrEmpty($"{_delete_id}")
  991. && data.TryGetProperty("tmdid", out JsonElement _dtmdid) && !string.IsNullOrEmpty($"{_dtmdid}")
  992. && data.TryGetProperty("scope", out JsonElement _dscope) && !string.IsNullOrEmpty($"{_dscope}")
  993. && data.TryGetProperty("opt", out JsonElement _opt) && !string.IsNullOrEmpty($"{_opt}"))
  994. {
  995. data.TryGetProperty("school", out JsonElement _dschool);
  996. school = $"{_dschool}";
  997. if ($"{_opt}".Equals("delete"))
  998. {
  999. scope = $"{_dscope}";
  1000. tmdid = $"{_dtmdid}";
  1001. lessonId = $"{_delete_id}";
  1002. updates.Add(new LessonUpdate { grant_type = "delete" });
  1003. }
  1004. else { return; }
  1005. }
  1006. else
  1007. {
  1008. return;
  1009. }
  1010. var client = _azureCosmos.GetCosmosClient();
  1011. if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
  1012. {
  1013. blobname = $"{school}";
  1014. code = $"LessonRecord-{school}";
  1015. tbname = "School";
  1016. }
  1017. else if ($"{scope}".Equals("private"))
  1018. {
  1019. blobname = $"{tmdid}";
  1020. code = $"LessonRecord";
  1021. tbname = "Teacher";
  1022. }
  1023. else
  1024. {
  1025. return;
  1026. }
  1027. LessonDis lessonDis = new LessonDis();
  1028. List<LessonUpdate> msgs = new List<LessonUpdate>();
  1029. try
  1030. {
  1031. LessonRecord oldlessonRecord = null;
  1032. LessonRecord lessonRecord = null;
  1033. Azure.Response response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
  1034. if (response.Status == 200)
  1035. {
  1036. var doc = JsonDocument.Parse(response.ContentStream);
  1037. lessonRecord = doc.RootElement.ToObject<LessonRecord>();
  1038. oldlessonRecord = doc.RootElement.ToObject<LessonRecord>();
  1039. }
  1040. else
  1041. {
  1042. lessonRecord = null;
  1043. }
  1044. bool isReplace = true;
  1045. if (updates.IsNotEmpty())
  1046. {
  1047. Teacher teacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>(tmdid, new PartitionKey("Base"));
  1048. foreach (LessonUpdate update in updates)
  1049. {
  1050. switch (update.grant_type)
  1051. {
  1052. //更新课堂时长
  1053. case "up-duration":
  1054. var duration = double.Parse($"{update.data}");
  1055. lessonRecord.duration = duration;
  1056. msgs.Add(update);
  1057. try
  1058. {
  1059. BlobDownloadResult Recording = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"records/{_lessonId}/Record/.Recording.json").DownloadContentAsync();
  1060. var RecordingJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(Recording.Content.ToString()))).RootElement;
  1061. if (RecordingJson.TryGetProperty("duration", out JsonElement _duration) && _duration.ValueKind.Equals(JsonValueKind.Number))
  1062. {
  1063. var durationFile = double.Parse($"{_duration}");
  1064. if (duration < durationFile)
  1065. {
  1066. lessonRecord.duration = durationFile;
  1067. }
  1068. }
  1069. if (RecordingJson.TryGetProperty("streamUrl", out JsonElement _streamUrl) && !string.IsNullOrWhiteSpace($"{_streamUrl}"))
  1070. {
  1071. lessonRecord.hasVideo = 1;
  1072. }
  1073. }
  1074. catch (Exception ex)
  1075. {
  1076. // await _dingDing.SendBotMsg($"{_option.Location}/LessonRecordEvent/课堂记录更新课堂时长出错records/{_lessonId}/Record/.Recording.json\n{ex.Message}\n{ex.StackTrace}{msg}", GroupNames.醍摩豆服務運維群組);
  1077. }
  1078. isReplace = true;
  1079. break;
  1080. //更新T分
  1081. case "up-tScore":
  1082. var tScore = int.Parse($"{update.data}");
  1083. lessonRecord.tScore = tScore;
  1084. msgs.Add(update);
  1085. break;
  1086. //更新课P分
  1087. case "up-pScore":
  1088. var pScore = int.Parse($"{update.data}");
  1089. lessonRecord.pScore = pScore;
  1090. msgs.Add(update);
  1091. break;
  1092. //更新 学生人数
  1093. case "up-mCount":
  1094. var mCount = int.Parse($"{update.data}");
  1095. lessonRecord.mCount = mCount;
  1096. msgs.Add(update);
  1097. break;
  1098. //更新 议课次数
  1099. case "up-techCount":
  1100. var techCount = int.Parse($"{update.data}");
  1101. lessonRecord.mCount = techCount;
  1102. msgs.Add(update);
  1103. break;
  1104. //更新 基础统计信息
  1105. case "up-base":
  1106. //如果有更新 则去读取/{_lessonId}/IES/base.json
  1107. try
  1108. {
  1109. // await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} 收到更新", GroupNames.醍摩豆服務運維群組);
  1110. BlobDownloadResult baseblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/base.json").DownloadContentAsync();
  1111. LessonBase lessonBase = baseblobDownload.Content.ToObjectFromJson<LessonBase>();
  1112. if (lessonBase != null && lessonBase.summary != null)
  1113. {
  1114. //lessonRecord.name = lessonBase.summary.activityName;
  1115. lessonRecord.attendCount = lessonBase.summary.attendCount;
  1116. lessonRecord.clientCount = lessonBase.summary.clientCount;
  1117. lessonRecord.attendRate = lessonBase.summary.attendRate;
  1118. lessonRecord.groupCount = lessonBase.summary.groupCount;
  1119. lessonRecord.collateTaskCount = lessonBase.summary.collateTaskCount;
  1120. lessonRecord.collateCount = lessonBase.summary.collateCount;
  1121. lessonRecord.pushCount = lessonBase.summary.pushCount;
  1122. lessonRecord.totalPoint = lessonBase.summary.totalPoint;
  1123. lessonRecord.examQuizCount = lessonBase.summary.examQuizCount;
  1124. lessonRecord.interactionCount = lessonBase.summary.interactionCount;
  1125. lessonRecord.examPointRate = lessonBase.summary.examPointRate;
  1126. lessonRecord.clientInteractionCount = lessonBase.summary.clientInteractionCount;
  1127. lessonRecord.clientInteractionAverge = lessonBase.summary.clientInteractionAverge;
  1128. lessonRecord.examCount = lessonBase.summary.examCount;
  1129. lessonRecord.totalInteractPoint = lessonBase.summary.totalInteractPoint;
  1130. if (!string.IsNullOrWhiteSpace(lessonRecord.school)) {
  1131. lessonBase.student.ForEach(x => {
  1132. if (string.IsNullOrWhiteSpace(x.school))
  1133. {
  1134. x.school = lessonRecord.school;
  1135. }
  1136. });
  1137. }
  1138. //LessonStudentRecord lessonStudentRecord = new LessonStudentRecord
  1139. //{
  1140. // clientSummaryList = lessonBase.report.clientSummaryList,
  1141. // students = lessonBase.student,
  1142. // name = lessonRecord.name,
  1143. // school = lessonRecord.school,
  1144. // id = lessonRecord.id,
  1145. // scope = lessonRecord.scope,
  1146. // tmdid = lessonRecord.tmdid,
  1147. // code = "LessonStudentRecord",
  1148. // pk = "LessonStudentRecord",
  1149. // courseId =lessonRecord.courseId,
  1150. // groupIds= lessonRecord.groupIds,
  1151. // periodId = lessonRecord.periodId,
  1152. // subjectId = lessonRecord.subjectId,
  1153. //};
  1154. //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS,Constant.Student).UpsertItemAsync<LessonStudentRecord>(lessonStudentRecord, new PartitionKey("LessonStudentRecord"));
  1155. }
  1156. //有上传 base.josn.
  1157. lessonRecord.upload = 1;
  1158. // await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} 更新完成", GroupNames.醍摩豆服務運維群組);
  1159. LessonService.DoAutoDeleteSchoolLessonRecord(lessonRecord, scope, client, school, tmdid, teacher, _notificationService, _serviceBus, _azureStorage, _configuration);
  1160. long? size = await _azureStorage.GetBlobContainerClient(blobname).GetBlobsSize($"records/{_lessonId}");
  1161. Bloblog bloblog = new Bloblog
  1162. {
  1163. id = lessonRecord.id,
  1164. code = $"Bloblog-{blobname}",
  1165. name = lessonRecord.name,
  1166. pk = "Bloblog",
  1167. time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  1168. type = "records",
  1169. url = $"records/{_lessonId}",
  1170. subjectId = string.IsNullOrWhiteSpace(lessonRecord.subjectId) ? new List<string>() : new List<string> { lessonRecord.subjectId },
  1171. periodId = string.IsNullOrWhiteSpace(lessonRecord.periodId) ? new List<string>() : new List<string> { lessonRecord.periodId },
  1172. size = size.HasValue ? size.Value : 0,
  1173. };
  1174. await client.GetContainer(Constant.TEAMModelOS, tbname).UpsertItemAsync(bloblog);
  1175. var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = "records", name = $"{blobname}" }.ToJsonString()); ;
  1176. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  1177. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  1178. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
  1179. //await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} blob刷新完成!", GroupNames.醍摩豆服務運維群組);
  1180. msgs.Add(update);
  1181. }
  1182. catch (Exception ex)
  1183. {
  1184. // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}课程读取base.json,{_lessonId}\n{ex.Message}\n{ex.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1185. }
  1186. break;
  1187. //更新 时间线
  1188. case "up-TimeLine":
  1189. //BlobDownloadResult TimeLineblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/TimeLine.json").DownloadContentAsync();
  1190. //var timeline = TimeLineblobDownload.Content.ToObjectFromJson<List<LessonTimeLine>>();
  1191. msgs.Add(update);
  1192. break;
  1193. //更新 课堂总览信息
  1194. case "up-ActivityInfo":
  1195. //BlobDownloadResult ActivityInfoblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/ActivityInfo.json").DownloadContentAsync();
  1196. //var activityInfos = ActivityInfoblobDownload.Content.ToObjectFromJson<List<LessonActivityInfo>>();
  1197. msgs.Add(update);
  1198. break;
  1199. case "up-baseinfo":///更新基础信息,名称科目,年级,分类等,不能删除 ,由update-lesson-baseinfo 触发。
  1200. isReplace = true;
  1201. msgs.Add(update);
  1202. break;
  1203. case "up-expire"://消除过期时间,消除后需要取消已经排程的通知订阅
  1204. try
  1205. {
  1206. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1207. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1208. foreach (var record in records)
  1209. {
  1210. try
  1211. {
  1212. await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  1213. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  1214. }
  1215. catch (Exception)
  1216. {
  1217. continue;
  1218. }
  1219. }
  1220. }
  1221. catch (Exception)
  1222. {
  1223. break;
  1224. }
  1225. isReplace = true;
  1226. msgs.Add(update);
  1227. break;
  1228. case "delete":
  1229. try
  1230. {
  1231. if (lessonRecord.expire > 0)
  1232. {
  1233. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1234. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1235. foreach (var record in records)
  1236. {
  1237. try
  1238. {
  1239. await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  1240. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  1241. }
  1242. catch (Exception)
  1243. {
  1244. continue;
  1245. }
  1246. }
  1247. }
  1248. await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, blobname, new List<string> { $"records/{_lessonId}" });
  1249. await client.GetContainer(Constant.TEAMModelOS, tbname).DeleteItemStreamAsync(lessonRecord.id, new PartitionKey($"Bloblog-{blobname}"));
  1250. var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = "records", name = $"{blobname}" }.ToJsonString()); ;
  1251. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  1252. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  1253. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
  1254. msgs.Add(update);
  1255. }
  1256. catch (CosmosException)
  1257. {
  1258. msgs.Add(update);
  1259. }
  1260. lessonRecord = null;
  1261. isReplace = false;
  1262. break;
  1263. case "create":
  1264. oldlessonRecord = null;
  1265. //处理课堂选用的课程信息
  1266. lessonRecord.show = teacher.lessonShow;
  1267. lessonRecord.upload = 0;
  1268. if (!string.IsNullOrEmpty(lessonRecord.courseId))
  1269. {
  1270. Course course = null;
  1271. try
  1272. {
  1273. var cresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.school}"));
  1274. if (cresponse.Status == 200)
  1275. {
  1276. using var cJson = await JsonDocument.ParseAsync(cresponse.ContentStream);
  1277. course = cJson.ToObject<Course>();
  1278. }
  1279. else
  1280. {
  1281. var sresponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
  1282. if (sresponse.Status == 200)
  1283. {
  1284. using var cJson = await JsonDocument.ParseAsync(sresponse.ContentStream);
  1285. course = cJson.ToObject<Course>();
  1286. }
  1287. else
  1288. {
  1289. course = null;
  1290. }
  1291. }
  1292. }
  1293. catch (Exception ex)
  1294. {
  1295. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-查询课程-CosmosDB异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1296. }
  1297. /*catch (CosmosException ex) when (ex.Status != 404)
  1298. {
  1299. try
  1300. {
  1301. course = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Course>(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
  1302. }
  1303. catch (CosmosException e) when (e.Status != 404)
  1304. {
  1305. course = null;
  1306. }
  1307. }*/
  1308. if (course != null)
  1309. {
  1310. lessonRecord.periodId = course.period?.id;
  1311. lessonRecord.subjectId = course.subject?.id;
  1312. }
  1313. }
  1314. //处理课堂选用的名单
  1315. if (lessonRecord.groupIds.IsNotEmpty())
  1316. {
  1317. HashSet<string> grades = new HashSet<string>();
  1318. List<GroupListDto> groups = await GroupListService.GetGroupListListids(client, _dingDing, lessonRecord.groupIds, lessonRecord.school);
  1319. List<GroupListDto> groupLists = groups?.FindAll(x => !string.IsNullOrEmpty(x.periodId) && x.year > 0 && !string.IsNullOrEmpty(x.school));
  1320. if (groupLists.IsNotEmpty() && !string.IsNullOrWhiteSpace(lessonRecord.periodId))
  1321. {
  1322. try
  1323. {
  1324. var gplist = groupLists.FindAll(x => lessonRecord.groupIds.Contains(x.id));
  1325. School schoolObj = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(lessonRecord.school, new PartitionKey("Base"));
  1326. //年级算法
  1327. var period = schoolObj.period.Find(x => x.id.Equals(lessonRecord.periodId));
  1328. int? Count = period?.grades?.Count;
  1329. if (Count.HasValue)
  1330. {
  1331. int Day = DateTimeOffset.UtcNow.Day;
  1332. int Month = DateTimeOffset.UtcNow.Month;
  1333. int Year = DateTimeOffset.UtcNow.Year;
  1334. int start = int.Parse($"{Year}0901");
  1335. var se = period.semesters.Find(x => x.start == 1);
  1336. if (se == null)
  1337. {
  1338. se = period.semesters.First();
  1339. }
  1340. if (se != null)
  1341. {
  1342. string sm = se.month >= 10 ? $"{se.month}" : $"0{se.month}";
  1343. string sd = se.day >= 10 ? $"{se.day}" : $"0{se.day}";
  1344. start = int.Parse($"{Year}{sm}{sd}");
  1345. }
  1346. int curr = int.Parse(DateTimeOffset.UtcNow.ToString("yyyyMMdd"));
  1347. //新学年开学时间大于当前时间,计算年级需要减1 20220901-20220408 > 0 则当前20220408是2021年入学的,
  1348. //当前时间大于新学年开学时间,计算年级则不需要 20220901-20221203 < 1 则当前20221203是2022年入学的,
  1349. //20230901-20230101 > 0 则当前20230101是2022年入学的,
  1350. int dis = start - curr;
  1351. foreach (int year in gplist.Select(x => x.year))
  1352. {
  1353. int grade;
  1354. if (dis > 0)
  1355. {
  1356. grade = (Year - year - 1) % Count.Value;
  1357. }
  1358. else
  1359. {
  1360. grade = (Year - year) % Count.Value;
  1361. }
  1362. grades.Add($"{grade}");
  1363. }
  1364. }
  1365. }
  1366. catch (CosmosException ex) when (ex.Status == 404)
  1367. {
  1368. }
  1369. catch (Exception ex)
  1370. {
  1371. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-处理课堂记录的-年级处理异常{ex.Message}\n{ex.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1372. }
  1373. }
  1374. lessonRecord.grade = grades.ToList();
  1375. }
  1376. //个人课例保存规则
  1377. try
  1378. {
  1379. if (scope.Equals("private"))
  1380. {
  1381. if (teacher.lessonLimit != -1)
  1382. {
  1383. HashSet<string> ids = new HashSet<string>();
  1384. //未定义的 以及过期时间小于等于0 的 课例
  1385. string private_count_sql = $"select value(c.id) from c where ( c.expire<=0 or IS_DEFINED(c.expire) = false ) and c.tmdid='{tmdid}' ";
  1386. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<string>(
  1387. queryText: private_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(code) }))
  1388. {
  1389. ids.Add(item);
  1390. }
  1391. //包含收藏的本人的个人课例
  1392. string favorite_count_sql = $"select value(c.id) from c where c.type='LessonRecord' and c.owner='{tmdid}' and c.scope='private' ";
  1393. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<string>(
  1394. queryText: favorite_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Favorite-{tmdid}") }))
  1395. {
  1396. ids.Add(item);
  1397. }
  1398. //教师个人预设的,可以通过设置的方式增加
  1399. int limit = teacher.lessonLimit;
  1400. if (teacher.lessonLimit == 0)
  1401. {
  1402. //未设置的的采用系统设置的默认值50
  1403. limit = Constant.private_lesson_limit;
  1404. }
  1405. if (ids.Count >= limit)
  1406. {
  1407. // 1-时间戳,7-时间戳
  1408. Dictionary<int, ExpireTag> result = new Dictionary<int, ExpireTag>();
  1409. //暂定7天
  1410. var now = DateTimeOffset.UtcNow;
  1411. //剩余3天的通知
  1412. //var day3= now.AddDays(Constant.private_lesson_expire - 3).ToUnixTimeMilliseconds();
  1413. //result.Add(3, day3);
  1414. //剩余1天的通知
  1415. var day1 = now.AddDays(Constant.private_lesson_expire - (Constant.private_lesson_expire - 1)).ToUnixTimeMilliseconds();
  1416. result.Add(1, new ExpireTag { expire = day1, tag = "notification" });
  1417. //到期通知
  1418. //不到五点上传的课例,七天之后直接删除。
  1419. int addSecond = 0;
  1420. if (now.Hour > 5)
  1421. {
  1422. // 到凌晨00点还差 (24 - now.Hour) *60 * 60 分钟,再加天数;
  1423. addSecond = Constant.private_lesson_expire * 86400 + (24 - now.Hour) * 3600;
  1424. //再加 00到05小时内的 随机秒数
  1425. Random rand = new Random();
  1426. int randInt = rand.Next(0, 18000);
  1427. addSecond += randInt;
  1428. }
  1429. else
  1430. {
  1431. addSecond = Constant.private_lesson_expire * 24 * 60 * 60;
  1432. }
  1433. lessonRecord.expire = now.AddSeconds(addSecond).ToUnixTimeMilliseconds();
  1434. //result.Add(Constant.private_lesson_expire, lessonRecord.expire);
  1435. result.Add(Constant.private_lesson_expire, new ExpireTag { expire = lessonRecord.expire, tag = "delete" });
  1436. string biz = "expire";
  1437. Notification notification = new Notification
  1438. {
  1439. hubName = "hita",
  1440. type = "msg",
  1441. from = $"ies5:{Environment.GetEnvironmentVariable("Option:Location")}:private",
  1442. to = new List<string> { tmdid },
  1443. label = $"{biz}_lessonRecord",
  1444. body = new
  1445. {
  1446. location = $"{Environment.GetEnvironmentVariable("Option:Location")}",
  1447. biz = biz,
  1448. tmdid = teacher.id,
  1449. tmdname = teacher.name,
  1450. sid = lessonRecord.id,
  1451. sname = lessonRecord.name,
  1452. scope = scope,
  1453. stime = lessonRecord.startTime,
  1454. expire = lessonRecord.expire,
  1455. status = 1,
  1456. //day = Constant.private_lesson_expire,
  1457. time = now
  1458. }.ToJsonString(),
  1459. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  1460. };
  1461. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  1462. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  1463. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  1464. var location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
  1465. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //站内发送消息
  1466. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1467. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1468. if (records.Count <= 0)
  1469. {
  1470. foreach (var item in result)
  1471. {
  1472. string PartitionKey = string.Format("{0}{1}{2}", lessonRecord.code, "-", $"expire-{item.Key}");
  1473. //课堂的id ,
  1474. //课堂的通知时间类型progress, 默认就会发送一条,到期前一天发送一条,最后已到期发送一条。
  1475. var message = new ServiceBusMessage(new
  1476. {
  1477. id = lessonRecord.id,
  1478. progress = item.Key,
  1479. code = lessonRecord.code,
  1480. scope = lessonRecord.scope,
  1481. school = lessonRecord.school,
  1482. opt = "delete",
  1483. expire = lessonRecord.expire,
  1484. tmdid = tmdid,
  1485. tmdname = teacher.name,
  1486. name = lessonRecord.name,
  1487. startTime = lessonRecord.startTime,
  1488. tag = item.Value.tag
  1489. }.ToJsonString());
  1490. message.ApplicationProperties.Add("name", "LessonRecordExpire");
  1491. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(item.Value.expire));
  1492. ChangeRecord changeRecord = new ChangeRecord
  1493. {
  1494. RowKey = lessonRecord.id,
  1495. PartitionKey = PartitionKey,
  1496. sequenceNumber = start,
  1497. msgId = message.MessageId
  1498. };
  1499. await table.Save<ChangeRecord>(changeRecord);
  1500. }
  1501. }
  1502. }
  1503. }
  1504. else
  1505. {
  1506. //=-1 则表示不限制上传数量
  1507. }
  1508. }
  1509. }
  1510. catch (Exception e)
  1511. {
  1512. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-处理课堂记录的-CosmosDB异常{e.Message}\n{e.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1513. }
  1514. msgs.Add(update);
  1515. break;
  1516. default:
  1517. break;
  1518. }
  1519. }
  1520. //如果被删除则不能再被更新
  1521. if (isReplace)
  1522. {
  1523. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(lessonRecord, lessonId, new PartitionKey(code));
  1524. }
  1525. //计算课堂更新前后的差值
  1526. lessonDis = LessonService.DisLessonCount(oldlessonRecord, lessonRecord, lessonDis);
  1527. await LessonService.FixLessonCount(client, _dingDing, lessonRecord, oldlessonRecord, lessonDis);
  1528. }
  1529. }
  1530. catch (CosmosException e)
  1531. {
  1532. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错-CosmosDB异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1533. }
  1534. catch (Exception ex)
  1535. {
  1536. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错\n{ex.Message}\n{ex.StackTrace}\n\n{data}\n{code}\n{updates}\n", GroupNames.醍摩豆服務運維群組);
  1537. }
  1538. }
  1539. [Function("LessonRecordExpire")]
  1540. public async Task LessonRecordExpireFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "lesson-record-expire", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  1541. {
  1542. try
  1543. {
  1544. var jsonMsg = JsonDocument.Parse(msg).RootElement;
  1545. jsonMsg.TryGetProperty("id", out JsonElement id);
  1546. jsonMsg.TryGetProperty("progress", out JsonElement progress);
  1547. jsonMsg.TryGetProperty("code", out JsonElement _code);
  1548. jsonMsg.TryGetProperty("tmdid", out JsonElement tmdid);
  1549. jsonMsg.TryGetProperty("tmdname", out JsonElement tmdname);
  1550. jsonMsg.TryGetProperty("name", out JsonElement name);
  1551. jsonMsg.TryGetProperty("startTime", out JsonElement startTime);
  1552. jsonMsg.TryGetProperty("expire", out JsonElement expire);
  1553. jsonMsg.TryGetProperty("scope", out JsonElement scope);
  1554. jsonMsg.TryGetProperty("school", out JsonElement _school);
  1555. jsonMsg.TryGetProperty("tag", out JsonElement _tag);
  1556. var client = _azureCosmos.GetCosmosClient();
  1557. //处理到期删除
  1558. if (_tag.ValueKind.Equals(JsonValueKind.String) && $"{_tag}".Equals("delete"))
  1559. {
  1560. string lessonId = $"{id}";
  1561. string tbname;
  1562. string school = $"{_school}";
  1563. string code = "";
  1564. if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
  1565. {
  1566. code = $"LessonRecord-{school}";
  1567. tbname = "School";
  1568. }
  1569. else if ($"{scope}".Equals("private"))
  1570. {
  1571. code = $"LessonRecord";
  1572. tbname = "Teacher";
  1573. }
  1574. else
  1575. {
  1576. return;
  1577. }
  1578. Azure.Response response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
  1579. if (response.Status == 200)
  1580. {
  1581. LessonRecord lessonRecord;
  1582. var doc = JsonDocument.Parse(response.ContentStream);
  1583. lessonRecord = doc.RootElement.ToObject<LessonRecord>();
  1584. lessonRecord.status = 404;
  1585. await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(lessonRecord, lessonRecord.id, new PartitionKey(lessonRecord.code));
  1586. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  1587. var messageChange = new ServiceBusMessage(new { delete_id = lessonId, tmdid = tmdid, scope = scope, opt = "delete", school = school }.ToJsonString());
  1588. messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
  1589. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
  1590. await _dingDing.SendBotMsg($"课例:【{lessonRecord.name}】\n课例ID:【{lessonRecord.id}】\n因时间到期,即将被自动删除,到期时间:" +
  1591. $"{lessonRecord.expire}\n{lessonRecord.ToJsonString()}", GroupNames.成都开发測試群組);
  1592. }
  1593. }
  1594. string biz = "expire";
  1595. Notification notification = new Notification
  1596. {
  1597. hubName = "hita",
  1598. type = "msg",
  1599. from = $"ies5:{_option.Location}:private",
  1600. to = new List<string> { $"{tmdid}" },
  1601. label = $"{biz}_lessonRecord",
  1602. body = new
  1603. {
  1604. location = $"{Environment.GetEnvironmentVariable("Option:Location")}",
  1605. biz = biz,
  1606. tmdid = $"{tmdid}",
  1607. tmdname = tmdname,
  1608. sid = $"{id}",
  1609. sname = $"{name}",
  1610. stime = long.Parse($"{startTime}"),
  1611. expire = long.Parse($"{expire}"),
  1612. status = 1,
  1613. //day = Constant.private_lesson_expire,
  1614. time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1615. }.ToJsonString(),
  1616. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  1617. };
  1618. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  1619. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  1620. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  1621. var location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
  1622. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //站内发送消息
  1623. }
  1624. catch (Exception ex)
  1625. {
  1626. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,LessonRecordExpire()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  1627. }
  1628. }
  1629. /// <summary>
  1630. /// 完善课程变更
  1631. /// </summary>
  1632. /// <data msg>
  1633. /// CourseChange
  1634. ///// </data>
  1635. /// <param name="msg"></param>
  1636. /// <returns></returns>
  1637. [Function("Course")]
  1638. public async Task CourseFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "course", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  1639. {
  1640. var client = _azureCosmos.GetCosmosClient();
  1641. try
  1642. {
  1643. //await _dingDing.SendBotMsg($"ServiceBus,CourseChange:{msg}", GroupNames.醍摩豆服務運維群組);
  1644. var jsonMsg = JsonDocument.Parse(msg);
  1645. CourseChange courseChange = msg.ToObject<CourseChange>();
  1646. if (courseChange == null)
  1647. {
  1648. return;
  1649. }
  1650. foreach (var cls in courseChange.addClass)
  1651. {
  1652. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { cls }, courseChange.school);
  1653. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  1654. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  1655. foreach (var stu in addStudentsCls)
  1656. {
  1657. try
  1658. {
  1659. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1660. if (!stuCourse.Value.classId.Contains(cls))
  1661. {
  1662. stuCourse.Value.classId.Add(cls);
  1663. }
  1664. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1665. }
  1666. catch (CosmosException ex)
  1667. {
  1668. if (ex.Response.Status == 404)
  1669. {
  1670. var course = new StuCourse
  1671. {
  1672. id = courseChange.id,
  1673. scode = courseChange.code,
  1674. name = courseChange.name,
  1675. code = $"StuCourse-{courseChange.school}-{stu.id}",
  1676. scope = courseChange.scope,
  1677. school = courseChange.school,
  1678. creatorId = courseChange.creatorId,
  1679. classId = new List<string> { cls },
  1680. pk = "StuCourse",
  1681. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1682. };
  1683. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1684. }
  1685. else
  1686. {
  1687. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1688. }
  1689. }
  1690. }
  1691. foreach (var tmd in addTmdidsCls)
  1692. {
  1693. try
  1694. {
  1695. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1696. if (!stuCourse.Value.classId.Contains(cls))
  1697. {
  1698. stuCourse.Value.classId.Add(cls);
  1699. }
  1700. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1701. }
  1702. catch (CosmosException ex)
  1703. {
  1704. if (ex.Response.Status == 404)
  1705. {
  1706. var course = new StuCourse
  1707. {
  1708. id = courseChange.id,
  1709. scode = courseChange.code,
  1710. name = courseChange.name,
  1711. code = $"StuCourse-{tmd.id}",
  1712. scope = courseChange.scope,
  1713. school = courseChange.school,
  1714. creatorId = courseChange.creatorId,
  1715. classId = new List<string> { cls },
  1716. pk = "StuCourse",
  1717. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1718. };
  1719. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1720. }
  1721. else
  1722. {
  1723. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1724. }
  1725. }
  1726. }
  1727. }
  1728. foreach (var list in courseChange.addList)
  1729. {
  1730. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { list }, courseChange.school);
  1731. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  1732. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  1733. foreach (var stu in addStudentsCls)
  1734. {
  1735. try
  1736. {
  1737. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
  1738. if (!stuCourse.Value.stulist.Contains(list))
  1739. {
  1740. stuCourse.Value.stulist.Add(list);
  1741. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
  1742. }
  1743. }
  1744. catch (CosmosException ex)
  1745. {
  1746. if (ex.Response.Status == 404)
  1747. {
  1748. var course = new StuCourse
  1749. {
  1750. id = courseChange.id,
  1751. scode = courseChange.code,
  1752. name = courseChange.name,
  1753. code = $"StuCourse-{courseChange.school}-{stu.id}",
  1754. scope = courseChange.scope,
  1755. school = courseChange.school,
  1756. creatorId = courseChange.creatorId,
  1757. stulist = new List<string> { list },
  1758. pk = "StuCourse",
  1759. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1760. };
  1761. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1762. }
  1763. else
  1764. {
  1765. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1766. }
  1767. }
  1768. }
  1769. foreach (var tmd in addTmdidsCls)
  1770. {
  1771. try
  1772. {
  1773. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1774. if (!stuCourse.Value.stulist.Contains(list))
  1775. {
  1776. stuCourse.Value.stulist.Add(list);
  1777. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1778. }
  1779. }
  1780. catch (CosmosException ex)
  1781. {
  1782. if (ex.Response.Status == 404)
  1783. {
  1784. var course = new StuCourse
  1785. {
  1786. id = courseChange.id,
  1787. scode = courseChange.code,
  1788. name = courseChange.name,
  1789. code = $"StuCourse-{tmd.id}",
  1790. scope = courseChange.scope,
  1791. school = courseChange.school,
  1792. creatorId = courseChange.creatorId,
  1793. stulist = new List<string> { list },
  1794. pk = "StuCourse",
  1795. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1796. };
  1797. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1798. }
  1799. else
  1800. {
  1801. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1802. }
  1803. }
  1804. }
  1805. }
  1806. foreach (var delCls in courseChange.delClass)
  1807. {
  1808. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { delCls }, courseChange.school);
  1809. var delStudentsCls = tchList.FindAll(x => x.type == 2);
  1810. var delTmdidsCls = tchList.FindAll(x => x.type == 1);
  1811. foreach (var stu in delStudentsCls)
  1812. {
  1813. try
  1814. {
  1815. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1816. if (stuCourse.Value.classId.Contains(delCls))
  1817. {
  1818. stuCourse.Value.classId.Remove(delCls);
  1819. }
  1820. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1821. {
  1822. //当两个列表都不存在时则直接删除
  1823. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1824. }
  1825. else
  1826. {
  1827. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1828. }
  1829. }
  1830. catch (CosmosException ex)
  1831. {
  1832. //await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1833. }
  1834. }
  1835. foreach (var tmd in delTmdidsCls)
  1836. {
  1837. try
  1838. {
  1839. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1840. if (stuCourse.Value.classId.Contains(delCls))
  1841. {
  1842. stuCourse.Value.classId.Remove(delCls);
  1843. }
  1844. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1845. {
  1846. //当两个列表都不存在时则直接删除
  1847. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1848. }
  1849. else
  1850. {
  1851. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1852. }
  1853. }
  1854. catch (CosmosException ex)
  1855. {
  1856. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1857. }
  1858. }
  1859. }
  1860. foreach (var delList in courseChange.delList)
  1861. {
  1862. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { delList }, courseChange.school);
  1863. var delStudentsCls = tchList.FindAll(x => x.type == 2);
  1864. var delTmdidsCls = tchList.FindAll(x => x.type == 1);
  1865. foreach (var stu in delStudentsCls)
  1866. {
  1867. try
  1868. {
  1869. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1870. if (stuCourse.Value.stulist.Contains(delList))
  1871. {
  1872. stuCourse.Value.stulist.Remove(delList);
  1873. }
  1874. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1875. {
  1876. //当两个列表都不存在时则直接删除
  1877. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1878. }
  1879. else
  1880. {
  1881. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1882. }
  1883. }
  1884. catch (CosmosException ex)
  1885. {
  1886. continue;
  1887. // await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1888. }
  1889. }
  1890. foreach (var tmd in delTmdidsCls)
  1891. {
  1892. try
  1893. {
  1894. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1895. if (stuCourse.Value.stulist.Contains(delList))
  1896. {
  1897. stuCourse.Value.stulist.Remove(delList);
  1898. }
  1899. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1900. {
  1901. //当两个列表都不存在时则直接删除
  1902. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1903. }
  1904. else
  1905. {
  1906. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1907. }
  1908. }
  1909. catch (CosmosException ex)
  1910. {
  1911. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1912. }
  1913. }
  1914. }
  1915. }
  1916. catch (Exception ex)
  1917. {
  1918. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -Course\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1919. }
  1920. }
  1921. }
  1922. }