123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493 |
- using Azure.Messaging.ServiceBus;
- using HTEXLib.COMM.Helpers;
- using Microsoft.Extensions.Configuration;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK;
- using Azure.Cosmos;
- using TEAMModelOS.SDK.Models.Cosmos.Common;
- using Azure.Core;
- using TEAMModelOS.SDK.Models.Service;
- using Microsoft.AspNetCore.Http;
- using OpenXmlPowerTools;
- using DocumentFormat.OpenXml.Office2010.Excel;
- using DocumentFormat.OpenXml.Office2016.Excel;
- using static TEAMModelOS.SDK.Models.Cosmos.Student.StudentAnalysis;
- using HTEXLib.Helpers.ShapeHelpers;
- using DocumentFormat.OpenXml.Spreadsheet;
- namespace TEAMModelOS.FunctionV4.CosmosDB
- {
- public class TriggerArt
- {
- public static async Task Trigger(CoreAPIHttpService _coreAPIHttpService, AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
- CosmosClient client, JsonElement input, TriggerData tdata, AzureRedisFactory _azureRedis, IConfiguration _configuration, HttpTrigger _httpTrigger)
- {
- try
- {
- if ((tdata.status != null && tdata.status.Value == 404))
- {
- await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(tdata.id, new PartitionKey(tdata.code));
- ActivityList data = input.ToObject<ActivityList>();
- //删除blob 相关资料
- await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, tdata.school, new List<string> { $"art/{tdata.id}" });
- await ActivityService.DeleteActivity(_coreAPIHttpService, client, _dingDing, data);
- var table_cancel = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
- List<ChangeRecord> records = await table_cancel.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tdata.id } });
- foreach (var record in records)
- {
- try
- {
- await table_cancel.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
- await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
- }
- catch (Exception)
- {
- continue;
- }
- }
- return;
- }
- var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
- var adid = tdata.id;
- var adcode = "";
- string blobcntr = null;
- if (tdata.scope.Equals("school"))
- {
- adcode = $"Activity-{tdata.school}";
- blobcntr = tdata.school;
- }
- else
- {
- adcode = $"Activity-{tdata.creatorId}";
- blobcntr = tdata.creatorId;
- }
- ArtEvaluation art = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ArtEvaluation>(tdata.id, new Azure.Cosmos.PartitionKey($"{tdata.code}"));
- if (art != null)
- {
- string PartitionKey = string.Format("{0}{1}{2}", art.code, "-", art.progress);
- List<ChangeRecord> voteRecords = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tdata.id }, { "PartitionKey", PartitionKey } });
- switch (art.progress)
- {
- case "pending":
- var messageVote = new ServiceBusMessage(new { tdata.id, progress = "going", code = tdata.code }.ToJsonString());
- messageVote.ApplicationProperties.Add("name", "Art");
- if (voteRecords.Count > 0)
- {
- long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVote, DateTimeOffset.FromUnixTimeMilliseconds(tdata.startTime));
- try
- {
- await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), voteRecords[0].sequenceNumber);
- }
- catch (Exception)
- {
- }
- voteRecords[0].sequenceNumber = start;
- await table.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
- }
- else
- {
- long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVote, DateTimeOffset.FromUnixTimeMilliseconds(tdata.startTime));
- ChangeRecord changeRecord = new ChangeRecord
- {
- RowKey = tdata.id,
- PartitionKey = PartitionKey,
- sequenceNumber = start,
- msgId = messageVote.MessageId
- };
- await table.Save<ChangeRecord>(changeRecord);
- }
- break;
- case "going":
- if (art.classes.Count > 0)
- {
- List<string> classes = ExamService.getClasses(art.classes, art.stuLists);
- (List<RMember> tmdIds, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, classes, art.school, null);
- var addStudentsCls = tmdIds.FindAll(x => x.type == 2);
- var addTmdidsCls = tmdIds.FindAll(x => x.type == 1);
- List<string> tmds = new List<string>();
- if (addTmdidsCls.IsNotEmpty())
- {
- tmds.AddRange(addTmdidsCls.Select(x => x.id).ToList());
- }
- List<StuActivity> stuActivities = new List<StuActivity>();
- List<StuActivity> tmdActivities = new List<StuActivity>();
- List<StuActivity> tchActivities = new List<StuActivity>();
- List<string> sub = new();
- if (art.subjects.Count > 0)
- {
- foreach (var course in art.subjects)
- {
- sub.Add(course.id);
- }
- }
- if (tmds.IsNotEmpty())
- {
- tmds.ForEach(x =>
- {
- HashSet<string> classIds = new HashSet<string>();
- classLists.ForEach(z =>
- {
- z.members.ForEach(y =>
- {
- if (y.id.Equals(x) && y.type == 1)
- {
- classIds.Add(z.id);
- }
- });
- });
- tmdActivities.Add(new StuActivity
- {
- pk = "Activity",
- id = art.id,
- code = $"Activity-{x}",
- type = "Art",
- name = art.name,
- startTime = art.startTime,
- endTime = art.endTime,
- scode = art.code,
- scope = art.scope,
- school = art.school,
- creatorId = art.creatorId,
- subjects = sub,
- blob = null,
- owner = art.owner,
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- ext = new Dictionary<string, JsonElement>() { { "subjects", art.subjects.ToJsonString().ToObject<JsonElement>() } },
- taskStatus = -1,
- classIds = classIds.ToList()
- });
- });
- }
- if (addStudentsCls.IsNotEmpty())
- {
- addStudentsCls.ForEach(x =>
- {
- HashSet<string> classIds = new HashSet<string>();
- classLists.ForEach(z =>
- {
- z.members.ForEach(y =>
- {
- if (y.id.Equals(x.id) && y.code.Equals(art.school) && y.type == 2)
- {
- classIds.Add(z.id);
- }
- });
- });
- stuActivities.Add(new StuActivity
- {
- pk = "Activity",
- id = art.id,
- code = $"Activity-{x.code.Replace("Base-", "")}-{x.id}",
- type = "Atr",
- name = art.name,
- startTime = art.startTime,
- endTime = art.endTime,
- scode = art.code,
- scope = art.scope,
- school = art.school,
- creatorId = art.creatorId,
- subjects = sub,
- blob = null,
- owner = art.owner,
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- ext = new Dictionary<string, JsonElement>() { { "subjects", art.subjects.ToJsonString().ToObject<JsonElement>() } },
- taskStatus = -1,
- classIds = classIds.ToList()
- });
- });
- }
- await ActivityService.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities, tchActivities);
- //await StatisticsService.SendServiceBus(list, _configuration, _serviceBus, client)
- }
- var messageVoteEnd = new ServiceBusMessage(new { tdata.id, progress = "finish", tdata.code }.ToJsonString());
- messageVoteEnd.ApplicationProperties.Add("name", "Art");
- if (voteRecords.Count > 0)
- {
- long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.endTime));
- try
- {
- await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), voteRecords[0].sequenceNumber);
- }
- catch (Exception)
- {
- }
- voteRecords[0].sequenceNumber = end;
- await table.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
- }
- else
- {
- long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.endTime));
- ChangeRecord changeRecord = new()
- {
- RowKey = tdata.id,
- PartitionKey = PartitionKey,
- sequenceNumber = end,
- msgId = messageVoteEnd.MessageId
- };
- await table.Save<ChangeRecord>(changeRecord);
- }
- break;
- case "finish":
- //判定是否是区级创建的活动内容
- /* if (art.lost.Count == 0 && art.pass == 0)
- {
- if (art.owner.Equals("area") && string.IsNullOrEmpty(art.pId))
- {
- *//* List<(string id, string code, List<Tasks> settings)> artSchools = new();
- string ql = $"select c.id,c.school,c.settings,c.classes from c where c.pk = 'Art' and c.pId = '{art.id}'";
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: ql))
- {
- 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;
- List<Tasks> settings = account.GetProperty("settings").ToObject<List<Tasks>>();
- artSchools.Add((account.GetProperty("id").GetString(), account.GetProperty("school").GetString(), settings));
- }
- }
- }
- foreach (var (id, code, settings) in artSchools)
- {
- List<(string eId, string sId)> ids = new();
- var examIds = settings.SelectMany(s => s.task).Where(a => a.type == 1).Select(z => new { z.acId, z.subject }).ToList();
- examIds.ForEach(x =>
- {
- ids.Add((x.acId, x.subject));
- });
- List<(string code, string sub, List<string> stu)> stuInfo = await getLostAsync(ids, client, code);
- List<string> stus = new();
- foreach (var lost in stuInfo)
- {
- if (stus.Count == 0)
- {
- stus = stus.Union(lost.stu).ToList();
- }
- else {
- stus = stus.Intersect(lost.stu).ToList();
- }
- LostStudent lostStudent = new()
- {
- code = lost.code,
- subject = lost.sub,
- stu = lost.stu.Count
- };
- art.lost.Add(lostStudent);
- }
- art.miss.Add(stus.Count);
- }
- art.pass = 1;
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ArtEvaluation>(art, art.id, new PartitionKey(art.code));*//*
- }
- else
- {
- //获取当前艺术评价相关评测ID目前暂时排除区级发布的评测信息
- *//*List<(string eId, string sId)> ids = new();
- var examId = art.settings.SelectMany(x => x.task).Where(c => c.type == 1).Select(z => new { z.acId, z.subject }).ToList();
- examId.ForEach(x =>
- {
- ids.Add((x.acId, x.subject));
- });
- List<(string code, string sub, List<string> stu)> stuInfo = await getLostAsync(ids, client, art.school);
- List<string> stus = new();
- foreach (var (code, sub, stu) in stuInfo)
- {
- if (stus.Count == 0)
- {
- stus = stus.Union(stu).ToList();
- }
- else
- {
- stus = stus.Intersect(stu).ToList();
- }
- LostStudent lostStudent = new()
- {
- code = code,
- subject = sub,
- stu = stu.Count
- };
- art.lost.Add(lostStudent);
- }
- art.miss.Add(stus.Count);
- //art.miss = stus.Count;
- art.pass = 1;
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ArtEvaluation>(art, art.id, new PartitionKey(art.code));*//*
- }
- }*/
- List<StudentArtResult> studentArtResults = new();
- string sql = $"SELECT value c FROM c where c.pk='ArtResult' ";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Student)
- .GetItemQueryIterator<StudentArtResult>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"ArtResult-{art.id}") }))
- {
- studentArtResults.Add(item);
- }
- //根据学校编码去获取区级ID
- School scInfo = new();
- //School scInfo = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{art.school}", partitionKey: new Azure.Cosmos.PartitionKey("Base"));
- var response = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{art.school}", partitionKey: new Azure.Cosmos.PartitionKey("Base"));
- if (response.Status == 200)
- {
- using var cJson = await JsonDocument.ParseAsync(response.ContentStream);
- scInfo = cJson.ToObject<School>();
- }
- ArtSetting setting = new();
- try
- {
- var artResponse = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{scInfo.areaId}", partitionKey: new Azure.Cosmos.PartitionKey("ArtSetting"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(artResponse.ContentStream);
- setting = json.ToObject<ArtSetting>();
- }
- }
- catch (Exception e)
- {
- }
- List<Task<ItemResponse<StudentArtResult>>> tasks = new List<Task<ItemResponse<StudentArtResult>>>();
- //新增数据推送 obj => Portrait
- Portrait portrait = new()
- {
- schoolCode = art.school,
- periodId = art.period.id,
- subjectId = "subject_art"
- };
- var period = scInfo.period.Where(x => x.id.Equals(art.period.id)).FirstOrDefault();
- //获取学期信息
- var (currSemester, studyYear, date, nextSemester) = SchoolService.GetSemester(period, art.startTime);
- //总分的占比情况
- foreach (var rs in studentArtResults)
- {
- foreach (var res in rs.results) {
- if (res.quotaId.Equals("quota_21") && res.score > -1 && res.score < 95) {
- /*res.score *= 1.5;
- if (res.score >= 95) {
- res.score = new Random().Next(90, 99);
- }*/
- res.score = Math.Round(res.score);
- }
- }
-
- //if (rs.totalScore == 0)
- //{
- foreach (var sc in rs.subjectScores)
- {
- //if (sc.score == 0)
- //{
- /* var subjectMore = rs.results.GroupBy(x => x.subjectId).Select(c => new { subject = c.Key, list = c.ToList().Select(m => new { m.quotaId,m.score}) });
- var totalScore = subjectMore.Select(x => new {
- x.subject,
- quotaScroe = x.list.Select(c => new {
- c.quotaId,
- c.score
- }),
- });*/
- var quotaPercent = setting.quotas.Select(x => new
- {
- x.id,
- x.percent,
- score = x.children.Select(c => new
- {
- real = rs.results.Where(r => r.quotaId.Equals(c.id) && r.subjectId.Equals(sc.subjectId) && r.score > -1).FirstOrDefault()?.score * c.percent * 0.01,
- score = c.children.Select(s => new
- {
- real = rs.results.Where(r => r.quotaId.Equals(s.id) && r.subjectId.Equals(sc.subjectId) && r.score > -1).FirstOrDefault()?.score * s.percent * 0.01
- }).Sum(n => n.real) * c.percent * 0.01
- }).Sum(n => n.real + n.score) * x.percent * 0.01
- });
- double realScore = Math.Round((double)quotaPercent.Sum(c => c.score),2);
- sc.score = realScore;
- //}
- }
- rs.totalScore = Math.Round(rs.subjectScores.Where(m => m.score >= 0).Sum(z => z.score),2);
- tasks.Add(client.GetContainer(Constant.TEAMModelOS, Constant.Student).ReplaceItemAsync(rs, rs.id, new PartitionKey(rs.code)));
- PortraitStudent student = new()
- {
- studentId = rs.studentId,
- name = rs.studentName,
- classId = rs.classIds[0]
- };
- SemesterData semesterData = new()
- {
- examName = art.name,
- examId = art.id,
- examDate = art.startTime,
- examType = "",
- year = studyYear,
- semesterId = currSemester.id,
- totalScore = 200,
- sumScore = rs.totalScore,
- excellenceRate = 0,
- passRate = 0,
- };
- int index = 0;
- foreach (var sj in art.subjects)
- {
- ItemScore item = new()
- {
- name = sj.name,
- score = rs.subjectScores.Where(x => x.subjectId.Equals(sj.id)).FirstOrDefault().score,
- time = art.startTime,
- totalScore = 100,
- type = sj.id
- };
- index++;
- semesterData.itemScore.Add(item);
- }
- student.semesterData.Add(semesterData);
- portrait.students.Add(student);
- //}
- }
- if (tasks.Count > 0)
- {
- await Task.WhenAll(tasks);
- }
-
- //获取学生信息
- //(List<RMember> rmembers, List<RGroupList> groups) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, art.classes, art.school);
- /* foreach (var member in studentArtResults)
- {
-
- }*/
- string location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
- var responseData = await _httpTrigger.RequestHttpTrigger(portrait.ToJson(), location, "upsert-student-portrait");
- break;
- }
- }
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.Status}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}艺术评价异常{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- }
- }
- }
- }
|