ActiveTaskTopic.cs 161 KB

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