ActiveTaskTopic.cs 137 KB

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