ActiveTaskTopic.cs 134 KB

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