ActiveTaskTopic.cs 154 KB

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