using System; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using TEAMModelOS.SDK.DI; using Azure.Cosmos; using System.Text.Json; using System.Collections.Generic; using TEAMModelOS.SDK.Models; using TEAMModelOS.SDK.Extension; using TEAMModelOS.SDK; using TEAMModelOS.SDK.Models.Cosmos; using TEAMModelOS.SDK.Models.Cosmos.Common; using System.Linq; using TEAMModelOS.Services.Common; using TEAMModelOS.SDK.Models.Service; using HTEXLib.COMM.Helpers; using System.Text; using static TEAMModelOS.SDK.Models.Teacher; using TEAMModelOS.SDK.Models.Cosmos.Common.Inner; using Azure.Storage.Blobs.Models; namespace TEAMModelFunction { public class ScsApisHttpTrigger { private readonly AzureCosmosFactory _azureCosmos; private readonly DingDing _dingDing; private readonly AzureStorageFactory _azureStorage; private readonly AzureRedisFactory _azureRedis; private readonly ThirdApisService _thirdApisService; public static string Code { get; set; } public static Dictionary parameterMap = null; public ScsApisHttpTrigger(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, ThirdApisService thirdApisService , AzureRedisFactory azureRedis) { _azureCosmos = azureCosmos; _dingDing = dingDing; _azureStorage = azureStorage; _azureRedis = azureRedis; _thirdApisService = thirdApisService; } /// /// 数据推送接口 /// /// /// /// [FunctionName("knowledge-change")] public async Task KnowledgeChange([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) { string data = await new StreamReader(req.Body).ReadToEndAsync(); var json = JsonDocument.Parse(data).RootElement; List old_new = null; string school = null; if (json.TryGetProperty("school", out JsonElement _school)) { school = _school.GetString(); } if (json.TryGetProperty("old_new", out JsonElement _old_new)) { old_new = _old_new.ToObject>(); } if (old_new.IsNotEmpty() && !string.IsNullOrWhiteSpace(school)) { foreach (var on in old_new) { List items = new List(); string sql = $"select value(c) from c where array_contains(c.knowledge,'{on._old}') "; await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator (queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{_school}") })) { items.Add(item); } items.ForEach(item => { //修改知识点 if (!string.IsNullOrEmpty(on._new)) { for (int i = 0; i < item.knowledge.Count; i++) { if (item.knowledge[i].Equals(on._old)) { item.knowledge[i] = on._new; } } } else { //表示删除知识点 item.knowledge.RemoveAll(x => x.Equals(on._old)); } }); foreach (var item in items) { ItemBlob itemBlob = null; try { BlobDownloadInfo blobDownloadResult = await _azureStorage.GetBlobContainerClient($"hbcn").GetBlobClient($"/item/{item.id}/{item.id}.json").DownloadAsync(); if (blobDownloadResult != null) { var blob = JsonDocument.Parse(blobDownloadResult.Content); itemBlob = blob.RootElement.ToObject(); itemBlob.exercise.knowledge = item.knowledge; await _azureStorage.UploadFileByContainer("hbcn", itemBlob.ToJsonString(), "item", $"{item.id}/{item.id}.json", true); } } catch (Exception ex) { itemBlob = null; } await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(item, item.id, new PartitionKey(item.code)); } } } return new OkResult(); } /// /// 数据推送接口 /// /// /// /// [FunctionName("SchoolDataPush")] public async Task SchoolDataPush([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) { var client = _azureCosmos.GetCosmosClient(); string data = await new StreamReader(req.Body).ReadToEndAsync(); JsonElement accessConfig = data.ToObject().GetProperty("accessConfig"); ScAccessConfig config = $"{accessConfig}".ToObject(); JsonElement school = data.ToObject().GetProperty("school"); StringBuilder queryText = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='yxtrain'"); List yxtrain = new List(); await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator(queryText: queryText.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") })) { yxtrain.Add(item); } List trains = new List(); var members = yxtrain.SelectMany(x => x.members).ToList(); if (members.IsNotEmpty()) { queryText = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='yxtrain' " + $"and c.id in ({string.Join(",", members.Select(x => $"'{x.id}'"))}) "); await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator(queryText: queryText.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"TeacherTrain-{school}") })) { trains.Add(item); } } string sql = $" SELECT value(c) FROM c join a in c.binds where ARRAY_LENGTH(c.binds)>0 and a.type='{config.config}' "; List teachers = new List(); await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator(queryText: sql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") })) { teachers.Add(item); } //5.3.1.12学员培训基本情况批量回写-UpdateTeacherListSituation List trains53112OK = new List(); //5.3.1.13学员能力点测评结果批量回写-UpdateTeacherListDiagnosis List trains53113OK = new List(); //5.3.1.17学员课堂实录批量回写-UploadKTSLList List trains53117OK = new List(); //5.3.1.22学员校本教研PDF(每人可以返回多条)批量回写-UploadSBTARPDFListV2 List trains53122OK = new List(); List> trainsNO = new List>(); List fails= new List(); trains.ForEach(x => { var teacher = teachers.Find(t => t.id.Equals(x.id)); if (teacher == null) { fails.Add(new PushFail { tmdid = x.id, msgs = new List> { new KeyValuePair("tmdid-unexistent", "账号不存在!") } }); } else { List> msgs = new List>(); var binddata = teachers.Where(t => t.id.Equals(x.id)).SelectMany(z => z.binds) .Where(d => d.data.IsNotEmpty()).SelectMany(d => d.data) .Where(d => string.IsNullOrEmpty(d) && d.Contains(config.config) && d.Contains(config.path)); if (binddata != null && binddata.Count() > 0) { var bindData = binddata.First().ToObject(); if (binddata != null) { } else { //如果没有找到绑定信息,则去blob查找。 } } else { //如果没有找到绑定信息,则去blob查找。 } } }); return new OkObjectResult(new { }); } /// /// 5.3.1.1获取项目列表 /// /// /// /// [FunctionName("GetProjectInfoByTrainComID")] public async Task GetProjectInfoByTrainComID([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) { List projects = new List() ; string data = await new StreamReader(req.Body).ReadToEndAsync(); JsonElement accessConfig = data.ToObject().GetProperty("accessConfig"); ScAccessConfig config = $"{accessConfig}".ToObject(); Code = "GetProjectInfoByTrainComID"; parameterMap = new Dictionary(); parameterMap.Add("TrainComID", config.trainComID); ScsResult result = new ScsResult { code = Code, title = "5.3.1.1获取项目列表" }; try { result = await _thirdApisService.Post(config.url, Code, config.passKey, config.privateKey, parameterMap); if (result.result) { projects = result.content.ToObject>(); } else { } return new OkObjectResult(new { data = projects.ToJsonString() }); } catch (Exception ex) { await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},IES5.ScApisService:GetProjectInfoByTrainComID\n{ex.Message}{ex.StackTrace}\n{result.ToJsonString()}\n{data}", GroupNames.成都开发測試群組); return new OkObjectResult(new { data = projects.ToJsonString() }); } } /// /// 5.3.1.18根据机构ID、项目ID、子项目ID返回学校列表 /// /// /// /// [FunctionName("GetSchoolList")] public async Task GetSchoolList([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) { List scSchools = new List(); string data = await new StreamReader(req.Body).ReadToEndAsync(); JsonElement accessConfig = data.ToObject().GetProperty("accessConfig"); ScAccessConfig config = $"{accessConfig}".ToObject(); Code = "GetSchoolList"; parameterMap = new Dictionary(); parameterMap.Add("TrainComID", config.trainComID); List results = new List(); try { if (config.p.IsNotEmpty()) { foreach (var ps in config.p) { parameterMap["ProjectID"] = ps.pd; parameterMap["ProjectItemID"] = ps.pid; ScsResult result = new ScsResult { code = Code, title = " 5.3.1.18根据机构ID、项目ID、子项目ID返回学校列表" }; result = await _thirdApisService.Post(config.url, Code, config.passKey, config.privateKey, parameterMap); if (result.result) { List schools = result.content.ToObject>(); if (schools.IsNotEmpty()) { scSchools.AddRange(schools); } } results.Add(result); } } return new OkObjectResult(new { data = scSchools.ToJsonString() }); } catch (Exception ex) { await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},IES5.ScApisService:GetSchoolList\n{ex.Message}{ex.StackTrace}\n{results.ToJsonString()}\n{data}", GroupNames.成都开发測試群組); return new OkObjectResult(new { data = scSchools.ToJsonString() }); } } /// /// 5.3.1.2获取学员名单 /// /// /// /// [FunctionName("GetTeachersListByProject")] public async Task GetTeachersListByProject([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) { List scTeachers = new List(); string data = await new StreamReader(req.Body).ReadToEndAsync(); JsonElement accessConfig = data.ToObject().GetProperty("accessConfig"); ScAccessConfig config = $"{accessConfig}".ToObject(); Code = "GetTeachersListByProject"; parameterMap = new Dictionary(); parameterMap.Add("TrainComID", config.trainComID); List results = new List(); try { if (config.p.IsNotEmpty()) { foreach (var ps in config.p) { parameterMap["ProjectID"] = ps.pd; parameterMap["ProjectItemID"] = ps.pid; ScsResult result = new ScsResult { code = Code, title = "5.3.1.2获取学员名单" }; result = await _thirdApisService.Post(config.url, Code, config.passKey, config.privateKey, parameterMap); if (result.result) { List teachers = result.content.ToObject>(); if (teachers.IsNotEmpty()) { scTeachers.AddRange(teachers); } } results.Add(result); } } return new OkObjectResult(new { data = scTeachers.ToJsonString() }); } catch (Exception ex) { await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},IES5.ScApisService:GetTeachersListByProject\n{ex.Message}{ex.StackTrace}\n{results.ToJsonString()}\n{data}", GroupNames.成都开发測試群組); return new OkObjectResult(new { data = scTeachers.ToJsonString() }); } } /// /// 5.3.1.20获取学校设置的可选能力点 /// /// /// /// [FunctionName("GetSchoolDiagnosis")] public async Task GetSchoolDiagnosis([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) { List projects = new List(); string data = await new StreamReader(req.Body).ReadToEndAsync(); JsonElement accessConfig = data.ToObject().GetProperty("accessConfig"); JsonElement schoolCode = data.ToObject().GetProperty("schoolCode"); ScAccessConfig config = $"{accessConfig}".ToObject(); Code = "GetSchoolDiagnosis"; parameterMap = new Dictionary(); parameterMap.Add("TrainComID", config.trainComID); List results = new List(); try { if (config.p.IsNotEmpty()) { foreach (var ps in config.p) { parameterMap["ProjectID"] = ps.pd; parameterMap["ProjectItemID"] = ps.pid; parameterMap["SchoolID"] = $"{schoolCode}"; parameterMap["School"] = $"{schoolCode}"; ScsResult result = new ScsResult { code = Code, title = " 5.3.1.20获取学校设置的可选能力点" }; result = await _thirdApisService.Post(config.url, Code, config.passKey, config.privateKey, parameterMap); if (result.result) { List diagnoses = result.content.ToObject>(); if (diagnoses.IsNotEmpty()) { projects.Add(new ScsProjectDiagnosis { project = ps, diagnoses = diagnoses }); await _azureStorage.SaveOrUpdate(new ScProjectDiagnosis { RowKey = $"{ps.pid}-{schoolCode}", PartitionKey = "ScSchoolDiagnosis", abilityNos = diagnoses.ToJsonString() }); } } else { List teacherDiagnoses = await _azureStorage.FindListByDict(new Dictionary { { "PartitionKey", "ScSchoolDiagnosis" }, { "RowKey", $"{ps.pid}-{schoolCode}" } }); if (teacherDiagnoses.IsNotEmpty()) { projects.Add(new ScsProjectDiagnosis { project = ps, diagnoses = teacherDiagnoses[0].abilityNos.ToObject>() }); } } results.Add(result); } } return new OkObjectResult(new { data = projects.ToJsonString() }); } catch (Exception ex) { //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},IES5.ScApisService:GetSchoolDiagnosis\n{ex.Message}{ex.StackTrace}\n{results.ToJsonString()}\n{data}", GroupNames.成都开发測試群組); if (config.p.IsNotEmpty()) { foreach (var ps in config.p) { List teacherDiagnoses = await _azureStorage.FindListByDict(new Dictionary { { "PartitionKey", "ScSchoolDiagnosis" }, { "RowKey", $"{ps.pid}-{schoolCode}" } }); if (teacherDiagnoses.IsNotEmpty()) { projects.Add(new ScsProjectDiagnosis { project = ps, diagnoses = teacherDiagnoses[0].abilityNos.ToObject>() }); } } } return new OkObjectResult(new { data = projects.ToJsonString() }); } } /// /// 5.3.1.19获取项目设置的可选能力点 /// /// /// /// [FunctionName("GetProjectDiagnosis")] public async Task GetProjectDiagnosis([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) { List projects = new List () ; string data = await new StreamReader(req.Body).ReadToEndAsync(); JsonElement accessConfig = data.ToObject().GetProperty("accessConfig"); ScAccessConfig config = $"{accessConfig}".ToObject(); Code = "GetProjectDiagnosis"; parameterMap = new Dictionary(); parameterMap.Add("TrainComID", config.trainComID); List results = new List(); try { if (config.p.IsNotEmpty()) { foreach (var ps in config.p) { parameterMap["ProjectID"] = ps.pd; parameterMap["ProjectItemID"] = ps.pid; ScsResult result = new ScsResult { code = Code, title = "5.3.1.19获取项目设置的可选能力点" }; result = await _thirdApisService.Post(config.url, Code, config.passKey, config.privateKey, parameterMap); if (result.result) { List diagnoses = result.content.ToObject>(); if (diagnoses.IsNotEmpty()) { projects.Add(new ScsProjectDiagnosis { project = ps, diagnoses = diagnoses }); await _azureStorage.SaveOrUpdate(new ScProjectDiagnosis { RowKey = $"{ps.pid}", PartitionKey = "ScProjectDiagnosis", abilityNos = diagnoses.ToJsonString() }); } } else { List teacherDiagnoses = await _azureStorage.FindListByDict(new Dictionary { { "PartitionKey", "ScProjectDiagnosis" }, { "RowKey", $"{ps.pid}" } }); if (teacherDiagnoses.IsNotEmpty()) { projects.Add(new ScsProjectDiagnosis { project = ps, diagnoses = teacherDiagnoses[0].abilityNos.ToObject>() }); } } results.Add(result); } } return new OkObjectResult(new { data = projects.ToJsonString() }); } catch (Exception ex) { if (config.p.IsNotEmpty()) { foreach (var ps in config.p) { //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},IES5.ScApisService:GetProjectDiagnosis\n{ex.Message}{ex.StackTrace}\n{results.ToJsonString()}\n{data}", GroupNames.成都开发測試群組); List teacherDiagnoses = await _azureStorage.FindListByDict(new Dictionary { { "PartitionKey", "ScProjectDiagnosis" }, { "RowKey", $"{ps.pid}" } }); if (teacherDiagnoses.IsNotEmpty()) { projects.Add(new ScsProjectDiagnosis { project = ps, diagnoses = teacherDiagnoses[0].abilityNos.ToObject>() }); } } } return new OkObjectResult(new { data = projects.ToJsonString() }); } } /// /// 5.3.1.3通过项目编号获取学员测评能力项V2 /// /// /// /// [FunctionName("GetDiagnosisListByProject_V2")] public async Task GetDiagnosisListByProject_V2([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) { List abilityNos = new List(); string data = await new StreamReader(req.Body).ReadToEndAsync(); JsonElement accessConfig= data.ToObject().GetProperty("accessConfig"); JsonElement pxid = data.ToObject().GetProperty("pxid"); ScAccessConfig config = $"{accessConfig}".ToObject(); Code = "GetDiagnosisListByProject_V2"; parameterMap = new Dictionary(); parameterMap.Add("TrainComID", config.trainComID); parameterMap.Add("PXID", pxid); ScsResult result = new ScsResult { code = Code, title = "5.3.1.3通过项目编号获取学员测评能力项V2" }; try { result = await _thirdApisService.Post(config.url, Code, config.passKey, config.privateKey, parameterMap); if (result.result) { List diagnoses = result.content.ToObject>(); if (diagnoses != null) { abilityNos = diagnoses.Select(x => x.DiagnosisDicNum).ToList(); } if (abilityNos .IsNotEmpty()) { await _azureStorage.SaveOrUpdate(new ScTeacherDiagnosis { RowKey = $"{pxid}", PartitionKey = "ScTeacherDiagnosis",abilityNos=abilityNos.ToJsonString() }); } } else { List teacherDiagnoses = await _azureStorage.FindListByDict(new Dictionary { { "PartitionKey", "ScTeacherDiagnosis" }, { "RowKey", $"{pxid}" } }); if (teacherDiagnoses.IsNotEmpty()) { abilityNos = teacherDiagnoses[0].abilityNos.ToObject>(); } } return new OkObjectResult(new { data= abilityNos .ToJsonString()}); } catch (Exception ex) { //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},IES5.ScApisService:getDiagnosisListByProject_V2\n{ex.Message}{ex.StackTrace}\n{result.ToJsonString()}\n{data}", GroupNames.成都开发測試群組); List teacherDiagnoses = await _azureStorage.FindListByDict(new Dictionary { { "PartitionKey", "ScTeacherDiagnosis" }, { "RowKey", $"{pxid}" } }); if (teacherDiagnoses.IsNotEmpty()) { abilityNos = teacherDiagnoses[0].abilityNos.ToObject>(); } return new OkObjectResult(new { data = abilityNos.ToJsonString() }); } } /// /// 5.3.1.11获取跳转学员信息,用于sso单点,后端验证。 /// /// /// /// [FunctionName("GetSingleTeacherByProject")] public async Task GetSingleTeacherByProject([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) { string teacher=null; string data = await new StreamReader(req.Body).ReadToEndAsync(); JsonElement accessConfig = data.ToObject().GetProperty("accessConfig"); JsonElement pxid = data.ToObject().GetProperty("pxid"); JsonElement tid = data.ToObject().GetProperty("tid"); ScAccessConfig config = $"{accessConfig}".ToObject(); Code = "GetSingleTeacherByProject"; parameterMap = new Dictionary(); parameterMap.Add("TrainComID", config.trainComID); parameterMap.Add("Pxid", $"{pxid}"); parameterMap.Add("Tid", $"{tid}"); ScsResult result = new ScsResult { code = Code, title = "5.3.1.11获取跳转学员信息,用于sso单点,后端验证。" }; try { ///{“result”:true,”reason”:null,”content”:”{“PXID”:””,”TID”:””,”TeacherName”:””,”ProjectTitle”:””,”ProjectItemTitle”:””,”CityName”:””, ///”DisName”:””,”SchoolName”:””,”Sex”:””,”PXXK”:””,”PXXD”:””,”TeacherXK”:””,”TeacherXD”:””,”Email”:””}”,”pagecount”:1} result = await _thirdApisService.Post(config.url, Code, config.passKey, config.privateKey, parameterMap); if (result.result) { teacher = result.content; } return new OkObjectResult(new {data= teacher }); } catch (Exception ex) { //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},IES5.ScApisService:GetSingleTeacherByProject\n{ex.Message}{ex.StackTrace}\n{result.ToJsonString()}\n{data}", GroupNames.成都开发測試群組); return new OkObjectResult(new { data = teacher }); } } public (int t53112OK, List> msgs) check53112(TeacherTrain teacherTrain, List> msgs) { //校验 基本情况是否满足 int t53112OK = 1; if (teacherTrain.finalScore < 0) { msgs.Add(new KeyValuePair("finalScore", $"最终评定结果参数:{teacherTrain.finalScore}")); t53112OK = 0; } if (string.IsNullOrEmpty(teacherTrain.summary) || teacherTrain.summary.Length > 300) { string msg = string.IsNullOrEmpty(teacherTrain.summary) ? "未填写" : teacherTrain.summary.Length > 300 ? "字数超过300." : ""; msgs.Add(new KeyValuePair("summary", $"教师培训总结:{msg}")); t53112OK = 0; } if (teacherTrain.totalTime <= 0) { msgs.Add(new KeyValuePair("totalTime", $"未获得学时:{teacherTrain.totalTime}")); t53112OK = 0; } return (t53112OK, msgs); } public (int t53112OK, List> msgs) check53113(TeacherTrain teacherTrain, List> msgs) { //校验 基本情况是否满足 int t53112OK = 1; if (teacherTrain.finalScore < 0) { msgs.Add(new KeyValuePair("finalScore", $"最终评定结果参数:{teacherTrain.finalScore}")); t53112OK = 0; } if (string.IsNullOrEmpty(teacherTrain.summary) || teacherTrain.summary.Length > 300) { string msg = string.IsNullOrEmpty(teacherTrain.summary) ? "未填写" : teacherTrain.summary.Length > 300 ? "字数超过300." : ""; msgs.Add(new KeyValuePair("summary", $"教师培训总结:{msg}")); t53112OK = 0; } if (teacherTrain.totalTime <= 0) { msgs.Add(new KeyValuePair("totalTime", $"未获得学时:{teacherTrain.totalTime}")); t53112OK = 0; } return (t53112OK, msgs); } } }