1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500 |
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using Azure.Cosmos;
- using Azure.Messaging.ServiceBus;
- using Microsoft.Extensions.Logging;
- using StackExchange.Redis;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK.Models.Cosmos;
- using TEAMModelOS.SDK.Models.Cosmos.Common;
- using System.Linq;
- using TEAMModelOS.SDK.Models.Service;
- using TEAMModelOS.SDK.Models.Cosmos.BI;
- using TEAMModelOS.Models;
- using Microsoft.Extensions.Options;
- using Microsoft.Extensions.Configuration;
- using HTEXLib.COMM.Helpers;
- using Microsoft.Azure.Functions.Worker;
- using TEAMModelOS.SDK.Services;
- using Azure.Storage.Blobs.Models;
- using System.IO;
- using Azure;
- using static TEAMModelOS.SDK.Models.Service.LessonService;
- using DinkToPdf.Contracts;
- using TEAMModelOS.SDK.Helper.Common.DateTimeHelper;
- using static TEAMModelOS.SDK.StatisticsService;
- using DocumentFormat.OpenXml.Office2010.Excel;
- using DocumentFormat.OpenXml.Wordprocessing;
- using System.Xml.Linq;
- using Azure.Storage.Sas;
- using DocumentFormat.OpenXml.Drawing;
- using static TEAMModelOS.FunctionV4.IESHttpTrigger;
- using System.Net.Http;
- using System.Web;
- using System.Net;
- using System.Net.Http.Json;
- using System.Threading;
- using System.Collections.Concurrent;
- using Microsoft.Azure.Amqp.Framing;
- using System.Security.Policy;
- using TEAMModelOS.SDK.Models.Service.BI;
- namespace TEAMModelOS.FunctionV4.ServiceBus
- {
- public class ActiveTaskTopic
- {
- private readonly int psize = 20;
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly DingDing _dingDing;
- private readonly AzureStorageFactory _azureStorage;
- private readonly AzureRedisFactory _azureRedis;
- private readonly AzureServiceBusFactory _serviceBus;
- private readonly Option _option;
- private readonly CoreAPIHttpService _coreAPIHttpService;
- private readonly IConfiguration _configuration;
- private readonly IConverter _converter;
- private readonly SnowflakeId _snowflakeId;
- private readonly HttpTrigger _httpTrigger;
- public ActiveTaskTopic(HttpTrigger httpTrigger, SnowflakeId snowflakeId, IConverter converter, CoreAPIHttpService coreAPIHttpService,
- AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis,
- AzureServiceBusFactory serviceBus, IOptionsSnapshot<Option> option,
- IConfiguration configuration)
- {
- _azureCosmos = azureCosmos;
- _dingDing = dingDing;
- _azureStorage = azureStorage;
- _azureRedis = azureRedis;
- _serviceBus = serviceBus;
- _option = option?.Value;
- _configuration = configuration;
- _coreAPIHttpService = coreAPIHttpService;
- _converter = converter;
- _snowflakeId = snowflakeId;
- _httpTrigger = httpTrigger;
- }
- [Function("Exam")]
- public async Task ExamFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "exam", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- try
- {
- var json = JsonDocument.Parse(msg);
- json.RootElement.TryGetProperty("id", out JsonElement id);
- json.RootElement.TryGetProperty("progress", out JsonElement progress);
- json.RootElement.TryGetProperty("code", out JsonElement code);
- //Dictionary<string, object> keyValuePairs = mySbMsg.ToObject<Dictionary<string, object>>();
- var client = _azureCosmos.GetCosmosClient();
- ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{code}"));
- exam.progress = progress.ToString();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"{code}"));
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamBus()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.Status}\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamBus()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- }
- [Function("Vote")]
- public async Task VoteFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "vote", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- try
- {
- var jsonMsg = JsonDocument.Parse(msg);
- jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
- jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
- jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
- var client = _azureCosmos.GetCosmosClient();
- Vote vote = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Vote>(id.ToString(), new PartitionKey($"{code}"));
- vote.progress = progress.ToString();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(vote, id.ToString(), new PartitionKey($"{code}"));
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,VoteBus()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.Status}\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,VoteBus()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- }
- [Function("Correct")]
- public async Task CorrectFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "correct", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- try
- {
- var jsonMsg = JsonDocument.Parse(msg);
- jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
- jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
- jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
- var client = _azureCosmos.GetCosmosClient();
- Correct correct = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Correct>(id.ToString(), new PartitionKey($"{code}"));
- correct.progress = progress.ToString();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(correct, id.ToString(), new PartitionKey($"{code}"));
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Correct()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.Status}\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Correct()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- }
- [Function("Survey")]
- public async Task SurveyFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "survey", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- try
- {
- var jsonMsg = JsonDocument.Parse(msg);
- jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
- jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
- jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
- //Dictionary<string, object> keyValuePairs = mySbMsg.ToObject<Dictionary<string, object>>();
- var client = _azureCosmos.GetCosmosClient();
- Survey survey = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Survey>(id.ToString(), new PartitionKey($"{code}"));
- survey.progress = progress.ToString();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(survey, id.ToString(), new PartitionKey($"{code}"));
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,SurveyBus()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.Status}\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,SurveyBus()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- }
- [Function("Homework")]
- public async Task HomeworkFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "homework", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- try
- {
- var jsonMsg = JsonDocument.Parse(msg);
- jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
- jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
- jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
- var client = _azureCosmos.GetCosmosClient();
- Homework homework = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Homework>(id.ToString(), new PartitionKey($"{code}"));
- homework.progress = progress.ToString();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(homework, id.ToString(), new PartitionKey($"{code}"));
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Homework()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.Status}\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Homework()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- }
- [Function("Study")]
- public async Task StudyFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "study", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- string activityId = string.Empty;
- try
- {
- var jsonMsg = JsonDocument.Parse(msg);
- jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
- jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
- jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
- var client = _azureCosmos.GetCosmosClient();
- Study study = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Study>(id.ToString(), new PartitionKey($"{code}"));
- study.progress = progress.ToString();
- activityId = id.ToString();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(study, id.ToString(), new PartitionKey($"{code}"));
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Study()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.Status}\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Study()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- }
- [Function("Art")]
- public async Task ArtFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "art", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- string activityId = string.Empty;
- try
- {
- var jsonMsg = JsonDocument.Parse(msg);
- jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
- jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
- jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
- var client = _azureCosmos.GetCosmosClient();
- ArtEvaluation art = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ArtEvaluation>(id.ToString(), new PartitionKey($"{code}"));
- art.progress = progress.ToString();
- activityId = id.ToString();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(art, id.ToString(), new PartitionKey($"{code}"));
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Art()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.Status}\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Art()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- }
- [Function("ExamLite")]
- public async Task ExamLiteFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "examlite", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- try
- {
- var jsonMsg = JsonDocument.Parse(msg);
- jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
- jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
- jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
- var client = _azureCosmos.GetCosmosClient();
- ExamLite lite = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamLite>(id.ToString(), new PartitionKey($"{code}"));
- lite.progress = progress.ToString();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(lite, id.ToString(), new PartitionKey($"{code}"));
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamLite()-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.Status}\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamLite()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- }
- /// <param name="msg"></param>
- /// <returns></returns>
- [Function("TeacherTrainChange")]
- public async Task TeacherTrainChangeFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "teacher-train-change", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- var client = _azureCosmos.GetCosmosClient();
- var data = msg.ToObject<TeacherTrainChangeMsg>();
- List<TeacherTrain> trains = new List<TeacherTrain>();
- //redis锁
- bool lockKey = await _azureRedis.GetRedisClient(8).KeyExistsAsync($"Train:Statistics:Lock:{data.areaId}");
- if (!lockKey)
- {
- await _azureRedis.GetRedisClient(8).SetAddAsync($"Train:Statistics:Lock:{data.areaId}", new RedisValue(data.areaId));
- DateTime minutes = DateTime.UtcNow.AddMinutes(15); //15分钟
- await _azureRedis.GetRedisClient(8).KeyExpireAsync($"Train:Statistics:Lock:{data.areaId}", minutes);
- Area area = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<Area>($"{data.areaId}", new PartitionKey("Base-Area"));
- AreaSetting setting = null;
- if (area != null)
- {
- try
- {
- setting = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<AreaSetting>(area.id, new PartitionKey("AreaSetting"));
- }
- catch (CosmosException)
- {
- setting = null;
- }
- }
- if (setting == null)
- {
- setting = new AreaSetting
- {
- allTime = 50,
- classTime = 5,
- submitTime = 15,
- onlineTime = 20,
- offlineTime = 10,
- lessonMinutes = 45,
- };
- }
- foreach (var school in data.schools)
- {
- List<Study> studies = new List<Study>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common")
- .GetItemQueryIterator<Study>(queryText: $"select value(c) from c where c.owner<>'area' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Study-{school.school}") }))
- {
- studies.Add(item);
- }
- if (school.teachers.Any())
- {
- string trainSql = $"select value(c) from c where c.id in ({string.Join(",", school.teachers.Select(x => $"'{x}'"))}) ";
- await foreach (var item in client.GetContainer("TEAMModelOS", Constant.Teacher)
- .GetItemQueryIterator<TeacherTrain>(queryText: trainSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"TeacherTrain-{school.school}") }))
- {
- trains.Add(item);
- }
- }
- await StatisticsService.GetStatisticsTeacher(trains, setting, area, client, studies);
- }
- area.updateTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- await client.GetContainer(Constant.TEAMModelOS, "Normal").ReplaceItemAsync<Area>(area, $"{data.areaId}", new PartitionKey("Base-Area"));
- }
- }
- /// <param name="msg"></param>
- /// <returns></returns>
- //[Function("TeacherTrainChange")]
- public async Task TeacherTrainChangeFuncBak([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "teacher-train-change", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- try
- {
- TeacherTrainChange change = msg.ToObject<TeacherTrainChange>();
- if (change.update == null || change.update.Count <= 0 || change.tmdids.IsEmpty())
- {
- return;
- }
- var client = _azureCosmos.GetCosmosClient();
- string insql = $"where c.id in ({string.Join(",", change.tmdids.Select(x => $"'{x}'"))})";
- string selsql = $"select value(c) from c {insql} ";
- List<TeacherTrain> teacherTrains = new List<TeacherTrain>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<TeacherTrain>(queryText: selsql,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"TeacherTrain-{change.school}") }))
- {
- teacherTrains.Add(item);
- }
- if (change.statistics != 1)
- {
- List<Task<ItemResponse<TeacherTrain>>> task = new List<Task<ItemResponse<TeacherTrain>>>();
- teacherTrains.ForEach(x =>
- {
- x.update.UnionWith(change.update);
- task.Add(client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<TeacherTrain>(x, x.id, new PartitionKey($"TeacherTrain-{change.school}")));
- });
- await task.TaskPage(5);
- var unchange = change.tmdids.Except(teacherTrains.Select(x => x.id));
- if (unchange != null)
- {
- task.Clear();
- unchange.ToList().ForEach(x =>
- {
- TeacherTrain teacherTrain = new TeacherTrain
- {
- pk = "TeacherTrain",
- id = x,
- code = $"TeacherTrain-{change.school}",
- tmdid = x,
- school = change.school,
- update = new HashSet<string> { StatisticsService.TeacherAbility,
- StatisticsService.TeacherClass, StatisticsService.OfflineRecord }
- };
- teacherTrain.update.UnionWith(change.update);
- task.Add(client.GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync<TeacherTrain>(teacherTrain, new PartitionKey($"TeacherTrain-{change.school}")));
- });
- await task.TaskPage(1);
- }
- }
- else
- {
- Area area = null;
- string sql = $"select value(c) from c where c.standard='{change.standard}'";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<Area>(queryText: sql,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-Area") }))
- {
- area = item;
- }
- AreaSetting setting = null;
- if (area != null)
- {
- try
- {
- setting = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<AreaSetting>(change.school, new PartitionKey("AreaSetting"));
- }
- catch (CosmosException)
- {
- try
- {
- setting = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<AreaSetting>(area.id, new PartitionKey("AreaSetting"));
- }
- catch (CosmosException)
- {
- setting = null;
- }
- }
- }
- if (setting == null)
- {
- setting = new AreaSetting
- {
- allTime = 50,
- classTime = 5,
- submitTime = 15,
- onlineTime = 20,
- offlineTime = 10,
- lessonMinutes = 45,
- };
- }
- List<Task<TeacherTrain>> task = new List<Task<TeacherTrain>>();
- teacherTrains.ForEach(x =>
- {
- x.update.UnionWith(change.update);
- task.Add(StatisticsService.StatisticsTeacher(x, setting, area, client, null));
- });
- await task.TaskPage(1);
- var unchange = change.tmdids.Except(teacherTrains.Select(x => x.id));
- if (unchange != null)
- {
- task.Clear();
- unchange.ToList().ForEach(x =>
- {
- task.Add(StatisticsService.StatisticsTeacher(new TeacherTrain
- {
- pk = "TeacherTrain",
- id = x,
- code = $"TeacherTrain-{change.school}",
- tmdid = x,
- school = change.school,
- update = new HashSet<string> { StatisticsService.TeacherAbility,
- StatisticsService.TeacherClass, StatisticsService.OfflineRecord }
- }, setting, area, client, null));
- });
- await task.TaskPage(1);
- }
- }
- }
- catch (CosmosException ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-研修数据变更,重新统计-TeacherTrainChange\n{msg}\n{ex.Message}\n{ex.StackTrace}\nCosmosException{ex.Status}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-研修数据变更,重新统计-TeacherTrainChange\n{msg}\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- }
- }
- /// <summary>
- /// 完善课程变更,StuListChange, originCode是学校编码 则表示名单是学校自定义名单,如果是tmdid则表示醍摩豆的私有名单,scope=school,private。
- /// </summary>
- /// <data msg>
- /// CourseChange
- ///// </data>
- /// <param name="msg"></param>
- /// <returns></returns>
- [Function("GroupChange")]
- public async Task GroupChangeFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "group-change", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- var client = _azureCosmos.GetCosmosClient();
- try
- {
- //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-名单成员变更-GroupChange\n{msg}", GroupNames.醍摩豆服務運維群組);
- //await _dingDing.SendBotMsg($"名单变化{msg}", GroupNames.成都开发測試群組);
- var jsonMsg = JsonDocument.Parse(msg);
- GroupChange groupChange = msg.ToObject<GroupChange>();
- //名单变动修改学生课程关联信息
- //await StuListService.FixStuCourse(client, stuListChange);
- //Vote投票 Survey问卷 Exam评测 Learn学习活动 Homework作业活动
- //名单变动修改学生问卷关联信息
- await IESActivityService.FixActivity(client, _dingDing, groupChange, "Survey");
- //名单变动修改学生投票关联信息
- await IESActivityService.FixActivity(client, _dingDing, groupChange, "Vote");
- //名单变动修改学生评测关联信息
- await IESActivityService.FixActivity(client, _dingDing, groupChange, "Exam");
- //名单变动修改学生研修关联信息
- await IESActivityService.FixActivity(client, _dingDing, groupChange, "Study");
- //名单变动修改学生简易评测关联信息
- await IESActivityService.FixActivity(client, _dingDing, groupChange, "ExamLite");
- //名单变动修改学生作业活动信息
- await IESActivityService.FixActivity(client, _dingDing, groupChange, "Homework");
- //名单变动修改学生艺术评价活动信息
- await IESActivityService.FixActivity(client, _dingDing, groupChange, "Art");
- //TODO学习活动
- //await FixActivity(client, stuListChange, "Learn");
- if (groupChange.type == null || !groupChange.type.Equals("research") || !groupChange.type.Equals("yxtrain") || !groupChange.type.Equals("activity"))
- {
- //课程名单变动修改学生课程关联信息
- await IESActivityService.FixStuCourse(client, _dingDing, groupChange);
- //名单变动修改课例关联信息
- //await ActivityService.FixLessonRecord(client, _dingDing, groupChange);
- }
- if (groupChange.type.Equals("class") || groupChange.type.Equals("teach") || groupChange.type.Equals("student"))
- {
- await _httpTrigger.RequestHttpTrigger(new { data = groupChange }, Environment.GetEnvironmentVariable("Option:Location"), "webhook/group-member-change");
- if (groupChange.stujoin.Count > 0)
- await BIStats.SetTypeAddStats(client, _dingDing, groupChange.school, "Student", groupChange.stujoin.Count);//BI统计增/减量
- if (groupChange.stuleave.Count > 0)
- await BIStats.SetTypeAddStats(client, _dingDing, groupChange.school, "Student", -groupChange.stuleave.Count);//BI统计增/减量
- }
- if ((groupChange.type.Equals("class") || groupChange.type.Equals("teach") || groupChange.type.Equals("student")) && "school".Equals(groupChange.scope) && "upsert".Equals(groupChange.status) && !string.IsNullOrWhiteSpace(groupChange.school)) {
-
- var data = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, new List<string> { groupChange.listid }, groupChange.school);
- if (data.groups.IsNotEmpty()) {
- School school = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(groupChange.school, new PartitionKey("Base"));
-
- //
- var period = school.period.Find(z => z.id.Equals(data.groups.First().periodId));
- if (period != null)
- {
- var dataSemester = SchoolService.GetSemester(period,DateTimeOffset.Now.ToUnixTimeMilliseconds());
- string id = $"{dataSemester.studyYear}-{dataSemester.currSemester.id}-{data.groups.First().id}";
- string code = $"GroupListSemester-{groupChange.school}";
- GroupListSemester groupListSemester = data.groups.First().ToJsonString().ToObject<GroupListSemester>();
- groupListSemester.id = id ;
- groupListSemester.code = code ;
- groupListSemester.pk="GroupListSemester";
- groupListSemester.semesterId=dataSemester.currSemester.id;
- groupListSemester.groupListId=data.groups.First().id ;
- groupListSemester.studyYear=dataSemester.studyYear;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync<GroupListSemester>(groupListSemester, new PartitionKey(groupListSemester.code));
- }
- }
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-GroupChange\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- }
- //接收死信消息
- [Function("ItemCondDel")]
- public async Task ItemCondDelFunc([ServiceBusTrigger("%Azure:ServiceBus:ItemCondQueue%/$DeadLetterQueue", Connection = "Azure:ServiceBus:ConnectionString")] string message)
- {
- await _dingDing.SendBotMsg($"{message}", GroupNames.成都开发測試群組);
- }
- [Function("ItemCond")]
- public async Task ItemCondFunc([ServiceBusTrigger("%Azure:ServiceBus:ItemCondQueue%", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- var jsonMsg = JsonDocument.Parse(msg);
- List<ItemCondDto> itemCondDtos = msg.ToObject<List<ItemCondDto>>();
- foreach (var itemCondDto in itemCondDtos)
- {
- if (itemCondDto.scope.Equals("school"))
- {
- ItemCond itemCond = null;
- List<ItemInfo> items = new List<ItemInfo>();
- 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 ";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{itemCondDto.key}") }))
- {
- items.Add(item);
- }
- itemCond = new ItemCond()
- {
- id = $"{itemCondDto.filed}",
- code = $"ItemCond-{itemCondDto.key}",
- pk = "ItemCond",
- ttl = -1,
- count = items.Count,
- grades = new List<GradeCount>(),
- subjects = new List<SubjectItemCount>()
- };
- items.ForEach(z =>
- {
- if (!string.IsNullOrEmpty(z.type))
- {
- ItemService.CountItemCond(z, null, itemCond);
- }
- });
- await _azureRedis.GetRedisClient(8).HashSetAsync($"ItemCond:{itemCondDto.key}", $"{itemCondDto.filed}", itemCond.ToJsonString());
- }
- else
- {
- ItemCond itemCond = null;
- List<ItemInfo> items = new List<ItemInfo>();
- var queryslt = $"SELECT c.gradeIds,c.subjectId,c.periodId,c.type,c.level,c.field ,c.scope FROM c where c.pid= null ";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{itemCondDto.filed}") }))
- {
- items.Add(item);
- }
- itemCond = new ItemCond() { id = $"{itemCondDto.filed}", code = $"ItemCond", pk = "ItemCond", ttl = -1, count = items.Count };
- items.ForEach(z =>
- {
- if (!string.IsNullOrEmpty(z.type))
- {
- ItemService.CountItemCond(z, null, itemCond);
- }
- });
- await _azureRedis.GetRedisClient(8).HashSetAsync($"ItemCond:ItemCond", $"{itemCondDto.filed}", itemCond.ToJsonString());
- }
- }
- }
- catch (CosmosException ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ItemCond()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ItemCond()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- }
- [Function("GenPdf")]
- public async Task GenPdfFunc([ServiceBusTrigger("%Azure:ServiceBus:GenPdfQueue%", Connection = "Azure:ServiceBus:ConnectionString", IsBatched = false)] string msg)
- {
- //https://github.com/aafgani/AzFuncWithServiceBus/blob/a0da42f59b5fc45655b73b85bae932e84520db70/ServiceBusTriggerFunction/host.json
- // messageHandlerOptions 设置
- JsonElement element = msg.ToObject<JsonElement>();
- // https://dotblogs.com.tw/yc421206/2013/04/25/102300 // C# 原子操作。Interlocked
- // ConcurrentQueue http://t.zoukankan.com/hohoa-p-12622459.html
- switch (true)
- {
- case bool when element.TryGetProperty("bizType", out JsonElement _bizType) && $"{_bizType}".Equals("OfflineRecord"):
- //处理教师线下研修报告的生成。
- //await GenOfflineRecordPdf(element, msg);
- break;
- case bool when element.TryGetProperty("bizType", out JsonElement _bizType) && $"{_bizType}".Equals("ArtStudentPdf"):
- await GenArtStudentPdf(element, msg);
- break;
- }
- }
- private async Task GenArtStudentPdf(JsonElement json, string msg)
- {
- try
- {
- json.TryGetProperty("studentIds", out JsonElement _studentIds);
- json.TryGetProperty("artId", out JsonElement _artId);
- json.TryGetProperty("schoolCode", out JsonElement _schoolId);
- json.TryGetProperty("headLang", out JsonElement headLang);
- List<string> studentIds = _studentIds.ToObject<List<string>>();
- string _schoolCode = $"{_schoolId}";
- (List<ArtStudentPdf> studentPdfs, List<StudentArtResult> artResults) = await ArtService.GenStuArtPDF(studentIds, $"{_artId}", $"{_schoolId}", $"{headLang}", _azureCosmos, _coreAPIHttpService, _dingDing);
- foreach (var artResult in artResults)
- {
- if (artResult.pdf == null || string.IsNullOrWhiteSpace(artResult.pdf.blob) || string.IsNullOrWhiteSpace(artResult.pdf.url))
- {
- artResult.pdf = new Attachment
- {
- // name = $"{artResult.studentId}.pdf",
- extension = "pdf",
- type = "doc",
- cnt = artResult.school,
- prime = false,//此处的作用是判断是否已经生成OK.
- };
- }
- else
- {
- artResult.pdf.prime = false;//此处的作用是判断是否已经生成OK.
- }
- await _azureRedis.GetRedisClient(8).HashSetAsync($"ArtPDF:{_artId}", artResult.studentId, artResult.ToJsonString());
- }
- //2个小时。
- await _azureRedis.GetRedisClient(8).KeyExpireAsync($"ArtPDF:{_artId}", new TimeSpan(2, 0, 0));
- List<Task<string>> uploads = new List<Task<string>>();
- studentPdfs.ForEach(x => {
- x.blob = $"art/{x.artId}/report/{x.studentId}.json";
- uploads.Add(_azureStorage.GetBlobContainerClient($"{_schoolCode}").UploadFileByContainer(x.ToJsonString(), "art", $"{x.artId}/report/{x.studentId}.json", true));
- });
- var uploadJsonUrls = await Task.WhenAll(uploads);
- var list = uploadJsonUrls.ToList();
- List<string> urls = new List<string>();
- (string uri, string sas) = _azureStorage.GetBlobContainerSAS($"{_schoolCode}", Azure.Storage.Sas.BlobContainerSasPermissions.Read);
- studentPdfs.ForEach(x => {
- string atrUrl = "https://teammodelos.blob.core.chinacloudapi.cn/0-public/art-report-template/report.html";
- var s = _azureStorage.GetBlobSAS($"{_schoolCode}", x.blob, BlobSasPermissions.Read);
- s = $"{HttpUtility.UrlEncode($"{s}", Encoding.UTF8)}";
- string url = $"{atrUrl}?url={s}&pdfpath={x.artId}/report/{x.studentId}";
- urls.Add(url);
- });
- string env = "release";
- if (Environment.GetEnvironmentVariable("Option:Location").Contains("Test", StringComparison.CurrentCultureIgnoreCase) ||
- Environment.GetEnvironmentVariable("Option:Location").Contains("Dep", StringComparison.CurrentCultureIgnoreCase))
- {
- env = "develop";
- }
- if (urls.Count <= psize)
- {
- var screenshot = new ScreenshotDto
- {
- msgId = Guid.NewGuid().ToString(),
- width = 1080,
- height = 1920,
- urls = urls,
- fileNameKey = "pdfpath",
- cnt = $"{_schoolCode}",
- root = "art",
- pagesize = 5,
- env = env
- };
- var message = new ServiceBusMessage(screenshot.ToJsonString());
- await _serviceBus.GetServiceBusClient().SendMessageAsync("screenpdf", message);
- }
- else
- {
- int pages = (urls.Count + psize) / psize;
- for (int i = 0; i < pages; i++)
- {
- var lists = urls.Skip((i) * psize).Take(psize).ToList();
- var screenshot = new ScreenshotDto
- {
- msgId = Guid.NewGuid().ToString(),
- width = 1080,
- height = 1920,
- urls = lists,
- fileNameKey = "pdfpath",
- cnt = $"{_schoolCode}",
- root = "art",
- pagesize = 5,
- env = env
- };
- var message = new ServiceBusMessage(screenshot.ToJsonString());
- await _serviceBus.GetServiceBusClient().SendMessageAsync("screenpdf", message);
- }
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
- }
- }
- private async Task GenOfflineRecordPdf(JsonElement element, string msg)
- {
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- /* var jsonMsg = JsonDocument.Parse(msg);
- jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
- //jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);*/
- element.TryGetProperty("id", out JsonElement ids);
- List<string> tIds = ids.ToObject<List<string>>();
- element.TryGetProperty("school", out JsonElement _code);
- string code = "";
- element.TryGetProperty("Key", out JsonElement key);
- if (string.IsNullOrWhiteSpace($"{_code}"))
- {
- code = $"{key}";
- }
- else
- {
- code = $"{_code}";
- }
- if (string.IsNullOrWhiteSpace(code))
- {
- await _dingDing.SendBotMsg($"校本研修生成PDF时,学校id为空\n{msg}", GroupNames.成都开发測試群組);
- return;
- }
- string sname = string.Empty;
- string areaId = string.Empty;
- School school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{code}", new PartitionKey("Base"));
- sname = school.name;
- areaId = school.areaId;
- //var scquery = $"SELECT c.name,c.areaId from c where c.id = '{code}'";
- //await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: scquery, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
- //{
- // using var json = await JsonDocument.ParseAsync(item.ContentStream);
- // if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- // {
- // var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- // while (accounts.MoveNext())
- // {
- // JsonElement account = accounts.Current;
- // sname = account.GetProperty("name").ToString();
- // areaId = account.GetProperty("areaId").ToString();
- // }
- // }
- //}
- if (string.IsNullOrWhiteSpace(areaId))
- {
- await _dingDing.SendBotMsg($"校本研修生成PDF时,区级id为空\n{msg}", GroupNames.成都开发測試群組);
- return;
- }
- if (!tIds.Any())
- {
- return;
- }
- var blobclient = _azureStorage.GetBlobContainerClient($"teammodelos");
- //查询当前学校所有的校本研修活动
- List<Study> studies = new();
- 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)";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<Study>(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Study-{code}") }))
- {
- studies.Add(item);
- }
- //List<string> tcs = new();
- //foreach (var item in studies)
- //{
- // foreach (var td in item.tchLists)
- // {
- // if (!tcs.Contains(td))
- // {
- // tcs.Add(td);
- // }
- // }
- //}
- HashSet<string> tcs = studies.SelectMany(x => x.tchLists).Where(y => !string.IsNullOrWhiteSpace(y)).ToHashSet();
- (List<RMember> tchList, List<RGroupList> classInfos) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, tcs.ToList(), code, null);
- foreach (string id in tIds)
- {
- StringBuilder stringBuilder = new StringBuilder();
- string cname = string.Empty;
- string gname = string.Empty;
- if (tchList.Exists(c => c.id == id))
- {
- gname = tchList.Where(c => c.id == id).FirstOrDefault().groupName;
- cname = tchList.Where(c => c.id == id).FirstOrDefault().name;
- }
- List<string> details = new();
- foreach (Study study in studies)
- {
- if (!study.teacIds.Contains(id))
- {
- continue;
- }
- var sresponse = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(study.id, new PartitionKey($"StudyRecord-{id}"));
- if (sresponse.Status == 200)
- {
- var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
- StudyRecord record = json.ToObject<StudyRecord>();
- if (record.status == 1)
- {
- var start = DateTimeHelper.FromUnixTimestamp(study.startTime).ToString("yyyy/MM/dd");
- var end = DateTimeHelper.FromUnixTimestamp(study.endTime).ToString("yyyy/MM/dd");
- string tname = string.Empty;
- List<string> setName = new();
- foreach (string setting in study.settings)
- {
- if (setting.Equals("sign"))
- {
- setName.Add("扫码签到");
- }
- else if (setting.Equals("hw"))
- {
- setName.Add("作业提交");
- }
- else if (setting.Equals("survey"))
- {
- setName.Add("问卷反馈");
- }
- else if (setting.Equals("exam"))
- {
- setName.Add("评测活动");
- }
- }
- switch (study.type)
- {
- case 1:
- tname = "信息化教学案例展示与分享";
- break;
- case 2:
- tname = "专家专题培训";
- break;
- case 3:
- tname = "同课同构";
- break;
- case 4:
- tname = "同课异构";
- break;
- case 5:
- tname = "校本2.0培训";
- break;
- case 6:
- tname = "自定义活动";
- break;
- };
- stringBuilder.Append($@"<tr>
- <td> {study.topic} </td>
- <td> {tname} </td >
- <td> {study.hour} </td >
- <td> {study.hour} </td >
- <td> {start} 到 {end} </td>
- <td>{study.desc}</td>
- <td> {string.Join("、", setName.Select(x => $"{x}\n"))} </td>
- <td> 已完成 </td >
- </tr> ");
- }
- else
- {
- continue;
- }
- }
- else
- {
- continue;
- }
- }
- string url = await StudyService.GenPdf(id, areaId, cname, sname, gname, stringBuilder.ToString(), _converter, _azureStorage, _dingDing);
- Azure.Response teacherTrainRes = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemStreamAsync(id, new PartitionKey($"TeacherTrain-{code}"));
- if (teacherTrainRes.Status == 200)
- {
- TeacherTrain teacherTrain = JsonDocument.Parse(teacherTrainRes.Content).RootElement.Deserialize<TeacherTrain>();
- try
- {
- BlobDownloadInfo blobDownload = await blobclient.GetBlobClient(url).DownloadAsync(range: new HttpRange(0, 4 * 1048576), rangeGetContentHash: true);
- if (blobDownload.Details.ContentHash != null)
- {
- string hash = Md5Hash.GetbyteToString(blobDownload.Details.ContentHash);
- teacherTrain.offlineReport = new Attachment
- {
- hash = hash,
- url = url,
- blob = $"{blobclient.Uri}/{url}",
- extension = "pdf",
- name = $"{teacherTrain.nickname}-校本研修汇总报告.pdf",
- type = "doc",
- size = blobDownload.ContentLength
- };
- await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync<TeacherTrain>(teacherTrain, id, new PartitionKey($"TeacherTrain-{code}"));
- }
- }
- catch
- {
- }
- }
- }
- /*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}') )";
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<Study>(queryText: query, requestOptions: new QueryRequestOptions() {PartitionKey = new PartitionKey($"Study-{code}") }))
- {
- studies.Add(item);
- }*/
- //(List<StuActivity> datas, string continuationToken) = await ActivityStudentService.FindActivity(element, null, null, _azureCosmos, _azureRedis);
- // string blob = await StudyService.GenPdf(cname,sname,gname,"", _converter);
- }
- catch (CosmosException ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,GenPdfFunc()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,GenPdfFunc()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- }
- //更新學校產品一覽表
- //處理內容:取得所有序號購買紀錄,服務週期、硬體購買紀錄後,更新ProductSum
- [Function("Product")]
- public async Task ProductFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "product", Connection = "Azure:ServiceBus:ConnectionString")] string msg, ILogger log)
- {
- try
- {
- var jsonMsg = JsonDocument.Parse(msg);
- jsonMsg.RootElement.TryGetProperty("method", out JsonElement method);
- jsonMsg.RootElement.TryGetProperty("schoolId", out JsonElement schoolId);
- jsonMsg.RootElement.TryGetProperty("prodCode", out JsonElement prodCode);
- jsonMsg.RootElement.TryGetProperty("prodId", out JsonElement prodId);
- var client = _azureCosmos.GetCosmosClient();
- string strQuery = string.Empty;
- //取得所有學校產品
- ////序號
- List<SchoolProductSumData> serialsProductSumOrg = new List<SchoolProductSumData>();
- strQuery = $"SELECT * FROM c WHERE c.dataType = 'serial'";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Product-{schoolId}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- SchoolProductSerial serialInfo = obj.ToObject<SchoolProductSerial>();
- SchoolProductSumData serialProd = serialsProductSumOrg.Where(sp => sp.prodCode == serialInfo.prodCode).FirstOrDefault();
- if (serialProd == null)
- {
- SchoolProductSumData serialProdAdd = new SchoolProductSumData();
- serialProdAdd.prodCode = serialInfo.prodCode;
- serialProdAdd.ids.Add(serialInfo.id);
- serialProdAdd.avaliable = serialProdAdd.ids.Count;
- serialsProductSumOrg.Add(serialProdAdd);
- }
- else
- {
- if (!serialProd.ids.Contains(serialInfo.id))
- {
- serialProd.ids.Add(serialInfo.id);
- }
- serialProd.avaliable = serialProd.ids.Count;
- }
- }
- }
- }
- ////服務
- List<SchoolProductSumDataService> servicesProductSumOrg = new List<SchoolProductSumDataService>();
- //////取得學校產品 授權週期:授權中 條件: startDate <= now <= endDate
- long timestampToday = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
- string strQueryM = $"SELECT * FROM c WHERE c.dataType = 'servicePeriod' AND c.startDate <= {timestampToday} AND {timestampToday} <= c.endDate AND c.ttl < 0";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQueryM, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Product-{schoolId}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- SchoolProductServicePeriod servicePeriodInfo = obj.ToObject<SchoolProductServicePeriod>();
- SchoolProductSumDataService serviceProd = servicesProductSumOrg.Where(sp => sp.prodCode == servicePeriodInfo.prodCode).FirstOrDefault();
- if (serviceProd == null)
- {
- SchoolProductSumDataService serviceProdAdd = new SchoolProductSumDataService();
- serviceProdAdd.prodCode = servicePeriodInfo.prodCode;
- serviceProdAdd.avaliable = 0;
- serviceProdAdd.ids.Add(servicePeriodInfo.id);
- serviceProdAdd.avaliable += servicePeriodInfo.number;
- serviceProdAdd.startDate = servicePeriodInfo.startDate;
- serviceProdAdd.endDate = servicePeriodInfo.endDate;
- servicesProductSumOrg.Add(serviceProdAdd);
- }
- else
- {
- serviceProd.ids = new List<string>();
- serviceProd.ids.Add(servicePeriodInfo.id);
- serviceProd.startDate = servicePeriodInfo.startDate;
- serviceProd.endDate = servicePeriodInfo.endDate;
- }
- }
- }
- }
- ////服務產品特別對應項
- School school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{schoolId}", new PartitionKey("Base")); //學校基本資料取得
- bool updSchool = false; //是否變更學校基本資料
- int chgSchSizeCnt = 0; //變更學校空間的次數 若為0表示現時間點沒有任何空間可使用 => 回復學校空間為初始值
- int schoolDefaultSize = 1; //學校空間初始值:1
- if (!string.IsNullOrWhiteSpace(school.id))
- {
- if (servicesProductSumOrg.Count > 0)
- {
- foreach (SchoolProductSumDataService servicesProductSumOrgRow in servicesProductSumOrg)
- {
- //更新學校空間
- if (servicesProductSumOrgRow.prodCode.Equals("IPALJ6NY"))
- {
- school.size = (servicesProductSumOrgRow.avaliable < 1) ? 1 : servicesProductSumOrgRow.avaliable;
- await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, $"{schoolId}", new PartitionKey("Base"));
- updSchool = true;
- chgSchSizeCnt++;
- }
- }
- }
- if (chgSchSizeCnt.Equals(0) && !school.size.Equals(schoolDefaultSize))
- {
- school.size = schoolDefaultSize;
- //updSchool = true; //關於學校空間初始式樣未定,目前暫定:若需要Reset空間,則先維持原空間數不更動
- updSchool = false;
- }
- }
- //變更學校基本資料
- if (updSchool)
- {
- await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, $"{schoolId}", new PartitionKey("Base"));
- }
- ////硬體
- List<SchoolProductSumDataHard> hardsProductSumOrg = new List<SchoolProductSumDataHard>();
- strQuery = $"SELECT * FROM c WHERE c.dataType = 'hard'";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Product-{schoolId}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- SchoolProductHard hardInfo = obj.ToObject<SchoolProductHard>();
- SchoolProductSumData hardProd = hardsProductSumOrg.Where(sp => sp.prodCode == hardInfo.prodCode).FirstOrDefault();
- if (hardProd == null)
- {
- SchoolProductSumDataHard hardProdAdd = new SchoolProductSumDataHard();
- hardProdAdd.prodCode = hardInfo.prodCode;
- hardProdAdd.model = hardInfo.model;
- hardProdAdd.ids.Add(hardInfo.id);
- hardProdAdd.avaliable = hardProdAdd.ids.Count;
- hardsProductSumOrg.Add(hardProdAdd);
- }
- else
- {
- if (!hardProd.ids.Contains(hardInfo.id))
- {
- hardProd.ids.Add(hardInfo.id);
- }
- hardProd.avaliable = hardProd.ids.Count;
- }
- }
- }
- }
- //更新學校產品一覽表
- SchoolProductSum prodSum = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolProductSum>(schoolId.ToString(), new PartitionKey($"ProductSum"));
- prodSum.serial = serialsProductSumOrg;
- prodSum.service = servicesProductSumOrg;
- prodSum.hard = hardsProductSumOrg;
- await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolProductSum>(prodSum, prodSum.id, new PartitionKey($"{prodSum.code}"));
- }
- catch (CosmosException ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Product()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Product()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- }
- /// <summary>
- /// 批量复制文件
- /// </summary>
- /// <param name="msg"></param>
- /// <returns></returns>
- ///[Function("CopyStandardFile")] 弃用
- public async Task BatchCopyBlobFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "copy-standard-file", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- try
- {
- //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-Blob复制文件-CopyStandardFile\n{msg}", GroupNames.醍摩豆服務運維群組);
- var jsonMsg = JsonDocument.Parse(msg);
- BatchCopyFile bIBatchCopyFile = msg.ToObject<BatchCopyFile>();
- //批量复制文件
- var result = await BatchCopyFileService.CopyFile(_dingDing, _azureStorage, bIBatchCopyFile);
- if (result == 200)
- {
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-Blob复制文件-CopyStandardFile\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- }
- /// <summary>
- /// 更新开课数据事件
- /// </summary>
- /// <param name="msg"></param>
- /// <returns></returns>
- [Function("LessonRecordEvent")]
- public async Task LessonRecordFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "lesson-record-event", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- JsonElement data = msg.ToObject<JsonElement>();
- string scope = "";
- string tmdid = "";
- string lessonId;
- string school;
- string tbname;
- string code;
- string blobname;
- List<LessonUpdate> updates = new List<LessonUpdate>();
- //更新课堂记录
- if (data.TryGetProperty("lesson_id", out JsonElement _lessonId) && !string.IsNullOrEmpty($"{_lessonId}"))
- {
- if (!data.TryGetProperty("tmdid", out JsonElement _tmdid)) return;
- if (!data.TryGetProperty("scope", out JsonElement _scope)) return;
- if (!data.TryGetProperty("grant_types", out JsonElement _grant_types)) return;
- data.TryGetProperty("school", out JsonElement _school);
- school = $"{_school}";
- scope = $"{_scope}";
- tmdid = $"{_tmdid}";
- lessonId = $"{_lessonId}";
- updates = _grant_types.ToObject<List<LessonUpdate>>();
- }//创建课堂记录
- else if (data.TryGetProperty("id", out JsonElement _id) && !string.IsNullOrEmpty($"{_id}")
- && data.TryGetProperty("tmdid", out JsonElement _tmdid) && !string.IsNullOrEmpty($"{_tmdid}")
- && data.TryGetProperty("scope", out JsonElement _scope) && !string.IsNullOrEmpty($"{_scope}"))
- {
- data.TryGetProperty("school", out JsonElement _school);
- school = $"{_school}";
- scope = $"{_scope}";
- tmdid = $"{_tmdid}";
- lessonId = $"{_id}";
- updates.Add(new LessonUpdate { grant_type = "create" });
- }//删除课堂记录
- else if (data.TryGetProperty("delete_id", out JsonElement _delete_id) && !string.IsNullOrEmpty($"{_delete_id}")
- && data.TryGetProperty("tmdid", out JsonElement _dtmdid) && !string.IsNullOrEmpty($"{_dtmdid}")
- && data.TryGetProperty("scope", out JsonElement _dscope) && !string.IsNullOrEmpty($"{_dscope}")
- && data.TryGetProperty("opt", out JsonElement _opt) && !string.IsNullOrEmpty($"{_opt}"))
- {
- data.TryGetProperty("school", out JsonElement _dschool);
- school = $"{_dschool}";
- if ($"{_opt}".Equals("delete"))
- {
- scope = $"{_dscope}";
- tmdid = $"{_dtmdid}";
- lessonId = $"{_delete_id}";
- updates.Add(new LessonUpdate { grant_type = "delete" });
- }
- else { return; }
- }
- else
- {
- return;
- }
- //if (!string.IsNullOrWhiteSpace(school) && school.Equals("habook"))
- //{
- // await _dingDing.SendBotMsg($"研发学校课堂记录事件触发:\n{msg}", GroupNames.成都开发測試群組);
- //}
- var client = _azureCosmos.GetCosmosClient();
- if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
- {
- blobname = $"{school}";
- code = $"LessonRecord-{school}";
- tbname = "School";
- }
- else if ($"{scope}".Equals("private"))
- {
- blobname = $"{tmdid}";
- code = $"LessonRecord";
- tbname = "Teacher";
- }
- else
- {
- return;
- }
- LessonDis lessonDis = new LessonDis();
- List<LessonUpdate> msgs = new List<LessonUpdate>();
- try
- {
- LessonRecord oldlessonRecord = null;
- LessonRecord lessonRecord = null;
- Azure.Response response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
- if (response.Status == 200)
- {
- var doc = JsonDocument.Parse(response.ContentStream);
- lessonRecord = doc.RootElement.ToObject<LessonRecord>();
- oldlessonRecord = doc.RootElement.ToObject<LessonRecord>();
- }
- else
- {
- lessonRecord = null;
- }
- bool isReplace = true;
- if (updates.IsNotEmpty())
- {
- Teacher teacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>(tmdid, new PartitionKey("Base"));
- foreach (LessonUpdate update in updates)
- {
- switch (update.grant_type)
- {
- //更新课堂时长
- case "up-duration":
- double.TryParse($"{update.data}", out double duration);
- lessonRecord.duration = duration;
- msgs.Add(update);
- try
- {
- BlobDownloadResult Recording = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"records/{_lessonId}/Record/.Recording.json").DownloadContentAsync();
- var RecordingJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(Recording.Content.ToString()))).RootElement;
- if (RecordingJson.TryGetProperty("duration", out JsonElement _duration) && _duration.ValueKind.Equals(JsonValueKind.Number))
- {
- var durationFile = double.Parse($"{_duration}");
- if (duration < durationFile)
- {
- lessonRecord.duration = durationFile;
- }
- }
- if (RecordingJson.TryGetProperty("streamUrl", out JsonElement _streamUrl) && !string.IsNullOrWhiteSpace($"{_streamUrl}"))
- {
- lessonRecord.hasVideo = 1;
- }
- }
- catch (Exception ex)
- {
- // await _dingDing.SendBotMsg($"{_option.Location}/LessonRecordEvent/课堂记录更新课堂时长出错records/{_lessonId}/Record/.Recording.json\n{ex.Message}\n{ex.StackTrace}{msg}", GroupNames.醍摩豆服務運維群組);
- }
- isReplace = true;
- break;
- //更新T分
- case "up-tScore":
- var tScore = int.Parse($"{update.data}");
- lessonRecord.tScore = tScore;
- msgs.Add(update);
- break;
- //更新课P分
- case "up-pScore":
- var pScore = int.Parse($"{update.data}");
- lessonRecord.pScore = pScore;
- msgs.Add(update);
- break;
- //更新 学生人数
- case "up-mCount":
- var mCount = int.Parse($"{update.data}");
- lessonRecord.mCount = mCount;
- msgs.Add(update);
- break;
- //更新 议课次数
- case "up-techCount":
- var techCount = int.Parse($"{update.data}");
- lessonRecord.mCount = techCount;
- msgs.Add(update);
- break;
- //更新 基础统计信息
- case "up-base":
- //读取TimeLine.json
- List<int> PickupMemberIds = new List<int>();
- try
- {
- BlobDownloadResult timeLineBlobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/TimeLine.json").DownloadContentAsync();
- TimeLineData timeLineData = timeLineBlobDownload.Content.ToObjectFromJson<TimeLineData>();
- lessonRecord.hitaClientCmpCount = timeLineData.events.Where(z => !string.IsNullOrWhiteSpace(z.WrkCmpSrcType) && z.WrkCmpSrcType.Equals("HitaClientCmp")).Count();
- //lessonRecord.collateTaskCount = lessonRecord.hitaClientCmpCount;
- List<TimeLineEvent> timeLineEvents = timeLineData.events.FindAll(z => !string.IsNullOrWhiteSpace(z.Event) && z.Event.Equals("PickupResult"));
- if (timeLineEvents.IsNotEmpty()) {
- foreach (var timeLineEvent in timeLineEvents) {
- var memberIds= timeLineEvent.PickupMemberId.ToObject<List<int>>();
- PickupMemberIds.AddRange(memberIds);
- }
- }
- }
- catch (Exception ex)
- {
- if (!ex.Message.Contains("The specified blob does not exist"))
- {
- await _dingDing.SendBotMsg($"{_option.Location},TimeLine.json转换异常,{ex.Message}{ex.StackTrace},{lessonRecord.id}", GroupNames.成都开发測試群組);
- }
- }
- //读取Task.json
- List<TaskData> taskDatas = new List<TaskData>();
- try
- {
- BlobDownloadResult taskBlobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/Task.json").DownloadContentAsync();
- taskDatas = taskBlobDownload.Content.ToObjectFromJson<List<TaskData>>();
- }
- catch (Exception ex)
- {
- if (!ex.Message.Contains("The specified blob does not exist"))
- {
- await _dingDing.SendBotMsg($"{_option.Location},Task.json转换异常,{ex.Message}{ex.StackTrace},{lessonRecord.id}", GroupNames.成都开发測試群組);
- }
- }
- //读取IRS.json
- List<IRSData> iRSDatas = new List<IRSData>();
- try
- {
- BlobDownloadResult irsBlobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/IRS.json").DownloadContentAsync();
- iRSDatas = irsBlobDownload.Content.ToObjectFromJson<List<IRSData>>();
- }
- catch (Exception ex)
- {
- if (!ex.Message.Contains("The specified blob does not exist"))
- {
- await _dingDing.SendBotMsg($"{_option.Location},IRS.json转换异常,{ex.Message}{ex.StackTrace},{lessonRecord.id}", GroupNames.成都开发測試群組);
- }
- }
- //如果有更新 则去读取/{_lessonId}/IES/base.json
- try
- {
- // await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} 收到更新", GroupNames.醍摩豆服務運維群組);
- BlobDownloadResult baseblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/base.json").DownloadContentAsync();
- //attendState
- string basejson = baseblobDownload.Content.ToString().Replace("\"Uncall\"", "0").Replace("Uncall", "0");
- LessonBase lessonBase = null;
- try
- {
- lessonBase = basejson.ToObject<LessonBase>();
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{_option.Location},base.json转换异常,{ex.Message}{ex.StackTrace}{basejson},{lessonRecord.id}", GroupNames.成都开发測試群組);
- //lessonBase = baseblobDownload.Content.ToObjectFromJson<LessonBase>();
- }
- //await _dingDing.SendBotMsg($"课例记录文件base.json:{lessonBase.ToJsonString()}", GroupNames.成都开发測試群組);
- if (lessonBase != null && lessonBase.summary != null)
- {
- //lessonRecord.name = lessonBase.summary.activityName;
- lessonRecord.attendCount = lessonBase.summary.attendCount;
- lessonRecord.clientCount = lessonBase.summary.clientCount;
- lessonRecord.attendRate = lessonBase.summary.attendRate;
- lessonRecord.groupCount = lessonBase.summary.groupCount;
- lessonRecord.collateTaskCount = lessonBase.summary.collateTaskCount;
- lessonRecord.hitaClientCmpCount = lessonBase.summary.collateTaskCount + lessonRecord.hitaClientCmpCount;
- lessonRecord.collateCount = lessonBase.summary.collateCount;
- lessonRecord.pushCount = lessonBase.summary.pushCount;
- lessonRecord.totalPoint = lessonBase.summary.totalPoint;
- lessonRecord.examQuizCount = lessonBase.summary.examQuizCount;
- lessonRecord.interactionCount = lessonBase.summary.interactionCount;
- lessonRecord.examPointRate = lessonBase.summary.examPointRate;
- lessonRecord.clientInteractionCount = lessonBase.summary.clientInteractionCount;
- lessonRecord.clientInteractionAverge = lessonBase.summary.clientInteractionAverge;
- lessonRecord.examCount = lessonBase.summary.examCount;
- lessonRecord.totalInteractPoint = lessonBase.summary.totalInteractPoint;
- lessonRecord.learningCategory = lessonBase.summary.learningCategory;
- if (lessonRecord.learningCategory == null)
- {
- lessonRecord.learningCategory = new LearningCategory();
- }
- if (lessonRecord.hitaClientCmpCount > 0)
- {
- lessonRecord.learningCategory.cooperation = 1;
- }
- if (!string.IsNullOrWhiteSpace(lessonRecord.school))
- {
- lessonBase.student.ForEach(x =>
- {
- if (string.IsNullOrWhiteSpace(x.school))
- {
- x.school = lessonRecord.school;
- }
- });
- }
- //计算TP灯
- {
- int T = -1;
- int P = -1;
- if (lessonRecord.clientInteractionAverge <= 0)
- {
- T = 0;
- }
- else if (lessonRecord.clientInteractionAverge > 0 && lessonRecord.clientInteractionAverge < 2)
- // else if (lessonRecord.clientInteractionAverge >= 1 && lessonRecord.clientInteractionAverge <= 2)
- {
- T = 1;
- }
- else
- {
- T = 2;
- }
- //if (lessonRecord.examCount > 0)
- //{
- // //有评测次数大于0则P是直接绿灯
- // P = 2;
- //}
- //else {
- //}
- int a = lessonRecord.hitaClientCmpCount;
- int b = lessonRecord.pushCount;
- int c = lessonRecord.examCount;
- switch (true)
- {
- case bool when T == 0:
- P = 0;
- break;
- case bool when T == 1 || T == 2:
- if (a == 0 && b == 0 && c == 0)
- {
- P = 0;
- }
- else if ((a > 0 && b > 0) || (a > 0 && c > 0) || (b > 0 && c > 0))
- {
- P = 2;
- }
- else
- {
- P = 1;
- }
- break;
- }
- lessonRecord.tLevel = T;
- lessonRecord.pLevel = P;
- }
- //LessonStudentRecord lessonStudentRecord = new LessonStudentRecord
- //{
- // clientSummaryList = lessonBase.report.clientSummaryList,
- // students = lessonBase.student,
- // name = lessonRecord.name,
- // school = lessonRecord.school,
- // id = lessonRecord.id,
- // scope = lessonRecord.scope,
- // tmdid = lessonRecord.tmdid,
- // code = "LessonStudentRecord",
- // pk = "LessonStudentRecord",
- // courseId =lessonRecord.courseId,
- // groupIds= lessonRecord.groupIds,
- // periodId = lessonRecord.periodId,
- // subjectId = lessonRecord.subjectId,
- //};
- //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS,Constant.Student).UpsertItemAsync<LessonStudentRecord>(lessonStudentRecord, new PartitionKey("LessonStudentRecord"));
- }
- //有上传 base.josn.
- lessonRecord.upload = 1;
- // await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} 更新完成", GroupNames.醍摩豆服務運維群組);
- LessonService.DoAutoDeleteSchoolLessonRecord(lessonRecord, scope, client, school, tmdid, teacher, _serviceBus, _azureStorage, _configuration, _coreAPIHttpService, _dingDing, _azureRedis);
- long? size = await _azureStorage.GetBlobContainerClient(blobname).GetBlobsSize($"records/{_lessonId}");
- Bloblog bloblog = new Bloblog
- {
- id = lessonRecord.id,
- code = $"Bloblog-{blobname}",
- name = lessonRecord.name,
- pk = "Bloblog",
- time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- type = "records",
- url = $"records/{_lessonId}",
- subjectId = string.IsNullOrWhiteSpace(lessonRecord.subjectId) ? new List<string>() : new List<string> { lessonRecord.subjectId },
- periodId = string.IsNullOrWhiteSpace(lessonRecord.periodId) ? new List<string>() : new List<string> { lessonRecord.periodId },
- size = size.HasValue ? size.Value : 0,
- };
- await client.GetContainer(Constant.TEAMModelOS, tbname).UpsertItemAsync(bloblog);
- //await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} blob刷新完成!", GroupNames.醍摩豆服務運維群組);
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = "records", name = $"{blobname}" }, _serviceBus, _configuration, _azureRedis);
- msgs.Add(update);
- DoLessonStudentRecord(_dingDing, _snowflakeId, lessonRecord, scope, client, school, tmdid, teacher, _serviceBus, _azureStorage, _configuration, lessonBase,_azureRedis ,PickupMemberIds ,taskDatas,iRSDatas );
- }
- catch (Exception ex)
- {
- if (!ex.Message.Contains("The specified blob does not exist"))
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}课程读取base.json,{_lessonId}\n{ex.Message}\n{ex.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- }
- // await BIStats.SetTypeAddStats(client, _dingDing,lessonRecord.school, "Less", 0, 1, lessonRecord.clientInteractionCount);//BI统计增/减量
- break;
- //更新 时间线
- case "up-TimeLine":
- //BlobDownloadResult TimeLineblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/TimeLine.json").DownloadContentAsync();
- //var timeline = TimeLineblobDownload.Content.ToObjectFromJson<List<LessonTimeLine>>();
- msgs.Add(update);
- break;
- //更新 课堂总览信息
- case "up-ActivityInfo":
- //BlobDownloadResult ActivityInfoblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/ActivityInfo.json").DownloadContentAsync();
- //var activityInfos = ActivityInfoblobDownload.Content.ToObjectFromJson<List<LessonActivityInfo>>();
- msgs.Add(update);
- break;
- case "up-baseinfo":///更新基础信息,名称科目,年级,分类等,不能删除 ,由update-lesson-baseinfo 触发。
- isReplace = true;
- msgs.Add(update);
- break;
- case "up-expire"://消除过期时间,消除后需要取消已经排程的通知订阅
- try
- {
- var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
- List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
- foreach (var record in records)
- {
- try
- {
- await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
- await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
- }
- catch (Exception)
- {
- continue;
- }
- }
- }
- catch (Exception)
- {
- break;
- }
- isReplace = true;
- msgs.Add(update);
- break;
- case "delete":
- try
- {
- if (lessonRecord.expire > 0)
- {
- var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
- List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
- foreach (var record in records)
- {
- try
- {
- await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
- await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
- }
- catch (Exception)
- {
- continue;
- }
- }
- }
- await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, blobname, new List<string> { $"records/{_lessonId}" });
- await client.GetContainer(Constant.TEAMModelOS, tbname).DeleteItemStreamAsync(lessonRecord.id, new PartitionKey($"Bloblog-{blobname}"));
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = "records", name = $"{blobname}" }, _serviceBus, _configuration, _azureRedis);
- msgs.Add(update);
- }
- catch (CosmosException)
- {
- msgs.Add(update);
- }
- lessonRecord = null;
- isReplace = false;
- break;
- case "create":
- oldlessonRecord = null;
- //处理课堂选用的课程信息
- lessonRecord.show = teacher.lessonShow;
- lessonRecord.upload = 0;
- if (!string.IsNullOrEmpty(lessonRecord.courseId))
- {
- CourseBase course = null;
- try
- {
- var cresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"CourseBase-{lessonRecord.school}"));
- if (cresponse.Status == 200)
- {
- using var cJson = await JsonDocument.ParseAsync(cresponse.ContentStream);
- course = cJson.ToObject<CourseBase>();
- }
- else
- {
- var sresponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"CourseBase"));
- if (sresponse.Status == 200)
- {
- using var cJson = await JsonDocument.ParseAsync(sresponse.ContentStream);
- course = cJson.ToObject<CourseBase>();
- }
- else
- {
- course = null;
- }
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-查询课程-CosmosDB异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- }
- /*catch (CosmosException ex) when (ex.Status != 404)
- {
- try
- {
- course = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Course>(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
- }
- catch (CosmosException e) when (e.Status != 404)
- {
- course = null;
- }
- }*/
- if (course != null)
- {
- lessonRecord.periodId = course.period?.id;
- lessonRecord.subjectId = course.subject?.id;
- }
- }
- //处理课堂选用的名单
- if (lessonRecord.groupIds.IsNotEmpty())
- {
- List<GroupListDto> groups = await GroupListService.GetGroupListByListids(client, _dingDing, lessonRecord.groupIds, lessonRecord.school);
- if (!string.IsNullOrWhiteSpace(lessonRecord.school) && !string.IsNullOrWhiteSpace(lessonRecord.periodId))
- {
- HashSet<string> grades = new HashSet<string>();
- School schoolObj = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(lessonRecord.school, new PartitionKey("Base"));
- HashSet<int> gd = groups.SelectMany(z => z.grades).ToHashSet();
- groups.ForEach(y => {
- if (y.type.Equals("teach") || y.type.Equals("class"))
- {
- gd.Add(y.year);
- }
- });
- var gpdata = SchoolService.GetGrades(schoolObj, lessonRecord.periodId, gd);
- lessonRecord.grade = gpdata.grades.ToList();
- }
- }
-
- try
- {
- if (scope.Equals("school")) {
- School schoolBase = await client.GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(school, new PartitionKey("Base"));
- var space = await BlobService.GetSurplusSpace(school, scope, $"{Environment.GetEnvironmentVariable("Option:Location")}", _azureCosmos, _azureRedis, _azureStorage, _dingDing, _httpTrigger);
- SchoolSetting setting = null;
- Azure.Response schoolSetting = await client.GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync(school, new PartitionKey("SchoolSetting"));
- if (schoolSetting.Status == 200)
- {
- setting = JsonDocument.Parse(schoolSetting.Content).RootElement.Deserialize<SchoolSetting>();
- if (setting.lessonSetting != null)
- {
- //两种状态都不属于,则默认未开启。
- if (setting.lessonSetting.openAutoClean != 0 && setting.lessonSetting.openAutoClean != 1)
- {
- setting.lessonSetting.openAutoClean = 0;
- setting.lessonSetting.expireDays = Constant.school_lesson_expire;
- }
- else
- {
- //属于 要么开启1,要么关闭0
- }
- }
- else
- {
- setting.lessonSetting = new LessonSetting() { openAutoClean = 0, expireDays = Constant.school_lesson_expire };
- }
- }
- else
- {
- setting = new SchoolSetting() { lessonSetting = new LessonSetting { openAutoClean = 0, expireDays = Constant.school_lesson_expire } };
- }
- int school_lesson_expire = 0;
- bool save = true;
- if (space.surplus > 0)
- {
- save = true;
- }
- else {
- save = false;
- school_lesson_expire = Constant.school_lesson_expire;
- }
- if (!save && school_lesson_expire > 0) {
- // 1-时间戳,7-时间戳
- Dictionary<int, ExpireTag> result = new Dictionary<int, ExpireTag>();
- //暂定7天
- var now = DateTimeOffset.UtcNow;
- //剩余3天的通知
- //var day3= now.AddDays(school_lesson_expire - 3).ToUnixTimeMilliseconds();
- //result.Add(3, day3);
- //剩余1天的通知
- var day1 = now.AddDays(school_lesson_expire - (school_lesson_expire - 1)).ToUnixTimeMilliseconds();
- result.Add(1, new ExpireTag { expire = day1, tag = "notification" });
- //到期通知
- //不到五点上传的课例,七天之后直接删除。
- int addSecond = 0;
- if (now.Hour > 5)
- {
- // 到凌晨00点还差 (24 - now.Hour) *60 * 60 分钟,再加天数;
- addSecond = school_lesson_expire * 86400 + (24 - now.Hour) * 3600 - (now.Hour * 3600);
- //再加 00到05小时内的 随机秒数
- Random rand = new Random();
- int randInt = rand.Next(0, 18000);
- addSecond += randInt;
- }
- else
- {
- addSecond = school_lesson_expire * 24 * 60 * 60;
- }
- lessonRecord.expire = now.AddSeconds(addSecond).ToUnixTimeMilliseconds();
- result.Add(school_lesson_expire, new ExpireTag { expire = lessonRecord.expire, tag = "delete" });
- // result.Add(school_lesson_expire, lessonRecord.expire);
- string biz = "expire";
- string expireTime = DateTimeOffset.FromUnixTimeMilliseconds(lessonRecord.expire).ToString("yyyy-MM-dd HH:mm:ss");
- Teacher targetTeacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>($"{tmdid}", new PartitionKey($"Base"));
- _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = targetTeacher.id, name = targetTeacher.name, code = targetTeacher.lang } }, "expire-school_lessonRecord", Constant.NotifyType_IES5_Course,
- new Dictionary<string, object> { { "tmdid", teacher.id }, { "tmdname", teacher.name }, { "schoolName", schoolBase.name },
- { "schoolId", $"{school}" },{ "lessonId",lessonRecord.id }, { "expireTime", expireTime },{ "lessonName",lessonRecord.name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
- var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
- List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
- if (records.Count <= 0)
- {
- foreach (var item in result)
- {
- string PartitionKey = string.Format("{0}{1}{2}", lessonRecord.code, "-", $"expire-{item.Key}");
- //课堂的id ,
- //课堂的通知时间类型progress, 默认就会发送一条,到期前一天发送一条,最后已到期发送一条。
- var message = new ServiceBusMessage(new
- {
- id = lessonRecord.id,
- progress = item.Key,
- code = lessonRecord.code,
- scope = lessonRecord.scope,
- school = lessonRecord.school,
- opt = "delete",
- expire = lessonRecord.expire,
- tmdid = tmdid,
- tmdname = teacher.name,
- name = lessonRecord.name,
- startTime = lessonRecord.startTime,
- tag = item.Value.tag
- }.ToJsonString());
- message.ApplicationProperties.Add("name", "LessonRecordExpire");
- long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(item.Value.expire));
- ChangeRecord changeRecord = new ChangeRecord
- {
- RowKey = lessonRecord.id,
- PartitionKey = PartitionKey,
- sequenceNumber = start,
- msgId = message.MessageId
- };
- await table.Save<ChangeRecord>(changeRecord);
- }
- }
- }
- }
- //个人课例保存规则
- if (scope.Equals("private"))
- {
- int lessonLimit = teacher.lessonLimit;
- var space= await BlobService.GetSurplusSpace(tmdid, scope, $"{Environment.GetEnvironmentVariable("Option:Location")}", _azureCosmos, _azureRedis, _azureStorage, _dingDing,_httpTrigger);
- //20230208调整之前 if (blobTotal * 1073741824 - blobsize > 2147483648) //剩余空间大于2G
- //剩余空间不足,则开启自动清理机制
- if (space .surplus> 0)
- {
- //大于0则表示空间充足
- lessonLimit = -1;
- }
- else
- {
- //20230208调整增加逻辑,之前lessonLimit用于处理默认保存50条,现在用于处理标记是否空间不足,不足则标记清理。
- if ($"{Environment.GetEnvironmentVariable("Option:Location")}".Contains("Test", StringComparison.OrdinalIgnoreCase))
- {
- lessonLimit = 0;
- }
- else {
- lessonLimit = -1 ;
- }
- }
- if (lessonLimit != -1)
- {
- #region 20230208 调整之后
- {
- // 1-时间戳,7-时间戳
- Dictionary<int, ExpireTag> result = new Dictionary<int, ExpireTag>();
- //暂定7天
- var now = DateTimeOffset.UtcNow;
- //剩余3天的通知
- //var day3= now.AddDays(Constant.private_lesson_expire - 3).ToUnixTimeMilliseconds();
- //result.Add(3, day3);
- //剩余1天的通知
- var day1 = now.AddDays(Constant.private_lesson_expire - (Constant.private_lesson_expire - 1)).ToUnixTimeMilliseconds();
- result.Add(1, new ExpireTag { expire = day1, tag = "notification" });
- //到期通知
- //不到五点上传的课例,七天之后直接删除。
- int addSecond = 0;
- if (now.Hour > 5)
- {
- // 到凌晨00点还差 (24 - now.Hour) *60 * 60 分钟,再加天数;
- addSecond = Constant.private_lesson_expire * 86400 + (24 - now.Hour) * 3600;
- //再加 00到05小时内的 随机秒数
- Random rand = new Random();
- int randInt = rand.Next(0, 18000);
- addSecond += randInt;
- }
- else
- {
- addSecond = Constant.private_lesson_expire * 24 * 60 * 60;
- }
- //将当前课例标记为 自动清理
- lessonRecord.expire = now.AddSeconds(addSecond).ToUnixTimeMilliseconds();
- result.Add(Constant.private_lesson_expire, new ExpireTag { expire = lessonRecord.expire, tag = "delete" });
- string biz = "expire";
- string expireTime = DateTimeOffset.FromUnixTimeMilliseconds(lessonRecord.expire).ToString("yyyy-MM-dd HH:mm:ss");
- _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = teacher.id, name = teacher.name, code = teacher.lang } }, "expire-private_lessonRecord", Constant.NotifyType_IES5_Course,
- new Dictionary<string, object> { { "tmdname", teacher.name }, { "tmdid", teacher.name }, { "expireTime", expireTime }, { "lessonId", lessonRecord.id }, { "lessonName", lessonRecord.name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
- var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
- List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
- if (records.Count <= 0)
- {
- foreach (var item in result)
- {
- string PartitionKey = string.Format("{0}{1}{2}", lessonRecord.code, "-", $"expire-{item.Key}");
- //课堂的id ,
- //课堂的通知时间类型progress, 默认就会发送一条,到期前一天发送一条,最后已到期发送一条。
- var message = new ServiceBusMessage(new
- {
- id = lessonRecord.id,
- progress = item.Key,
- code = lessonRecord.code,
- scope = lessonRecord.scope,
- school = lessonRecord.school,
- opt = "delete",
- expire = lessonRecord.expire,
- tmdid = tmdid,
- tmdname = teacher.name,
- name = lessonRecord.name,
- startTime = lessonRecord.startTime,
- tag = item.Value.tag
- }.ToJsonString());
- message.ApplicationProperties.Add("name", "LessonRecordExpire");
- long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(item.Value.expire));
- ChangeRecord changeRecord = new ChangeRecord
- {
- RowKey = lessonRecord.id,
- PartitionKey = PartitionKey,
- sequenceNumber = start,
- msgId = message.MessageId
- };
- await table.Save<ChangeRecord>(changeRecord);
- }
- }
- await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(lessonRecord, lessonRecord.id, new PartitionKey(lessonRecord.code));
- }
- #endregion 20230208 调整之后
- #region 20230208 调整之前
- /** 20230208 调整之前
- HashSet<string> ids = new HashSet<string>();
- //未定义的 以及过期时间小于等于0 的 课例
- string private_count_sql = $"select value(c.id) from c where ( c.expire<=0 or IS_DEFINED(c.expire) = false ) and c.tmdid='{tmdid}' ";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<string>(
- queryText: private_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(code) }))
- {
- ids.Add(item);
- }
- // 220601 收藏不限條數,但空間不足時,僅保留最後一次上傳的課例 ()
- //包含收藏的本人的个人课例
- //string favorite_count_sql = $"select value(c.id) from c where c.type='LessonRecord' and c.owner='{tmdid}' and c.scope='private' ";
- //await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<string>(
- // queryText: favorite_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Favorite-{tmdid}") }))
- //{
- // ids.Add(item);
- //}
- //教师个人预设的,可以通过设置的方式增加
- int limit = teacher.lessonLimit;
- if (teacher.lessonLimit == 0)
- {
- //未设置的的采用系统设置的默认值50
- limit = Constant.private_lesson_limit;
- }
- if (ids.Count >= limit)
- {
- LessonRecord lessonRecordExpire = null;
- //获取一条最新的 且没有被收藏,且没有被标记为过期的记录,且不是当前触发的id 。
- //220712 讨论,将desc去掉,获取最旧的那一笔数据。删除最旧的
- string sql = $"SELECT top 1 value(c) FROM c where ( c.expire<=0 or IS_DEFINED(c.expire) = false ) and c.tmdid='{tmdid}' " +
- $"and c.favorite<=0 and c.id<>'{lessonRecord.id}' and c.status<>404 order by c.startTime ";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<LessonRecord>(
- queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"{code}") }))
- {
- lessonRecordExpire = item; break;
- }
- if (lessonRecordExpire != null)
- {
- // 1-时间戳,7-时间戳
- Dictionary<int, ExpireTag> result = new Dictionary<int, ExpireTag>();
- //暂定7天
- var now = DateTimeOffset.UtcNow;
- //剩余3天的通知
- //var day3= now.AddDays(Constant.private_lesson_expire - 3).ToUnixTimeMilliseconds();
- //result.Add(3, day3);
- //剩余1天的通知
- var day1 = now.AddDays(Constant.private_lesson_expire - (Constant.private_lesson_expire - 1)).ToUnixTimeMilliseconds();
- result.Add(1, new ExpireTag { expire = day1, tag = "notification" });
- //到期通知
- //不到五点上传的课例,七天之后直接删除。
- int addSecond = 0;
- if (now.Hour > 5)
- {
- // 到凌晨00点还差 (24 - now.Hour) *60 * 60 分钟,再加天数;
- addSecond = Constant.private_lesson_expire * 86400 + (24 - now.Hour) * 3600;
- //再加 00到05小时内的 随机秒数
- Random rand = new Random();
- int randInt = rand.Next(0, 18000);
- addSecond += randInt;
- }
- else
- {
- addSecond = Constant.private_lesson_expire * 24 * 60 * 60;
- }
- lessonRecordExpire.expire = now.AddSeconds(addSecond).ToUnixTimeMilliseconds();
- //result.Add(Constant.private_lesson_expire, lessonRecordExpire.expire);
- result.Add(Constant.private_lesson_expire, new ExpireTag { expire = lessonRecordExpire.expire, tag = "delete" });
- string biz = "expire";
- string expireTime= DateTimeOffset.FromUnixTimeMilliseconds(lessonRecordExpire.expire).ToString("yyyy-MM-dd HH:mm:ss");
- _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = teacher.id, name = teacher.name, code = teacher.lang } }, "expire-private_lessonRecord", Constant.NotifyType_IES5_Course,
- new Dictionary<string, object> { { "tmdname", teacher.name }, { "tmdid", teacher.name }, { "expireTime", expireTime }, { "lessonId", lessonRecordExpire.id }, { "lessonName", lessonRecordExpire. name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
- var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
- List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecordExpire.id } });
- if (records.Count <= 0)
- {
- foreach (var item in result)
- {
- string PartitionKey = string.Format("{0}{1}{2}", lessonRecordExpire.code, "-", $"expire-{item.Key}");
- //课堂的id ,
- //课堂的通知时间类型progress, 默认就会发送一条,到期前一天发送一条,最后已到期发送一条。
- var message = new ServiceBusMessage(new
- {
- id = lessonRecordExpire.id,
- progress = item.Key,
- code = lessonRecordExpire.code,
- scope = lessonRecordExpire.scope,
- school = lessonRecordExpire.school,
- opt = "delete",
- expire = lessonRecordExpire.expire,
- tmdid = tmdid,
- tmdname = teacher.name,
- name = lessonRecordExpire.name,
- startTime = lessonRecordExpire.startTime,
- tag = item.Value.tag
- }.ToJsonString());
- message.ApplicationProperties.Add("name", "LessonRecordExpire");
- long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(item.Value.expire));
- ChangeRecord changeRecord = new ChangeRecord
- {
- RowKey = lessonRecordExpire.id,
- PartitionKey = PartitionKey,
- sequenceNumber = start,
- msgId = message.MessageId
- };
- await table.Save<ChangeRecord>(changeRecord);
- }
- }
- await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(lessonRecordExpire, lessonRecordExpire.id, new PartitionKey(lessonRecordExpire.code));
- }
- }**/
- #endregion 20230208 调整之前
- }
- else
- {
- //=-1 则表示不限制上传数量
- }
- }
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-处理课堂记录的-CosmosDB异常{e.Message}\n{e.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- msgs.Add(update);
- await BIStats.SetTypeAddStats(client, _dingDing, lessonRecord.school, "Less", 1, 0);//BI统计增/减量
- break;
- default:
- break;
- }
- }
- //如果被删除则不能再被更新
- if (isReplace)
- {
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(lessonRecord, lessonId, new PartitionKey(code));
- }
- //计算课堂更新前后的差值
- lessonDis = LessonService.DisLessonCount(oldlessonRecord, lessonRecord, lessonDis);
- await LessonService.FixLessonCount(client, _dingDing, lessonRecord, oldlessonRecord, lessonDis);
- }
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错-CosmosDB异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错\n{ex.Message}\n{ex.StackTrace}\n\n{data}\n{code}\n{updates}\n", GroupNames.醍摩豆服務運維群組);
- }
- }
- [Function("LessonRecordExpire")]
- public async Task LessonRecordExpireFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "lesson-record-expire", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- try
- {
- var jsonMsg = JsonDocument.Parse(msg).RootElement;
- jsonMsg.TryGetProperty("id", out JsonElement id);
- jsonMsg.TryGetProperty("progress", out JsonElement progress);
- jsonMsg.TryGetProperty("code", out JsonElement _code);
- jsonMsg.TryGetProperty("tmdid", out JsonElement tmdid);
- jsonMsg.TryGetProperty("tmdname", out JsonElement tmdname);
- jsonMsg.TryGetProperty("name", out JsonElement name);
- jsonMsg.TryGetProperty("startTime", out JsonElement startTime);
- jsonMsg.TryGetProperty("expire", out JsonElement expire);
- jsonMsg.TryGetProperty("scope", out JsonElement scope);
- jsonMsg.TryGetProperty("school", out JsonElement _school);
- jsonMsg.TryGetProperty("tag", out JsonElement _tag);
- var client = _azureCosmos.GetCosmosClient();
- //处理到期删除
- if (_tag.ValueKind.Equals(JsonValueKind.String) && $"{_tag}".Equals("delete"))
- {
- string lessonId = $"{id}";
- string tbname;
- string school = $"{_school}";
- string code = "";
- if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
- {
- code = $"LessonRecord-{school}";
- tbname = "School";
- }
- else if ($"{scope}".Equals("private"))
- {
- code = $"LessonRecord";
- tbname = "Teacher";
- }
- else
- {
- return;
- }
- Azure.Response response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
- if (response.Status == 200)
- {
- LessonRecord lessonRecord;
- var doc = JsonDocument.Parse(response.ContentStream);
- lessonRecord = doc.RootElement.ToObject<LessonRecord>();
- lessonRecord.status = 404;
- await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(lessonRecord, lessonRecord.id, new PartitionKey(lessonRecord.code));
- var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
- var messageChange = new ServiceBusMessage(new { delete_id = lessonId, tmdid = tmdid, scope = scope, opt = "delete", school = school }.ToJsonString());
- messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
- await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
- await _dingDing.SendBotMsg($"课例:【{lessonRecord.name}】\n课例ID:【{lessonRecord.id}】\n因时间到期,即将被自动删除,到期时间:" +
- $"{lessonRecord.expire}\n{lessonRecord.ToJsonString()}", GroupNames.成都开发測試群組);
- }
- }
- string biz = "expire";
- Teacher targetTeacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>($"{tmdid}", new PartitionKey($"Base"));
- string expireTime = DateTimeOffset.FromUnixTimeMilliseconds(long.Parse($"{expire}")).ToString("yyyy-MM-dd HH:mm:ss");
- _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = targetTeacher.id, name = targetTeacher.name, code = targetTeacher.lang } }, "expire-private_lessonRecord", Constant.NotifyType_IES5_Course,
- new Dictionary<string, object> { { "tmdname", tmdname }, { "tmdid", tmdid }, { "lessonId", id }, { "expireTime", expireTime }, { "lessonName", name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,LessonRecordExpire()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- }
- /// <summary>
- /// 完善课程变更
- /// </summary>
- /// <data msg>
- /// CourseChange
- ///// </data>
- /// <param name="msg"></param>
- /// <returns></returns>
- ///[Function("Course")] 弃用
- public async Task CourseFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "course", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- var client = _azureCosmos.GetCosmosClient();
- try
- {
- //await _dingDing.SendBotMsg($"ServiceBus,CourseChange:{msg}", GroupNames.醍摩豆服務運維群組);
- var jsonMsg = JsonDocument.Parse(msg);
- CourseChange courseChange = msg.ToObject<CourseChange>();
- if (courseChange == null)
- {
- return;
- }
- foreach (var cls in courseChange.addClass)
- {
- (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, new List<string> { cls }, courseChange.school);
- var addStudentsCls = tchList.FindAll(x => x.type == 2);
- var addTmdidsCls = tchList.FindAll(x => x.type == 1);
- foreach (var stu in addStudentsCls)
- {
- try
- {
- ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
- if (!stuCourse.Value.classId.Contains(cls))
- {
- stuCourse.Value.classId.Add(cls);
- }
- await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
- }
- catch (CosmosException ex)
- {
- if (ex.Response.Status == 404)
- {
- var course = new StuCourse
- {
- id = courseChange.id,
- scode = courseChange.code,
- name = courseChange.name,
- code = $"StuCourse-{stu.schoolId}-{stu.id}",
- scope = courseChange.scope,
- school = stu.schoolId,
- creatorId = courseChange.creatorId,
- classId = new List<string> { cls },
- pk = "StuCourse",
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
- };
- await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
- }
- else
- {
- await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- }
- }
- }
- foreach (var tmd in addTmdidsCls)
- {
- try
- {
- ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
- if (!stuCourse.Value.classId.Contains(cls))
- {
- stuCourse.Value.classId.Add(cls);
- }
- await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
- }
- catch (CosmosException ex)
- {
- if (ex.Response.Status == 404)
- {
- var course = new StuCourse
- {
- id = courseChange.id,
- scode = courseChange.code,
- name = courseChange.name,
- code = $"StuCourse-{tmd.id}",
- scope = courseChange.scope,
- school = courseChange.school,
- creatorId = courseChange.creatorId,
- classId = new List<string> { cls },
- pk = "StuCourse",
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
- };
- await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
- }
- else
- {
- await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- }
- }
- }
- }
- foreach (var list in courseChange.addList)
- {
- (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, new List<string> { list }, courseChange.school);
- var addStudentsCls = tchList.FindAll(x => x.type == 2);
- var addTmdidsCls = tchList.FindAll(x => x.type == 1);
- foreach (var stu in addStudentsCls)
- {
- try
- {
- ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
- if (!stuCourse.Value.stulist.Contains(list))
- {
- stuCourse.Value.stulist.Add(list);
- await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
- }
- }
- catch (CosmosException ex)
- {
- if (ex.Response.Status == 404)
- {
- var course = new StuCourse
- {
- id = courseChange.id,
- scode = courseChange.code,
- name = courseChange.name,
- code = $"StuCourse-{stu.schoolId}-{stu.id}",
- scope = courseChange.scope,
- school = stu.schoolId,
- creatorId = courseChange.creatorId,
- stulist = new List<string> { list },
- pk = "StuCourse",
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
- };
- await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
- }
- else
- {
- await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- }
- }
- }
- foreach (var tmd in addTmdidsCls)
- {
- try
- {
- ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
- if (!stuCourse.Value.stulist.Contains(list))
- {
- stuCourse.Value.stulist.Add(list);
- await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
- }
- }
- catch (CosmosException ex)
- {
- if (ex.Response.Status == 404)
- {
- var course = new StuCourse
- {
- id = courseChange.id,
- scode = courseChange.code,
- name = courseChange.name,
- code = $"StuCourse-{tmd.id}",
- scope = courseChange.scope,
- school = courseChange.school,
- creatorId = courseChange.creatorId,
- stulist = new List<string> { list },
- pk = "StuCourse",
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
- };
- await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
- }
- else
- {
- await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- }
- }
- }
- }
- foreach (var delCls in courseChange.delClass)
- {
- (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, new List<string> { delCls }, courseChange.school);
- var delStudentsCls = tchList.FindAll(x => x.type == 2);
- var delTmdidsCls = tchList.FindAll(x => x.type == 1);
- foreach (var stu in delStudentsCls)
- {
- try
- {
- ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
- if (stuCourse.Value.classId.Contains(delCls))
- {
- stuCourse.Value.classId.Remove(delCls);
- }
- if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
- {
- //当两个列表都不存在时则直接删除
- await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
- }
- else
- {
- await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
- }
- }
- catch (CosmosException ex)
- {
- //await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- }
- }
- foreach (var tmd in delTmdidsCls)
- {
- try
- {
- ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
- if (stuCourse.Value.classId.Contains(delCls))
- {
- stuCourse.Value.classId.Remove(delCls);
- }
- if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
- {
- //当两个列表都不存在时则直接删除
- await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
- }
- else
- {
- await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
- }
- }
- catch (CosmosException ex)
- {
- await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- }
- }
- }
- foreach (var delList in courseChange.delList)
- {
- (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, new List<string> { delList }, courseChange.school);
- var delStudentsCls = tchList.FindAll(x => x.type == 2);
- var delTmdidsCls = tchList.FindAll(x => x.type == 1);
- foreach (var stu in delStudentsCls)
- {
- try
- {
- ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
- if (stuCourse.Value.stulist.Contains(delList))
- {
- stuCourse.Value.stulist.Remove(delList);
- }
- if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
- {
- //当两个列表都不存在时则直接删除
- await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
- }
- else
- {
- await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
- }
- }
- catch (CosmosException ex)
- {
- continue;
- // await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- }
- }
- foreach (var tmd in delTmdidsCls)
- {
- try
- {
- ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
- if (stuCourse.Value.stulist.Contains(delList))
- {
- stuCourse.Value.stulist.Remove(delList);
- }
- if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
- {
- //当两个列表都不存在时则直接删除
- await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
- }
- else
- {
- await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
- }
- }
- catch (CosmosException ex)
- {
- await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- }
- }
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -Course\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- }
- }
- [Function("Imei")]
- public async Task ImeiFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "imei", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- try
- {
- //await _dingDing.SendBotMsg($"IES5,{Environment.GetEnvironmentVariable("Option:Location")},Imei AF call\n{msg.ToJsonString()}", GroupNames.成都开发測試群組);
- using var json = JsonDocument.Parse(msg);
- if (json.RootElement.TryGetProperty("channel", out JsonElement channel) &&
- json.RootElement.TryGetProperty("userid", out JsonElement userid) &&
- json.RootElement.TryGetProperty("school", out JsonElement school) &&
- json.RootElement.TryGetProperty("stus", out JsonElement stus))
- {
- var db = _azureCosmos.GetCosmosClient();
- foreach (var stu in stus.EnumerateArray())
- {
- await foreach (Response item in db.GetContainer(Constant.TEAMModelOS, Constant.Student).GetItemQueryStreamIterator(
- queryText: $"SELECT TOP 1 * FROM c WHERE c.stuid = '{stu.GetString()}'",
- requestOptions: new() { PartitionKey = new($"Imei") }))
- {
- using var root = await JsonDocument.ParseAsync(item.ContentStream);
- if (root.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var doc = root.RootElement.GetProperty("Documents").EnumerateArray().First();
- var imei = doc.ToObject<Imei>();
- imei.channel = channel.GetString();
- imei.userid = userid.GetString();
- await db.GetContainer(Constant.TEAMModelOS, Constant.Student).ReplaceItemAsync<Imei>(imei, imei.id);
- }
- }
- }
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"IES5,{_option.Location},Imei AF error\n{ex.Message}\n{ex.StackTrace}{msg.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- }
- }
- }
|