ActiveTaskTopic.cs 137 KB

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