ActiveTaskTopic.cs 135 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208
  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. //attendState
  1263. string basejson = baseblobDownload.Content.ToString().Replace("\"Uncall\"", "0").Replace("Uncall","0");
  1264. LessonBase lessonBase = null;
  1265. try {
  1266. lessonBase = basejson.ToObject<LessonBase>();
  1267. } catch (Exception ex ){
  1268. await _dingDing.SendBotMsg($"base.json转换异常,{ex.Message}{ex.StackTrace}{basejson}", GroupNames.成都开发測試群組);
  1269. //lessonBase = baseblobDownload.Content.ToObjectFromJson<LessonBase>();
  1270. }
  1271. //await _dingDing.SendBotMsg($"课例记录文件base.json:{lessonBase.ToJsonString()}", GroupNames.成都开发測試群組);
  1272. if (lessonBase != null && lessonBase.summary != null)
  1273. {
  1274. //lessonRecord.name = lessonBase.summary.activityName;
  1275. lessonRecord.attendCount = lessonBase.summary.attendCount;
  1276. lessonRecord.clientCount = lessonBase.summary.clientCount;
  1277. lessonRecord.attendRate = lessonBase.summary.attendRate;
  1278. lessonRecord.groupCount = lessonBase.summary.groupCount;
  1279. lessonRecord.collateTaskCount = lessonBase.summary.collateTaskCount;
  1280. lessonRecord.hitaClientCmpCount = lessonBase.summary.collateTaskCount+ lessonRecord.hitaClientCmpCount;
  1281. lessonRecord.collateCount = lessonBase.summary.collateCount;
  1282. lessonRecord.pushCount = lessonBase.summary.pushCount;
  1283. lessonRecord.totalPoint = lessonBase.summary.totalPoint;
  1284. lessonRecord.examQuizCount = lessonBase.summary.examQuizCount;
  1285. lessonRecord.interactionCount = lessonBase.summary.interactionCount;
  1286. lessonRecord.examPointRate = lessonBase.summary.examPointRate;
  1287. lessonRecord.clientInteractionCount = lessonBase.summary.clientInteractionCount;
  1288. lessonRecord.clientInteractionAverge = lessonBase.summary.clientInteractionAverge;
  1289. lessonRecord.examCount = lessonBase.summary.examCount;
  1290. lessonRecord.totalInteractPoint = lessonBase.summary.totalInteractPoint;
  1291. lessonRecord.learningCategory = lessonBase.summary.learningCategory;
  1292. if (lessonRecord.learningCategory == null)
  1293. {
  1294. lessonRecord.learningCategory = new LearningCategory();
  1295. }
  1296. if (lessonRecord.hitaClientCmpCount > 0) {
  1297. lessonRecord.learningCategory.cooperation = 1;
  1298. }
  1299. if (!string.IsNullOrWhiteSpace(lessonRecord.school))
  1300. {
  1301. lessonBase.student.ForEach(x =>
  1302. {
  1303. if (string.IsNullOrWhiteSpace(x.school))
  1304. {
  1305. x.school = lessonRecord.school;
  1306. }
  1307. });
  1308. }
  1309. //计算TP灯
  1310. {
  1311. int T = -1;
  1312. int P = -1;
  1313. if (lessonRecord.clientInteractionAverge <= 0)
  1314. {
  1315. T = 0;
  1316. }
  1317. else if (lessonRecord.clientInteractionAverge >= 1 && lessonRecord.clientInteractionAverge <= 2)
  1318. {
  1319. T = 1;
  1320. }
  1321. else
  1322. {
  1323. T = 2;
  1324. }
  1325. //if (lessonRecord.examCount > 0)
  1326. //{
  1327. // //有评测次数大于0则P是直接绿灯
  1328. // P = 2;
  1329. //}
  1330. //else {
  1331. //}
  1332. int a = lessonRecord.hitaClientCmpCount;
  1333. int b = lessonRecord.pushCount;
  1334. int c = lessonRecord.examCount;
  1335. switch (true)
  1336. {
  1337. case bool when T == 0:
  1338. P = 0;
  1339. break;
  1340. case bool when T == 1 || T == 2:
  1341. if (a == 0 && b == 0 && c == 0)
  1342. {
  1343. P = 0;
  1344. }
  1345. else if ((a > 0 && b > 0) || (a > 0 && c > 0) || (b > 0 && c > 0))
  1346. {
  1347. P = 2;
  1348. }
  1349. else
  1350. {
  1351. P = 1;
  1352. }
  1353. break;
  1354. }
  1355. lessonRecord.tLevel = T;
  1356. lessonRecord.pLevel = P;
  1357. }
  1358. //LessonStudentRecord lessonStudentRecord = new LessonStudentRecord
  1359. //{
  1360. // clientSummaryList = lessonBase.report.clientSummaryList,
  1361. // students = lessonBase.student,
  1362. // name = lessonRecord.name,
  1363. // school = lessonRecord.school,
  1364. // id = lessonRecord.id,
  1365. // scope = lessonRecord.scope,
  1366. // tmdid = lessonRecord.tmdid,
  1367. // code = "LessonStudentRecord",
  1368. // pk = "LessonStudentRecord",
  1369. // courseId =lessonRecord.courseId,
  1370. // groupIds= lessonRecord.groupIds,
  1371. // periodId = lessonRecord.periodId,
  1372. // subjectId = lessonRecord.subjectId,
  1373. //};
  1374. //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS,Constant.Student).UpsertItemAsync<LessonStudentRecord>(lessonStudentRecord, new PartitionKey("LessonStudentRecord"));
  1375. }
  1376. //有上传 base.josn.
  1377. lessonRecord.upload = 1;
  1378. // await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} 更新完成", GroupNames.醍摩豆服務運維群組);
  1379. LessonService.DoAutoDeleteSchoolLessonRecord(lessonRecord, scope, client, school, tmdid, teacher, _serviceBus, _azureStorage, _configuration,_coreAPIHttpService,_dingDing, _azureRedis);
  1380. long? size = await _azureStorage.GetBlobContainerClient(blobname).GetBlobsSize($"records/{_lessonId}");
  1381. Bloblog bloblog = new Bloblog
  1382. {
  1383. id = lessonRecord.id,
  1384. code = $"Bloblog-{blobname}",
  1385. name = lessonRecord.name,
  1386. pk = "Bloblog",
  1387. time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  1388. type = "records",
  1389. url = $"records/{_lessonId}",
  1390. subjectId = string.IsNullOrWhiteSpace(lessonRecord.subjectId) ? new List<string>() : new List<string> { lessonRecord.subjectId },
  1391. periodId = string.IsNullOrWhiteSpace(lessonRecord.periodId) ? new List<string>() : new List<string> { lessonRecord.periodId },
  1392. size = size.HasValue ? size.Value : 0,
  1393. };
  1394. await client.GetContainer(Constant.TEAMModelOS, tbname).UpsertItemAsync(bloblog);
  1395. //await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} blob刷新完成!", GroupNames.醍摩豆服務運維群組);
  1396. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = "records", name = $"{blobname}" }, _serviceBus, _configuration,_azureRedis);
  1397. msgs.Add(update);
  1398. DoLessonStudentRecord(_dingDing, _snowflakeId, lessonRecord, scope, client, school, tmdid, teacher, _serviceBus, _azureStorage, _configuration, lessonBase);
  1399. }
  1400. catch (Exception ex)
  1401. {
  1402. if (!ex.Message.Contains("exist")) {
  1403. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}课程读取base.json,{_lessonId}\n{ex.Message}\n{ex.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1404. }
  1405. }
  1406. break;
  1407. //更新 时间线
  1408. case "up-TimeLine":
  1409. //BlobDownloadResult TimeLineblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/TimeLine.json").DownloadContentAsync();
  1410. //var timeline = TimeLineblobDownload.Content.ToObjectFromJson<List<LessonTimeLine>>();
  1411. msgs.Add(update);
  1412. break;
  1413. //更新 课堂总览信息
  1414. case "up-ActivityInfo":
  1415. //BlobDownloadResult ActivityInfoblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/ActivityInfo.json").DownloadContentAsync();
  1416. //var activityInfos = ActivityInfoblobDownload.Content.ToObjectFromJson<List<LessonActivityInfo>>();
  1417. msgs.Add(update);
  1418. break;
  1419. case "up-baseinfo":///更新基础信息,名称科目,年级,分类等,不能删除 ,由update-lesson-baseinfo 触发。
  1420. isReplace = true;
  1421. msgs.Add(update);
  1422. break;
  1423. case "up-expire"://消除过期时间,消除后需要取消已经排程的通知订阅
  1424. try
  1425. {
  1426. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1427. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1428. foreach (var record in records)
  1429. {
  1430. try
  1431. {
  1432. await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  1433. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  1434. }
  1435. catch (Exception)
  1436. {
  1437. continue;
  1438. }
  1439. }
  1440. }
  1441. catch (Exception)
  1442. {
  1443. break;
  1444. }
  1445. isReplace = true;
  1446. msgs.Add(update);
  1447. break;
  1448. case "delete":
  1449. try
  1450. {
  1451. if (lessonRecord.expire > 0)
  1452. {
  1453. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1454. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  1455. foreach (var record in records)
  1456. {
  1457. try
  1458. {
  1459. await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  1460. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  1461. }
  1462. catch (Exception)
  1463. {
  1464. continue;
  1465. }
  1466. }
  1467. }
  1468. await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, blobname, new List<string> { $"records/{_lessonId}" });
  1469. await client.GetContainer(Constant.TEAMModelOS, tbname).DeleteItemStreamAsync(lessonRecord.id, new PartitionKey($"Bloblog-{blobname}"));
  1470. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = "records", name = $"{blobname}" }, _serviceBus, _configuration, _azureRedis);
  1471. msgs.Add(update);
  1472. }
  1473. catch (CosmosException)
  1474. {
  1475. msgs.Add(update);
  1476. }
  1477. lessonRecord = null;
  1478. isReplace = false;
  1479. break;
  1480. case "create":
  1481. oldlessonRecord = null;
  1482. //处理课堂选用的课程信息
  1483. lessonRecord.show = teacher.lessonShow;
  1484. lessonRecord.upload = 0;
  1485. if (!string.IsNullOrEmpty(lessonRecord.courseId))
  1486. {
  1487. Course course = null;
  1488. try
  1489. {
  1490. var cresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.school}"));
  1491. if (cresponse.Status == 200)
  1492. {
  1493. using var cJson = await JsonDocument.ParseAsync(cresponse.ContentStream);
  1494. course = cJson.ToObject<Course>();
  1495. }
  1496. else
  1497. {
  1498. var sresponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
  1499. if (sresponse.Status == 200)
  1500. {
  1501. using var cJson = await JsonDocument.ParseAsync(sresponse.ContentStream);
  1502. course = cJson.ToObject<Course>();
  1503. }
  1504. else
  1505. {
  1506. course = null;
  1507. }
  1508. }
  1509. }
  1510. catch (Exception ex)
  1511. {
  1512. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-查询课程-CosmosDB异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1513. }
  1514. /*catch (CosmosException ex) when (ex.Status != 404)
  1515. {
  1516. try
  1517. {
  1518. course = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Course>(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
  1519. }
  1520. catch (CosmosException e) when (e.Status != 404)
  1521. {
  1522. course = null;
  1523. }
  1524. }*/
  1525. if (course != null)
  1526. {
  1527. lessonRecord.periodId = course.period?.id;
  1528. lessonRecord.subjectId = course.subject?.id;
  1529. }
  1530. }
  1531. //处理课堂选用的名单
  1532. if (lessonRecord.groupIds.IsNotEmpty())
  1533. {
  1534. List<GroupListDto> groups = await GroupListService.GetGroupListByListids(client, _dingDing, lessonRecord.groupIds, lessonRecord.school);
  1535. if ( !string.IsNullOrWhiteSpace(lessonRecord.school) && !string.IsNullOrWhiteSpace(lessonRecord.periodId)) {
  1536. HashSet<string> grades = new HashSet<string>();
  1537. School schoolObj = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(lessonRecord.school, new PartitionKey("Base"));
  1538. HashSet<int> gd = groups.SelectMany(z => z.grades).ToHashSet();
  1539. groups.ForEach(y => {
  1540. if (y.type.Equals("teach")|| y.type.Equals("class")) {
  1541. gd.Add(y.year);
  1542. }
  1543. });
  1544. var gpdata = SchoolService.GetGrades(schoolObj, lessonRecord.periodId, gd);
  1545. lessonRecord.grade = gpdata.grades.ToList();
  1546. }
  1547. }
  1548. //个人课例保存规则
  1549. try
  1550. {
  1551. if (scope.Equals("private"))
  1552. {
  1553. int lessonLimit = teacher.lessonLimit;
  1554. //获取已经使用的空间大小
  1555. long blobsize = 0;
  1556. var value = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", tmdid);
  1557. if (value != default && !value.IsNullOrEmpty)
  1558. {
  1559. JsonElement record = value.ToString().ToObject<JsonElement>();
  1560. if (record.TryGetInt64(out blobsize))
  1561. {
  1562. }
  1563. }
  1564. int blobTotal = teacher.size;
  1565. blobTotal = teacher.size;
  1566. //累加学校分配的空间
  1567. foreach (var schoolInfo in teacher.schools)
  1568. {
  1569. SchoolTeacher st = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolTeacher>(lessonRecord.tmdid, new PartitionKey($"Teacher-{schoolInfo.schoolId}"));
  1570. blobTotal += st.size;
  1571. }
  1572. //剩余空间大于2G
  1573. if (blobTotal * 1073741824 - blobsize > 2147483648)
  1574. {
  1575. //大于2G 不限制
  1576. lessonLimit = -1;
  1577. }
  1578. if (lessonLimit != -1)
  1579. {
  1580. HashSet<string> ids = new HashSet<string>();
  1581. //未定义的 以及过期时间小于等于0 的 课例
  1582. string private_count_sql = $"select value(c.id) from c where ( c.expire<=0 or IS_DEFINED(c.expire) = false ) and c.tmdid='{tmdid}' ";
  1583. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<string>(
  1584. queryText: private_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(code) }))
  1585. {
  1586. ids.Add(item);
  1587. }
  1588. // 220601 收藏不限條數,但空間不足時,僅保留最後一次上傳的課例 ()
  1589. //包含收藏的本人的个人课例
  1590. //string favorite_count_sql = $"select value(c.id) from c where c.type='LessonRecord' and c.owner='{tmdid}' and c.scope='private' ";
  1591. //await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<string>(
  1592. // queryText: favorite_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Favorite-{tmdid}") }))
  1593. //{
  1594. // ids.Add(item);
  1595. //}
  1596. //教师个人预设的,可以通过设置的方式增加
  1597. int limit = teacher.lessonLimit;
  1598. if (teacher.lessonLimit == 0)
  1599. {
  1600. //未设置的的采用系统设置的默认值50
  1601. limit = Constant.private_lesson_limit;
  1602. }
  1603. if (ids.Count >= limit)
  1604. {
  1605. LessonRecord lessonRecordExpire = null;
  1606. //获取一条最新的 且没有被收藏,且没有被标记为过期的记录,且不是当前触发的id 。
  1607. //220712 讨论,将desc去掉,获取最旧的那一笔数据。删除最旧的
  1608. string sql = $"SELECT top 1 value(c) FROM c where ( c.expire<=0 or IS_DEFINED(c.expire) = false ) and c.tmdid='{tmdid}' " +
  1609. $"and c.favorite<=0 and c.id<>'{lessonRecord.id}' and c.status<>404 order by c.startTime ";
  1610. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<LessonRecord>(
  1611. queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"{code}") }))
  1612. {
  1613. lessonRecordExpire = item; break;
  1614. }
  1615. if (lessonRecordExpire != null)
  1616. {
  1617. // 1-时间戳,7-时间戳
  1618. Dictionary<int, ExpireTag> result = new Dictionary<int, ExpireTag>();
  1619. //暂定7天
  1620. var now = DateTimeOffset.UtcNow;
  1621. //剩余3天的通知
  1622. //var day3= now.AddDays(Constant.private_lesson_expire - 3).ToUnixTimeMilliseconds();
  1623. //result.Add(3, day3);
  1624. //剩余1天的通知
  1625. var day1 = now.AddDays(Constant.private_lesson_expire - (Constant.private_lesson_expire - 1)).ToUnixTimeMilliseconds();
  1626. result.Add(1, new ExpireTag { expire = day1, tag = "notification" });
  1627. //到期通知
  1628. //不到五点上传的课例,七天之后直接删除。
  1629. int addSecond = 0;
  1630. if (now.Hour > 5)
  1631. {
  1632. // 到凌晨00点还差 (24 - now.Hour) *60 * 60 分钟,再加天数;
  1633. addSecond = Constant.private_lesson_expire * 86400 + (24 - now.Hour) * 3600;
  1634. //再加 00到05小时内的 随机秒数
  1635. Random rand = new Random();
  1636. int randInt = rand.Next(0, 18000);
  1637. addSecond += randInt;
  1638. }
  1639. else
  1640. {
  1641. addSecond = Constant.private_lesson_expire * 24 * 60 * 60;
  1642. }
  1643. lessonRecordExpire.expire = now.AddSeconds(addSecond).ToUnixTimeMilliseconds();
  1644. //result.Add(Constant.private_lesson_expire, lessonRecordExpire.expire);
  1645. result.Add(Constant.private_lesson_expire, new ExpireTag { expire = lessonRecordExpire.expire, tag = "delete" });
  1646. string biz = "expire";
  1647. string expireTime= DateTimeOffset.FromUnixTimeMilliseconds(lessonRecordExpire.expire).ToString("yyyy-MM-dd HH:mm:ss");
  1648. _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = teacher.id, name = teacher.name, code = teacher.lang } }, "expire-private_lessonRecord", Constant.NotifyType_IES5_Course,
  1649. new Dictionary<string, object> { { "tmdname", teacher.name }, { "tmdid", teacher.name }, { "expireTime", expireTime }, { "lessonId", lessonRecordExpire.id }, { "lessonName", lessonRecordExpire. name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
  1650. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  1651. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecordExpire.id } });
  1652. if (records.Count <= 0)
  1653. {
  1654. foreach (var item in result)
  1655. {
  1656. string PartitionKey = string.Format("{0}{1}{2}", lessonRecordExpire.code, "-", $"expire-{item.Key}");
  1657. //课堂的id ,
  1658. //课堂的通知时间类型progress, 默认就会发送一条,到期前一天发送一条,最后已到期发送一条。
  1659. var message = new ServiceBusMessage(new
  1660. {
  1661. id = lessonRecordExpire.id,
  1662. progress = item.Key,
  1663. code = lessonRecordExpire.code,
  1664. scope = lessonRecordExpire.scope,
  1665. school = lessonRecordExpire.school,
  1666. opt = "delete",
  1667. expire = lessonRecordExpire.expire,
  1668. tmdid = tmdid,
  1669. tmdname = teacher.name,
  1670. name = lessonRecordExpire.name,
  1671. startTime = lessonRecordExpire.startTime,
  1672. tag = item.Value.tag
  1673. }.ToJsonString());
  1674. message.ApplicationProperties.Add("name", "LessonRecordExpire");
  1675. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(item.Value.expire));
  1676. ChangeRecord changeRecord = new ChangeRecord
  1677. {
  1678. RowKey = lessonRecordExpire.id,
  1679. PartitionKey = PartitionKey,
  1680. sequenceNumber = start,
  1681. msgId = message.MessageId
  1682. };
  1683. await table.Save<ChangeRecord>(changeRecord);
  1684. }
  1685. }
  1686. await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(lessonRecordExpire, lessonRecordExpire.id, new PartitionKey(lessonRecordExpire.code));
  1687. }
  1688. }
  1689. }
  1690. else
  1691. {
  1692. //=-1 则表示不限制上传数量
  1693. }
  1694. }
  1695. }
  1696. catch (Exception e)
  1697. {
  1698. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-处理课堂记录的-CosmosDB异常{e.Message}\n{e.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1699. }
  1700. msgs.Add(update);
  1701. break;
  1702. default:
  1703. break;
  1704. }
  1705. }
  1706. //如果被删除则不能再被更新
  1707. if (isReplace)
  1708. {
  1709. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(lessonRecord, lessonId, new PartitionKey(code));
  1710. }
  1711. //计算课堂更新前后的差值
  1712. lessonDis = LessonService.DisLessonCount(oldlessonRecord, lessonRecord, lessonDis);
  1713. await LessonService.FixLessonCount(client, _dingDing, lessonRecord, oldlessonRecord, lessonDis);
  1714. }
  1715. }
  1716. catch (CosmosException e)
  1717. {
  1718. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错-CosmosDB异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1719. }
  1720. catch (Exception ex)
  1721. {
  1722. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错\n{ex.Message}\n{ex.StackTrace}\n\n{data}\n{code}\n{updates}\n", GroupNames.醍摩豆服務運維群組);
  1723. }
  1724. }
  1725. [Function("LessonRecordExpire")]
  1726. public async Task LessonRecordExpireFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "lesson-record-expire", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  1727. {
  1728. try
  1729. {
  1730. var jsonMsg = JsonDocument.Parse(msg).RootElement;
  1731. jsonMsg.TryGetProperty("id", out JsonElement id);
  1732. jsonMsg.TryGetProperty("progress", out JsonElement progress);
  1733. jsonMsg.TryGetProperty("code", out JsonElement _code);
  1734. jsonMsg.TryGetProperty("tmdid", out JsonElement tmdid);
  1735. jsonMsg.TryGetProperty("tmdname", out JsonElement tmdname);
  1736. jsonMsg.TryGetProperty("name", out JsonElement name);
  1737. jsonMsg.TryGetProperty("startTime", out JsonElement startTime);
  1738. jsonMsg.TryGetProperty("expire", out JsonElement expire);
  1739. jsonMsg.TryGetProperty("scope", out JsonElement scope);
  1740. jsonMsg.TryGetProperty("school", out JsonElement _school);
  1741. jsonMsg.TryGetProperty("tag", out JsonElement _tag);
  1742. var client = _azureCosmos.GetCosmosClient();
  1743. //处理到期删除
  1744. if (_tag.ValueKind.Equals(JsonValueKind.String) && $"{_tag}".Equals("delete"))
  1745. {
  1746. string lessonId = $"{id}";
  1747. string tbname;
  1748. string school = $"{_school}";
  1749. string code = "";
  1750. if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
  1751. {
  1752. code = $"LessonRecord-{school}";
  1753. tbname = "School";
  1754. }
  1755. else if ($"{scope}".Equals("private"))
  1756. {
  1757. code = $"LessonRecord";
  1758. tbname = "Teacher";
  1759. }
  1760. else
  1761. {
  1762. return;
  1763. }
  1764. Azure.Response response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
  1765. if (response.Status == 200)
  1766. {
  1767. LessonRecord lessonRecord;
  1768. var doc = JsonDocument.Parse(response.ContentStream);
  1769. lessonRecord = doc.RootElement.ToObject<LessonRecord>();
  1770. lessonRecord.status = 404;
  1771. await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(lessonRecord, lessonRecord.id, new PartitionKey(lessonRecord.code));
  1772. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  1773. var messageChange = new ServiceBusMessage(new { delete_id = lessonId, tmdid = tmdid, scope = scope, opt = "delete", school = school }.ToJsonString());
  1774. messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
  1775. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
  1776. await _dingDing.SendBotMsg($"课例:【{lessonRecord.name}】\n课例ID:【{lessonRecord.id}】\n因时间到期,即将被自动删除,到期时间:" +
  1777. $"{lessonRecord.expire}\n{lessonRecord.ToJsonString()}", GroupNames.成都开发測試群組);
  1778. }
  1779. }
  1780. string biz = "expire";
  1781. Teacher targetTeacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>($"{tmdid}", new PartitionKey($"Base"));
  1782. string expireTime = DateTimeOffset.FromUnixTimeMilliseconds(long.Parse($"{expire}")).ToString("yyyy-MM-dd HH:mm:ss");
  1783. _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = targetTeacher.id, name = targetTeacher.name, code = targetTeacher.lang } }, "expire-private_lessonRecord", Constant.NotifyType_IES5_Course,
  1784. new Dictionary<string, object> { { "tmdname", tmdname }, { "tmdid",tmdid}, { "lessonId", id }, { "expireTime", expireTime }, { "lessonName",name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
  1785. }
  1786. catch (Exception ex)
  1787. {
  1788. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,LessonRecordExpire()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
  1789. }
  1790. }
  1791. /// <summary>
  1792. /// 完善课程变更
  1793. /// </summary>
  1794. /// <data msg>
  1795. /// CourseChange
  1796. ///// </data>
  1797. /// <param name="msg"></param>
  1798. /// <returns></returns>
  1799. [Function("Course")]
  1800. public async Task CourseFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "course", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  1801. {
  1802. var client = _azureCosmos.GetCosmosClient();
  1803. try
  1804. {
  1805. //await _dingDing.SendBotMsg($"ServiceBus,CourseChange:{msg}", GroupNames.醍摩豆服務運維群組);
  1806. var jsonMsg = JsonDocument.Parse(msg);
  1807. CourseChange courseChange = msg.ToObject<CourseChange>();
  1808. if (courseChange == null)
  1809. {
  1810. return;
  1811. }
  1812. foreach (var cls in courseChange.addClass)
  1813. {
  1814. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, new List<string> { cls }, courseChange.school);
  1815. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  1816. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  1817. foreach (var stu in addStudentsCls)
  1818. {
  1819. try
  1820. {
  1821. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1822. if (!stuCourse.Value.classId.Contains(cls))
  1823. {
  1824. stuCourse.Value.classId.Add(cls);
  1825. }
  1826. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1827. }
  1828. catch (CosmosException ex)
  1829. {
  1830. if (ex.Response.Status == 404)
  1831. {
  1832. var course = new StuCourse
  1833. {
  1834. id = courseChange.id,
  1835. scode = courseChange.code,
  1836. name = courseChange.name,
  1837. code = $"StuCourse-{courseChange.school}-{stu.id}",
  1838. scope = courseChange.scope,
  1839. school = courseChange.school,
  1840. creatorId = courseChange.creatorId,
  1841. classId = new List<string> { cls },
  1842. pk = "StuCourse",
  1843. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1844. };
  1845. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1846. }
  1847. else
  1848. {
  1849. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1850. }
  1851. }
  1852. }
  1853. foreach (var tmd in addTmdidsCls)
  1854. {
  1855. try
  1856. {
  1857. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1858. if (!stuCourse.Value.classId.Contains(cls))
  1859. {
  1860. stuCourse.Value.classId.Add(cls);
  1861. }
  1862. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1863. }
  1864. catch (CosmosException ex)
  1865. {
  1866. if (ex.Response.Status == 404)
  1867. {
  1868. var course = new StuCourse
  1869. {
  1870. id = courseChange.id,
  1871. scode = courseChange.code,
  1872. name = courseChange.name,
  1873. code = $"StuCourse-{tmd.id}",
  1874. scope = courseChange.scope,
  1875. school = courseChange.school,
  1876. creatorId = courseChange.creatorId,
  1877. classId = new List<string> { cls },
  1878. pk = "StuCourse",
  1879. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1880. };
  1881. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1882. }
  1883. else
  1884. {
  1885. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1886. }
  1887. }
  1888. }
  1889. }
  1890. foreach (var list in courseChange.addList)
  1891. {
  1892. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, new List<string> { list }, courseChange.school);
  1893. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  1894. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  1895. foreach (var stu in addStudentsCls)
  1896. {
  1897. try
  1898. {
  1899. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
  1900. if (!stuCourse.Value.stulist.Contains(list))
  1901. {
  1902. stuCourse.Value.stulist.Add(list);
  1903. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
  1904. }
  1905. }
  1906. catch (CosmosException ex)
  1907. {
  1908. if (ex.Response.Status == 404)
  1909. {
  1910. var course = new StuCourse
  1911. {
  1912. id = courseChange.id,
  1913. scode = courseChange.code,
  1914. name = courseChange.name,
  1915. code = $"StuCourse-{courseChange.school}-{stu.id}",
  1916. scope = courseChange.scope,
  1917. school = courseChange.school,
  1918. creatorId = courseChange.creatorId,
  1919. stulist = new List<string> { list },
  1920. pk = "StuCourse",
  1921. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1922. };
  1923. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1924. }
  1925. else
  1926. {
  1927. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1928. }
  1929. }
  1930. }
  1931. foreach (var tmd in addTmdidsCls)
  1932. {
  1933. try
  1934. {
  1935. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1936. if (!stuCourse.Value.stulist.Contains(list))
  1937. {
  1938. stuCourse.Value.stulist.Add(list);
  1939. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  1940. }
  1941. }
  1942. catch (CosmosException ex)
  1943. {
  1944. if (ex.Response.Status == 404)
  1945. {
  1946. var course = new StuCourse
  1947. {
  1948. id = courseChange.id,
  1949. scode = courseChange.code,
  1950. name = courseChange.name,
  1951. code = $"StuCourse-{tmd.id}",
  1952. scope = courseChange.scope,
  1953. school = courseChange.school,
  1954. creatorId = courseChange.creatorId,
  1955. stulist = new List<string> { list },
  1956. pk = "StuCourse",
  1957. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1958. };
  1959. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
  1960. }
  1961. else
  1962. {
  1963. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1964. }
  1965. }
  1966. }
  1967. }
  1968. foreach (var delCls in courseChange.delClass)
  1969. {
  1970. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, new List<string> { delCls }, courseChange.school);
  1971. var delStudentsCls = tchList.FindAll(x => x.type == 2);
  1972. var delTmdidsCls = tchList.FindAll(x => x.type == 1);
  1973. foreach (var stu in delStudentsCls)
  1974. {
  1975. try
  1976. {
  1977. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1978. if (stuCourse.Value.classId.Contains(delCls))
  1979. {
  1980. stuCourse.Value.classId.Remove(delCls);
  1981. }
  1982. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  1983. {
  1984. //当两个列表都不存在时则直接删除
  1985. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1986. }
  1987. else
  1988. {
  1989. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  1990. }
  1991. }
  1992. catch (CosmosException ex)
  1993. {
  1994. //await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1995. }
  1996. }
  1997. foreach (var tmd in delTmdidsCls)
  1998. {
  1999. try
  2000. {
  2001. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  2002. if (stuCourse.Value.classId.Contains(delCls))
  2003. {
  2004. stuCourse.Value.classId.Remove(delCls);
  2005. }
  2006. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  2007. {
  2008. //当两个列表都不存在时则直接删除
  2009. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  2010. }
  2011. else
  2012. {
  2013. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  2014. }
  2015. }
  2016. catch (CosmosException ex)
  2017. {
  2018. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2019. }
  2020. }
  2021. }
  2022. foreach (var delList in courseChange.delList)
  2023. {
  2024. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, new List<string> { delList }, courseChange.school);
  2025. var delStudentsCls = tchList.FindAll(x => x.type == 2);
  2026. var delTmdidsCls = tchList.FindAll(x => x.type == 1);
  2027. foreach (var stu in delStudentsCls)
  2028. {
  2029. try
  2030. {
  2031. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  2032. if (stuCourse.Value.stulist.Contains(delList))
  2033. {
  2034. stuCourse.Value.stulist.Remove(delList);
  2035. }
  2036. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  2037. {
  2038. //当两个列表都不存在时则直接删除
  2039. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  2040. }
  2041. else
  2042. {
  2043. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
  2044. }
  2045. }
  2046. catch (CosmosException ex)
  2047. {
  2048. continue;
  2049. // await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2050. }
  2051. }
  2052. foreach (var tmd in delTmdidsCls)
  2053. {
  2054. try
  2055. {
  2056. ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  2057. if (stuCourse.Value.stulist.Contains(delList))
  2058. {
  2059. stuCourse.Value.stulist.Remove(delList);
  2060. }
  2061. if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
  2062. {
  2063. //当两个列表都不存在时则直接删除
  2064. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  2065. }
  2066. else
  2067. {
  2068. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
  2069. }
  2070. }
  2071. catch (CosmosException ex)
  2072. {
  2073. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2074. }
  2075. }
  2076. }
  2077. }
  2078. catch (Exception ex)
  2079. {
  2080. await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -Course\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2081. }
  2082. }
  2083. [Function("Imei")]
  2084. public async Task ImeiFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "imei", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  2085. {
  2086. try
  2087. {
  2088. //await _dingDing.SendBotMsg($"IES5,{Environment.GetEnvironmentVariable("Option:Location")},Imei AF call\n{msg.ToJsonString()}", GroupNames.成都开发測試群組);
  2089. using var json = JsonDocument.Parse(msg);
  2090. if (json.RootElement.TryGetProperty("channel", out JsonElement channel) &&
  2091. json.RootElement.TryGetProperty("userid", out JsonElement userid) &&
  2092. json.RootElement.TryGetProperty("school", out JsonElement school) &&
  2093. json.RootElement.TryGetProperty("stus", out JsonElement stus))
  2094. {
  2095. var db = _azureCosmos.GetCosmosClient();
  2096. foreach (var stu in stus.EnumerateArray())
  2097. {
  2098. await foreach (Response item in db.GetContainer(Constant.TEAMModelOS, Constant.Student).GetItemQueryStreamIterator(
  2099. queryText: $"SELECT TOP 1 * FROM c WHERE c.stuid = '{stu.GetString()}'",
  2100. requestOptions: new() { PartitionKey = new($"Imei") }))
  2101. {
  2102. using var root = await JsonDocument.ParseAsync(item.ContentStream);
  2103. if (root.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2104. {
  2105. var doc = root.RootElement.GetProperty("Documents").EnumerateArray().First();
  2106. var imei = doc.ToObject<Imei>();
  2107. imei.channel = channel.GetString();
  2108. imei.userid = userid.GetString();
  2109. await db.GetContainer(Constant.TEAMModelOS, Constant.Student).ReplaceItemAsync<Imei>(imei, imei.id);
  2110. }
  2111. }
  2112. }
  2113. }
  2114. }
  2115. catch (Exception ex)
  2116. {
  2117. await _dingDing.SendBotMsg($"IES5,{_option.Location},Imei AF error\n{ex.Message}\n{ex.StackTrace}{msg.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  2118. }
  2119. }
  2120. }
  2121. }