1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675 |
- using Azure.Cosmos;
- using Azure.Messaging.ServiceBus;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK.Models.Service;
- using HTEXLib.COMM.Helpers;
- using ClouDASLibx;
- using System.Text.Json;
- using System.Collections.Generic;
- using System.Threading.Tasks;
- using System;
- using System.Linq;
- using TEAMModelOS.SDK.Models.Service.BI;
- using Azure.Storage.Blobs.Models;
- using System.IO;
- using System.Text;
- using System.Text.Json.Nodes;
- using TEAMModelOS.SDK.Helper.Common.JsonHelper.JsonPath;
- using Newtonsoft.Json.Linq;
- using TEAMModelOS.SDK.Models.Cosmos.Student;
- using HTEXLib.Helpers.ShapeHelpers;
- using TEAMModelOS.Models.Dto;
- using TEAMModelOS.SDK.Models.Cosmos.Common;
- using DocumentFormat.OpenXml.Office2010.Excel;
- using DocumentFormat.OpenXml.Drawing.Charts;
- using DocumentFormat.OpenXml.Vml;
- using System.Net.Http;
- using Newtonsoft.Json;
- using System.Net;
- using System.Security.Policy;
- using Microsoft.Extensions.Configuration;
- using DocumentFormat.OpenXml.EMMA;
- using Microsoft.Extensions.Options;
- using TEAMModelOS.Models;
- namespace TEAMModelOS.FunctionV4
- {
- public class TriggerExam
- {
- public static async Task Trigger(CoreAPIHttpService _coreAPIHttpService, AzureCosmosFactory _azureCosmos, AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
- CosmosClient client, JsonElement input, TriggerData data, IHttpClientFactory _httpClient, IConfiguration _configuration, HttpTrigger _httpTrigger)
- {
- List<ExamClassResult> examClassResults = new();
- List<ExamSubject> examSubjects = new();
- try
- {
- if ((data.status != null && data.status.Value == 404))
- {
- await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(data.id, new PartitionKey(data.code));
- ActivityList activity = input.ToObject<ActivityList>();
- await ActivityService.DeleteActivity(_coreAPIHttpService, client, _dingDing, activity);
- var table_cancel = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
- List<ChangeRecord> records = await table_cancel.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", data.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;
- }
- }
- await BIStats.SetTypeAddStats(client, _dingDing, data.school, "Exam", -1, careDate: data.startTime);//BI统计增/减量
- return;
- }
- ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(data.id, new Azure.Cosmos.PartitionKey($"{data.code}"));
- if (info != null)
- {
- if (info.scope.Equals("teacher", StringComparison.OrdinalIgnoreCase) || info.scope.Equals("private", StringComparison.OrdinalIgnoreCase))
- {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: $"select value(c) from c where c.examId = '{info.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamClassResult-{info.creatorId}") }))
- {
- 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())
- {
- examClassResults.Add(obj.ToObject<ExamClassResult>());
- }
- }
- }
- }
- else
- {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: $"select value(c) from c where c.examId = '{info.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamClassResult-{data.school}") }))
- {
- 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())
- {
- examClassResults.Add(obj.ToObject<ExamClassResult>());
- }
- }
- }
- }
- var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
- string PartitionKey = string.Format("{0}{1}{2}", info.code, "-", info.progress);
- List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", data.id }, { "PartitionKey", PartitionKey } });
- //处理科目信息
- List<string> sub = new List<string>();
- School sc = new();
- if (!string.IsNullOrEmpty(info.school)) {
- sc = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(info.school, new Azure.Cosmos.PartitionKey("Base"));
- }
-
- foreach (ExamSubject subject in info.subjects)
- {
- sub.Add(subject.id);
- }
- //整合名单
- List<string> classes = ExamService.getClasses(info.classes, info.stuLists);
- //ChangeRecord record = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ChangeRecord>(input.Id, new Azure.Cosmos.PartitionKey($"{info.progress}"));
- switch (info.progress)
- {
- case "pending":
- var message = new ServiceBusMessage(new { id = data.id, progress = "going", code = data.code }.ToJsonString());
- message.ApplicationProperties.Add("name", "Exam");
- if (records.Count > 0)
- {
- try
- {
- await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), records[0].sequenceNumber);
- }
- catch (Exception)
- {
- }
- long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(data.startTime));
- records[0].sequenceNumber = start;
- await table.SaveOrUpdate<ChangeRecord>(records[0]);
- //await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(record, record.id, new Azure.Cosmos.PartitionKey($"{record.code}"));
- }
- else
- {
- long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(data.startTime));
- //string pk = String.Format("{0}{1}{2}", info.code, "-", "pending");
- ChangeRecord changeRecord = new ChangeRecord
- {
- RowKey = data.id,
- PartitionKey = PartitionKey,
- sequenceNumber = start,
- msgId = message.MessageId
- };
- await table.Save<ChangeRecord>(changeRecord);
- //await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
- }
- break;
- case "going":
- try
- {
- //向学生或醍摩豆账号发起通知
- #region
- //Notice notice = new Notice()
- //{
- // msgId = info.id,
- // creation = info.startTime,
- // expire = info.endTime,
- // creatorId = info.creatorId,
- // stuids = studentss,
- // tmdids = tmdids,
- // type = "notice",//评测参加通知
- // priority = "normal",
- // school = info.school,
- // scope = info.scope,
- // //data = new { }.ToJsonString()
- // body = new Body { sid = info.id, scode = info.code, spk = info.pk, biztype = "exam-join" }
- //};
- //var messageBlob = new ServiceBusMessage(notice.ToJsonString());
- //messageBlob.ApplicationProperties.Add("name", "Notice");
- //await _serviceBus.GetServiceBusClient().SendMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageBlob);
- #endregion
- //List<string> classes = new List<string>();
- //处理活动中间件
- List<RGroupList> members = await Activity(_coreAPIHttpService, info, classes, client, _dingDing, sub, examClassResults);
- if (examClassResults.Count == 0)
- {
- foreach (string cla in classes)
- {
- int m = 0;
- RGroupList rGroup = new();
- rGroup = members.Where(m => m.id.Equals(cla)).FirstOrDefault();
- foreach (ExamSubject subject in info.subjects)
- {
- string classCode = string.Empty;
- string cname = string.Empty;
- if (string.IsNullOrEmpty(info.school) || !info.scope.Equals("school", StringComparison.OrdinalIgnoreCase))
- {
- classCode = "ExamClassResult-" + info.creatorId;
- }
- else
- {
- classCode = "ExamClassResult-" + info.school;
- }
- cname = members.Where(m => m.id.Equals(cla)).FirstOrDefault()?.name;
- // 预处理活动中间件信息
- ExamClassResult result = new()
- {
- code = classCode,
- examId = info.id,
- id = Guid.NewGuid().ToString(),
- subjectId = subject.id,
- year = info.year,
- scope = info.scope
- };
- result.info.id = cla;
- result.info.name = cname;
- List<string> ans = new();
- List<List<string>> anses = new();
- List<List<Details>> marks = new();
- List<double> ansPoint = new();
- List<(string sId, string scode)> ids = new();
- foreach (double p in info.papers[m].point)
- {
- //Details details = new Details();
- //ans.Add(new List<string>());
- anses.Add(new List<string>());
- marks.Add(new List<Details>());
- ansPoint.Add(-1);
- }
- var sresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"Class-{info.school}"));
- if (sresponse.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
- Class classroom = json.ToObject<Class>();
-
- foreach (SDK.Models.Period period in sc.period)
- {
- if (period.id.Equals(classroom.periodId))
- {
- foreach (Semester semester in period.semesters)
- {
- if (semester.start == 1)
- {
- int year = DateTimeOffset.UtcNow.Year;
- int month = DateTimeOffset.UtcNow.Month;
- int day = DateTimeOffset.UtcNow.Day;
- int time = 0;
- if (month == semester.month)
- {
- time = day >= semester.day ? 0 : 1;
- }
- else
- {
- time = month > semester.month ? 0 : 1;
- }
- int eyear = year - time;
- result.gradeId = (eyear - classroom.year).ToString();
- }
- }
- }
- }
- //result.info.id = classroom.id;
- //result.info.name = classroom.name;
- //result.gradeId = classroom.year.ToString();
- //处理班级人数
- /* await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: $"select c.id from c where c.classId = '{classroom.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{info.school}") }))
- {
- using var json_stu = await JsonDocument.ParseAsync(item.ContentStream);
- if (json_stu.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json_stu.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- ids.Add(account.GetProperty("id").GetString());
- }
- }
- }*/
- }
- /*if (info.scope.Equals("private", StringComparison.OrdinalIgnoreCase))
- {
- var stuResponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"GroupList"));
- if (stuResponse.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(stuResponse.ContentStream);
- GroupList stuList = json.ToObject<GroupList>();
- //result.info.id = stuList.id;
- result.info.name = stuList.name;
- //处理发布对象为自选名单(个人)
- foreach (Member stus in stuList.members)
- {
- if (!ids.Contains(stus.id))
- {
- ids.Add(stus.id);
- }
- }
- }
- }
- else
- {
- var stuResponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"GroupList-{info.school}"));
- if (stuResponse.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(stuResponse.ContentStream);
- GroupList stuList = json.ToObject<GroupList>();
- //result.info.id = stuList.id;
- result.info.name = stuList.name;
- //处理发布对象为自选名单(校本)
- foreach (Member stus in stuList.members)
- {
- if (!ids.Contains(stus.id))
- {
- ids.Add(stus.id);
- }
- }
- }
- }*/
- foreach (RMember member in rGroup.members)
- {
- ids.Add((member.id, member.code));
- }
- //ids = members.Where(c => c.id.Equals(cla)).SelectMany(m => m.members).Select(g => g.id).ToList();
- foreach (var (sId, scode) in ids)
- {
- result.mark.Add(marks);
- result.studentIds.Add(sId);
- //result.scIds.Add(scode ?? "");
- result.studentAnswers.Add(ans);
- result.studentScores.Add(ansPoint);
- result.ans.Add(anses);
- result.sum.Add(0);
- result.status.Add(1);
- }
- //result.progress = info.progress;
- result.school = info.school;
- m++;
- await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(result, new Azure.Cosmos.PartitionKey($"{result.code}"));
- }
- }
- }
- else
- {
- //处理单科结算时科目与试卷信息匹配的问题
- int gno = 0;
- foreach (ExamSubject subject in info.subjects)
- {
- if (subject.classCount == classes.Count)
- {
- await createClassResultAsync(info, examClassResults, subject, gno, _azureCosmos, _dingDing, _azureStorage, _httpClient, _configuration);
- }
- gno++;
- }
- var isScore = examClassResults.SelectMany(e => e.studentScores).ToList().Exists(c => c.Contains(-1));
- int newStatus = 0;
- if (!isScore)
- {
- newStatus = 1;
- }
- Settlement settlement = await getMore(client, info);
- long nowTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- //判断评分状态是否发生变化,便于实时的更新评测基本信息
- if (info.average != settlement.score || info.sStatus != newStatus)
- {
- info.sRate = settlement.rate;
- info.sStatus = newStatus;
- info.updateTime = nowTime;
- info.average = settlement.score;
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ExamInfo>(info, info.id, new PartitionKey(info.code));
- }
- }
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测going状态异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- }
- finally
- {
- // 发送信息通知
- var messageEnd = new ServiceBusMessage(new { id = data.id, progress = "finish", code = data.code }.ToJsonString());
- messageEnd.ApplicationProperties.Add("name", "Exam");
- if (records.Count > 0)
- {
- long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(data.endTime));
- try
- {
- await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), records[0].sequenceNumber);
- }
- catch (Exception)
- {
- }
- records[0].sequenceNumber = end;
- await table.SaveOrUpdate<ChangeRecord>(records[0]);
- //await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(record, record.id, new Azure.Cosmos.PartitionKey($"{record.code}"));
- }
- else
- {
- long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(data.endTime));
- //string pk = String.Format("{0}{1}{2}", info.code, "-", "going");
- ChangeRecord changeRecord = new ChangeRecord
- {
- RowKey = data.id,
- PartitionKey = PartitionKey,
- sequenceNumber = end,
- msgId = messageEnd.MessageId
- };
- await table.Save<ChangeRecord>(changeRecord);
- //await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
- }
- }
- break;
- case "finish":
- int fno = 0;
- try
- {
- //用来判定是否完成评分
- //bool isScore = true;
- await resultStatus(client, examClassResults);
-
- await Activity(_coreAPIHttpService, info, classes, client, _dingDing, sub, examClassResults);
- foreach (ExamSubject subject in info.subjects)
- {
- await createClassResultAsync(info, examClassResults, subject, fno, _azureCosmos, _dingDing, _azureStorage, _httpClient, _configuration);
- fno++;
- }
- Settlement settlement = await getMore(client, info);
- var isScore = examClassResults.SelectMany(e => e.studentScores).ToList().Exists(c => c.Contains(-1));
- int newStatus = 0;
- if (!isScore)
- {
- newStatus = 1;
- }
- //判断均分是否发生变化,便于实时的更新评测基本信息
- if (info.sRate != settlement.rate || info.average != settlement.score || info.sStatus != newStatus || info.qRate != settlement.qrate)
- {
- info.sRate = settlement.rate;
- info.average = settlement.score;
- info.sStatus = newStatus;
- info.lostStu = settlement.stus;
- info.stuCount = settlement.total;
- info.qRate = settlement.qrate;
- //新增数据推送 obj => Portrait
- Portrait portrait = new()
- {
- schoolCode = info.school,
- periodId = info.period.id,
- subjectId = "subject_exam"
- };
- var period = sc.period.Where(x => x.id.Equals(info.period.id)).FirstOrDefault();
- //获取学期信息
- var (currSemester, studyYear, date, nextSemester) = SchoolService.GetSemester(period, info.startTime);
- //获取学生信息
- (List<RMember> rmembers, List<RGroupList> groups) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, info.classes, info.school);
- foreach (var member in rmembers) {
- if (info.lostStu.Contains(member.id)) {
- continue;
- }
- PortraitStudent student = new()
- {
- studentId = member.id,
- name = member.name,
- classId = member.classId
- };
- SemesterData semesterData = new()
- {
- examName = info.name,
- examId = info.id,
- examDate = info.startTime,
- examType = info.examType?.name,
- year = info.year,
- semesterId = currSemester.id,
- totalScore = info.papers.SelectMany(x => x.point).Sum(),
- sumScore = examClassResults.SelectMany(x => x.sum).Sum(),
- excellenceRate = 0,
- passRate = 0,
- };
- int index = 0;
- foreach (var sj in info.subjects) {
- ItemScore item = new()
- {
- name = sj.name,
- score = examClassResults.Where(x => x.subjectId.Equals(sj.id)).FirstOrDefault().sum.Sum(),
- time = info.startTime,
- totalScore = info.papers[index].point.Sum(),
- type = sj.id
- };
- index++;
- semesterData.itemScore.Add(item);
- }
- student.semesterData.Add(semesterData);
- portrait.students.Add(student);
- }
- string location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
- var (status, json) = await _httpTrigger.RequestHttpTrigger(portrait.ToJson(), location, "upsert-student-portrait");
- //PortraitStudent student = new();
- //处理试卷活动结束统计账户信息
- List<FMember> idList = await GroupListService.GetFinishMemberInfo(_coreAPIHttpService, client, _dingDing, info.school, info.classes, info.stuLists, null);
- info.staffIds = idList;
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ExamInfo>(info, info.id, new Azure.Cosmos.PartitionKey(info.code));
- }
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测finish状态异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- }
- break;
- }
- }
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.Status}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-评测结算异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- }
- }
- public static async Task resultStatus(CosmosClient client, List<ExamClassResult> examClassResults)
- {
- List<Task<ItemResponse<ExamClassResult>>> tasks = new();
- //结算单科单班的标准差和平均分
- foreach (ExamClassResult classResult in examClassResults)
- {
- //标记单科单班总得分
- double subScore = 0;
- //标准差
- double sPowSum = 0;
- List<double> newSumScore = new List<double>();
- List<double> effectiveScore = new List<double>();
- int lostStu = classResult.status.Where(c => c == 1).ToList().Count;
- var scount = classResult.studentIds.Count - lostStu;
- int index = 0;
- if (classResult.status.Count > 0)
- {
- foreach (var sta in classResult.status)
- {
- if (sta == 1)
- {
- for (int i = 0; i < classResult.studentScores[index].Count; i++)
- {
- if (classResult.studentScores[index][i] == -1)
- {
- classResult.studentScores[index][i] = 0;
- }
- }
- }
- else if (sta == 0)
- {
- //var ans = classResult.studentAnswers[index];
- //该学生缺考,历史数据的判定
- //if (ans.Count == 0)
- //{
- for (int i = 0; i < classResult.studentScores[index].Count; i++)
- {
- if (classResult.studentScores[index][i] == -1)
- {
- classResult.studentScores[index][i] = 0;
- }
- }
- /*if (ans.Count == 0)
- {
- classResult.status[index] = 1;
- } */
- //}
- }
- index++;
- }
- }
- else
- {
- List<int> sta = new();
- foreach (var id in classResult.studentIds)
- {
- sta.Add(0);
- }
- classResult.status = sta;
- foreach (var ans in classResult.studentAnswers)
- {
- //该学生缺考,历史数据的判定
- if (ans.Count == 0)
- {
- for (int i = 0; i < classResult.studentScores[index].Count; i++)
- {
- if (classResult.studentScores[index][i] == -1)
- {
- classResult.studentScores[index][i] = 0;
- }
- }
- classResult.status[index] = 1;
- }
- index++;
- }
- }
- int sIndex = 0;
- foreach (List<double> sc in classResult.studentScores)
- {
- List<double> newSc = new List<double>();
- foreach (double ssc in sc)
- {
- if (ssc == -1)
- {
- newSc.Add(0);
- }
- else
- {
- newSc.Add(ssc);
- }
- }
- double nc = Math.Round(newSc.Sum(), 2);
- if (classResult.status[sIndex] == 0)
- {
- effectiveScore.Add(nc);
- };
- newSumScore.Add(nc);
- subScore += nc;
- classResult.sum[sIndex] = nc;
- sIndex++;
- }
- double rateScore = scount > 0 ? Math.Round(subScore * 1.0 / scount, 2) : 0;
- //有效分数
- foreach (double scs in effectiveScore)
- {
- sPowSum += Math.Pow(scs - rateScore, 2);
- }
- classResult.standard = Math.Round(scount > 0 ? Math.Pow(sPowSum / scount, 0.5) : 0, 2);
- classResult.average = scount > 0 ? Math.Round(subScore / scount, 2) : 0;
- classResult.progress = true;
- tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new PartitionKey($"{classResult.code}")));
- }
- await Task.WhenAll(tasks);
- }
- public static async Task<Settlement> getMore(CosmosClient client, ExamInfo info)
- {
- //计算单次考试简易统计信息
- Settlement settlement = new();
- List<ExamResult> examResults = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamResult>(
- queryText: $"select value(c) from c where c.examId = '{info.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}") }))
- {
- examResults.Add(item);
- }
- if (examResults.Count > 0)
- {
- //记录某次考试所有学生得分总分
- double score = 0;
- double allScore = 0;
- int stuCount = 0;
- //标准差
- double powSum = 0;
- List<string> losStu = new List<string>();
- //当前完成考试得人数
- int total = examResults[0].studentIds.Distinct().Count();
- //先与第一个值取并集
- losStu = losStu.Union(examResults[0].lostStus).ToList();
- foreach (ExamResult examResult in examResults)
- {
- //取交集
- losStu = losStu.Intersect(examResult.lostStus).ToList();
- }
- //处理缺考的学生
- List<string> stus = examResults[0].studentIds.Except(losStu).ToList();
- foreach (ExamResult examResult in examResults)
- {
- foreach (var id in stus)
- {
- int index = examResult.studentIds.IndexOf(id);
- score += examResult.studentScores[index].Sum();
- }
- }
- stuCount = total - losStu.Count;
- double NewsRateScore = stuCount > 0 ? Math.Round(score * 1.0 / stuCount, 2) : 0;
- foreach (PaperSimple simple in info.papers)
- {
- allScore += simple.point.Sum();
- }
- //计算全科标准差
- foreach (string id in stus)
- {
- double sc = 0;
- foreach (ExamResult result in examResults)
- {
- if (result.studentScores.Count > 0)
- {
- sc += result.studentScores[result.studentIds.IndexOf(id)].Sum();
- }
- }
- powSum += Math.Pow(sc - NewsRateScore, 2);
- }
- info.standard = Math.Round(total - losStu.Count > 0 ? Math.Pow(powSum / (total - losStu.Count), 0.5) : 0, 2);
- double NewsRate = allScore > 0 ? Math.Round(NewsRateScore / allScore * 100, 2) : 0;
- double qrate = Math.Round(total > 0 ? losStu.Count * 1.0 / total * 100 : 0, 2);
- settlement.rate = NewsRate;
- settlement.score = NewsRateScore;
- settlement.stus = losStu;
- settlement.total = total;
- settlement.qrate = qrate;
- }
- return settlement;
- }
- //处理全部学生选题计数
- public static async Task examRecordCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, ExamResult er, List<ExamClassResult> classResults, AzureCosmosFactory _azureCosmos)
- {
- try
- {
- List<double> scores = new List<double>();
- foreach (List<double> sc in er.studentScores)
- {
- scores.Add(sc.Sum());
- }
- //确定高分组 最低分数
- //var srowallorder = scores.EnumerateIndexed().OrderByDescending(g => g.Item2); //各生總分排序
- //var srowallorder = scores.OrderByDescending(g => g);
- double[] point = StringHelper.ListTodouble(er.paper.point);
- double[,] result = StringHelper.ListToDouble(er.studentScores);
- var cdm = new ClouDASMatrix(result, point);
- scores.Sort((s1, s2) => { return s2.CompareTo(s1); });
- int rhwCount = cdm.SH.Count();
- double rhw = cdm.SH.LastOrDefault().Item2;
- int rhlCount = cdm.SL.Count();
- double rhl = cdm.SL.FirstOrDefault().Item2;
- List<string> phs = new();
- List<string> pls = new();
- //分别获取高分组低分组人员
- foreach (var ph in cdm.SH)
- {
- phs.Add(er.studentIds[ph.Item1]);
- }
- foreach (var pl in cdm.SL)
- {
- pls.Add(er.studentIds[pl.Item1]);
- }
- /* if (scores.Count > 3)
- {
- rhwCount = Convert.ToInt32(Math.Floor(scores.Count * 0.27));
- rhw = rhwCount > 0 ? scores[rhwCount - 1] : 0;
- rhlCount = Convert.ToInt32(Math.Ceiling(scores.Count * 0.73));
- rhl = rhlCount > 0 ? scores[rhlCount] : 0;
- }
- else
- {
- rhwCount = Convert.ToInt32(Math.Floor(scores.Count * 0.27));
- rhw = rhwCount > 0 ? scores[rhwCount] : 0;
- rhlCount = Convert.ToInt32(Math.Ceiling(scores.Count * 0.73));
- rhl = rhlCount > 0 ? scores[rhlCount - 1] : 0;
- }*/
- /*int rhwCount = Convert.ToInt32(Math.Floor(scores.Count * 0.27));
- double rhw = rhwCount > 0 ? scores[rhwCount-1] : 0;
- //var rhww = srowallorder.Take(Convert.ToInt32(Math.Floor(scores.Count * 0.27)));
- //确定低分组 最高分数
- //scores.Sort((s1, s2) => { return s1.CompareTo(s2); });
- int rhlCount = Convert.ToInt32(Math.Ceiling(scores.Count * 0.73));
- double rhl = rhlCount > 0 ? scores[rhlCount-1] : 0;*/
- //var rhll = srowallorder.Skip(Convert.ToInt32(Math.Ceiling(scores.Count * 0.73)));
- //存放高分组学生ID
- List<string> phId = new();
- List<string> plId = new();
- List<List<List<string>>> opth = new();
- List<List<List<string>>> optl = new();
- List<double> akp = await knowledgeCount(info, subject, _dingDing, no, classResults, rhwCount, rhw, rhlCount, rhl, _azureCosmos);
- List<double> afp = await fieldCount(info, subject, _dingDing, no, classResults, rhwCount, rhw, rhlCount, rhl, _azureCosmos);
- int PHCount = 0;
- int PLCount = 0;
- foreach (ExamClassResult classResult in classResults)
- {
- if (classResult.subjectId.Equals(subject.id))
- {
- foreach (string id in classResult.studentIds)
- {
- int index = classResult.studentIds.IndexOf(id);
- if (classResult.studentScores.Count > 0)
- {
- if (phs.Contains(id))
- {
- if (classResult.ans.Count > 0)
- {
- opth.Add(classResult.ans[index]);
- PHCount++;
- continue;
- }
- }
- if (pls.Contains(id))
- {
- if (classResult.ans.Count > 0)
- {
- optl.Add(classResult.ans[index]);
- PLCount++;
- continue;
- }
- }
- }
- }
- }
- }
- er.phc = getMore(info, no, opth);
- er.plc = getMore(info, no, optl);
- er.afp = afp;
- er.akp = akp;
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测作答记录结算异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- }
- }
- public static async Task<List<RGroupList>> Activity(CoreAPIHttpService _coreAPIHttpService, ExamInfo info, List<string> classes, CosmosClient client, DingDing _dingDing, List<string> sub, List<ExamClassResult> results)
- {
- List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
- if (info.groupLists.Count > 0)
- {
- var group = info.groupLists;
- foreach (var gp in group)
- {
- foreach (KeyValuePair<string, List<string>> pp in gp)
- {
- ps.Add((pp.Key, pp.Value));
- }
- }
- }
- (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, classes, info.school, ps);
- var addStudentsCls = tchList.FindAll(x => x.type == 2);
- var addTmdidsCls = tchList.FindAll(x => x.type == 1);
- List<StuActivity> stuActivities = new List<StuActivity>();
- List<StuActivity> tmdActivities = new List<StuActivity>();
- if (addTmdidsCls.IsNotEmpty())
- {
- addTmdidsCls.ForEach(x =>
- {
- HashSet<string> classIds = new HashSet<string>();
- classLists.ForEach(z =>
- {
- z.members.ForEach(y =>
- {
- if (y.id.Equals(x.id) && y.type == 1)
- {
- classIds.Add(z.id);
- }
- });
- });
- bool iss = false;
- //标记学生作答状态
- int ts = 0;
- if (results.Count > 0)
- {
- foreach (ExamClassResult exam in results)
- {
- int index = exam.studentIds.IndexOf(x.id);
- if (index != -1)
- {
- if (exam.studentAnswers[index].Count > 0)
- {
- bool flag = exam.studentScores[index].Exists(x => x == -1);
- if (!flag)
- {
- ts = 1;
- iss = true;
- break;
- }
- else
- {
- ts = 0;
- }
- }
- else
- {
- ts = -1;
- }
- }
- }
- }
- else
- {
- ts = -1;
- }
- tmdActivities.Add(new StuActivity
- {
- pk = "Activity",
- id = info.id,
- code = $"Activity-{x.id}",
- type = "Exam",
- name = info.name,
- source = info.source,
- startTime = info.startTime,
- endTime = info.endTime,
- scode = info.code,
- scope = info.scope,
- school = info.school,
- creatorId = info.creatorId,
- subjects = sub,
- blob = null,
- owner = info.owner,
- createTime = info.createTime,
- taskStatus = ts,
- qamode = info.qamode,
- ext = new Dictionary<string, JsonElement>() { { "type", info.examType.ToJsonString().ToObject<JsonElement>() },
- { "subjects", info.subjects.ToJsonString().ToObject<JsonElement>() } },
- sStatus = iss ? 1 : 0,
- 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(info.school) && y.type == 2)
- {
- classIds.Add(z.id);
- }
- });
- });
- bool iss = false;
- //标记学生作答状态
- int ts = 0;
- if (results.Count > 0)
- {
- foreach (ExamClassResult exam in results)
- {
- int index = exam.studentIds.IndexOf(x.id);
- if (index != -1)
- {
- if (exam.studentAnswers[index].Count > 0)
- {
- bool flag = exam.studentScores[index].Exists(x => x == -1);
- if (!flag)
- {
- ts = 1;
- iss = true;
- break;
- }
- else
- {
- ts = 0;
- }
- }
- else
- {
- ts = -1;
- }
- }
- }
- }
- else
- {
- ts = -1;
- }
- stuActivities.Add(new StuActivity
- {
- pk = "Activity",
- id = info.id,
- code = $"Activity-{x.code.Replace("Base-", "")}-{x.id}",
- type = "Exam",
- name = info.name,
- source = info.source,
- startTime = info.startTime,
- endTime = info.endTime,
- scode = info.code,
- scope = info.scope,
- school = info.school,
- creatorId = info.creatorId,
- subjects = sub,
- blob = null,
- owner = info.owner,
- classIds = classIds.ToList(),
- createTime = info.createTime,
- qamode = info.qamode,
- ext = new Dictionary<string, JsonElement>() { { "type", info.examType.ToJsonString().ToObject<JsonElement>() },
- { "subjects", info.subjects.ToJsonString().ToObject<JsonElement>() } },
- taskStatus = ts,
- sStatus = iss ? 1 : 0,
- });
- });
- }
- await ActivityService.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities, null);
- return classLists;
- }
- public static async Task<List<double>> knowledgeCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, List<ExamClassResult> classResults,
- double rhwCount, double rhw, double rhlCount, double rhl, AzureCosmosFactory _azureCosmos)
- {
- List<double> akp = new();
- try
- {
- int phcount = 0;
- int plcount = 0;
- //存放并去重知识点
- HashSet<string> kname = new HashSet<string>();
- if (info.papers[no].knowledge.Count > 0)
- {
- info.papers[no].knowledge.ForEach(kno =>
- {
- kno.ForEach(k =>
- {
- kname.Add(k);
- });
- });
- List<string> knowledgeName = new List<string>();
- foreach (string cla in kname)
- {
- knowledgeName.Add(cla);
- }
- for (int k = 0; k < knowledgeName.Count; k++)
- {
- if (null == knowledgeName[k])
- {
- knowledgeName.Remove(knowledgeName[k]);
- }
- }
- foreach (ExamClassResult classResult in classResults)
- {
- if (classResult.subjectId.Equals(subject.id))
- {
- //List<int> phc = new List<int>();
- List<int> ph = new List<int>();
- List<int> pl = new List<int>();
- List<int> pc = new List<int>();
- List<double> persent = new List<double>();
- int lostStu = classResult.status.Where(c => c == 1).ToList().Count;
- for (int i = 0; i < knowledgeName.Count; i++)
- {
- //初始化单个知识点得分
- double score = 0;
- int n = 0;
- int phCount = 0;
- int plCount = 0;
- int pCount = 0;
- double classScore = 0;
- foreach (List<string> str in info.papers[no].knowledge)
- {
- if (str.Contains(knowledgeName[i]))
- {
- var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
- classScore += info.papers[no].point.Count > 0 ? (info.papers[no].point[n] * itemPersent) : 0;
- foreach (string id in classResult.studentIds)
- {
- int index = classResult.studentIds.IndexOf(id);
- if (classResult.studentScores.Count > 0)
- {
- if (classResult.studentScores[index].Count > 0)
- {
- double realScore = classResult.studentScores[index][n] == -1 ? 0 : classResult.studentScores[index][n] * itemPersent;
- score += realScore;
- //score += classResult.studentScores[index][n] == -1 ? 0 : classResult.studentScores[index][n] * itemPersent;
- if (classResult.studentScores[index].Sum() >= rhw && phcount < rhwCount)
- {
- if (classResult.studentScores[index][n] <= 0)
- {
- phCount++;
- }
- phcount++;
- continue;
- }
- if (classResult.studentScores[index].Sum() <= rhl && plcount < (info.stuCount - rhlCount))
- {
- if (classResult.studentScores[index][n] <= 0)
- {
- plCount++;
- }
- plcount++;
- continue;
- }
- if (classResult.studentScores[index][n] <= 0)
- {
- pCount++;
- }
- }
- }
- }
- }
- n++;
- }
- pc.Add(pCount);
- ph.Add(phCount);
- pl.Add(plCount);
- double per = classResult.studentIds.Count - lostStu > 0 ? Math.Round(score / (classResult.studentIds.Count - lostStu), 2) : 0;
- persent.Add(classScore > 0 ? Math.Round(per * 1.0 / classScore, 2) : 0);
- }
- classResult.phc = ph;
- classResult.plc = pl;
- classResult.pc = pc;
- classResult.krate = persent;
- }
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new Azure.Cosmos.PartitionKey($"{classResult.code}"));
- }
- foreach (string k in knowledgeName)
- {
- double score = 0;
- double allScore = 0;
- int count = 0;
- int m = 0;
- foreach (List<string> str in info.papers[no].knowledge)
- {
- if (str.Contains(k))
- {
- var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
- allScore += info.papers[no].point.Count > 0 ? info.papers[no].point[m] * itemPersent : 0;
- }
- m++;
- }
- foreach (ExamClassResult result in classResults)
- {
- if (result.subjectId.Equals(subject.id))
- {
- int n = 0;
- foreach (List<string> str in info.papers[no].knowledge)
- {
- if (str.Contains(k))
- {
- var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
- if (result.studentScores.Count > 0)
- {
- foreach (List<double> sc in result.studentScores)
- {
- double tsc = sc[n] == -1 ? 0 : sc[n];
- score += (tsc * itemPersent);
- }
- }
- }
- n++;
- }
- count += result.studentIds.Count;
- }
- }
- double per = count - info.lostStu.Count > 0 ? Math.Round(score / (count - info.lostStu.Count), 2) : 0;
- akp.Add(allScore > 0 ? Math.Round(per / allScore, 2) : 0);
- }
- }
- return akp;
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测知识点结算异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return null;
- }
- }
- public static async Task<List<double>> fieldCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, List<ExamClassResult> classResults,
- double rhwCount, double rhw, double rhlCount, double rhl, AzureCosmosFactory _azureCosmos)
- {
- List<double> afp = new();
- try
- {
- int phcount = 0;
- int plcount = 0;
- //存放并去重知识点
- List<int> knowledgeName = new List<int>() { 1, 2, 3, 4, 5, 6 };
- /* knowledgeName.Add(1);
- knowledgeName.Add(2);
- knowledgeName.Add(3);
- knowledgeName.Add(4);
- knowledgeName.Add(5);
- knowledgeName.Add(6);*/
- foreach (ExamClassResult classResult in classResults)
- {
- if (classResult.subjectId.Equals(subject.id))
- {
- //List<int> phc = new List<int>();
- List<int> ph = new List<int>();
- List<int> pl = new List<int>();
- List<int> pc = new List<int>();
- List<double> persent = new List<double>();
- int lostStu = classResult.status.Where(c => c == 1).ToList().Count;
- for (int i = 0; i < knowledgeName.Count; i++)
- {
- //初始化单个知识点得分
- double score = 0;
- int n = 0;
- int phCount = 0;
- int plCount = 0;
- int pCount = 0;
- double classScore = 0;
- if (info.papers[no].field.Count > 0)
- {
- foreach (int str in info.papers[no].field)
- {
- if (str == knowledgeName[i])
- {
- var itemPersent = 1;
- classScore += info.papers[no].point.Count > 0 ? info.papers[no].point[n] * itemPersent : 0;
- foreach (string id in classResult.studentIds)
- {
- int index = classResult.studentIds.IndexOf(id);
- if (classResult.studentScores.Count > 0)
- {
- if (classResult.studentScores[index].Count > 0)
- {
- score += classResult.studentScores[index][n] == -1 ? 0 : classResult.studentScores[index][n];
- if (classResult.studentScores[index].Sum() >= rhw && phcount < rhwCount)
- {
- if (classResult.studentScores[index][n] <= 0)
- {
- phCount++;
- }
- phcount++;
- continue;
- }
- if (classResult.studentScores[index].Sum() <= rhl && plcount < (info.stuCount - rhlCount))
- {
- if (classResult.studentScores[index][n] <= 0)
- {
- plCount++;
- }
- plcount++;
- continue;
- }
- if (classResult.studentScores[index][n] <= 0)
- {
- pCount++;
- }
- }
- }
- }
- }
- n++;
- }
- pc.Add(pCount);
- ph.Add(phCount);
- pl.Add(plCount);
- double per = classResult.studentIds.Count - lostStu > 0 ? Math.Round(score / (classResult.studentIds.Count - lostStu), 2) : 0;
- persent.Add(classScore > 0 ? Math.Round(per / classScore, 2) : 0);
- }
- }
- classResult.fphc = ph;
- classResult.fplc = pl;
- classResult.fpc = pc;
- classResult.frate = persent;
- }
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new Azure.Cosmos.PartitionKey($"{classResult.code}"));
- }
- for (int i = 0; i < knowledgeName.Count; i++)
- {
- double score = 0;
- double allScore = 0;
- int count = 0;
- int m = 0;
- foreach (int str in info.papers[no].field)
- {
- if (str == knowledgeName[i])
- {
- var itemPersent = 1;
- allScore += info.papers[no].point.Count > 0 ? info.papers[no].point[m] * itemPersent : 0;
- }
- m++;
- }
- foreach (ExamClassResult result in classResults)
- {
- if (result.subjectId.Equals(subject.id))
- {
- int n = 0;
- foreach (int str in info.papers[no].field)
- {
- var itemPersent = 1;
- if (str == knowledgeName[i])
- {
- if (result.studentScores.Count > 0)
- {
- foreach (List<double> sc in result.studentScores)
- {
- double tsc = sc[n] == -1 ? 0 : sc[n];
- score += tsc * itemPersent;
- }
- }
- }
- n++;
- }
- count += result.studentIds.Count;
- }
- }
- double per = count - info.lostStu.Count > 0 ? Math.Round(score / (count - info.lostStu.Count), 2) : 0;
- afp.Add(allScore > 0 ? Math.Round(per / allScore, 2) : 0);
- }
- return afp;
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测认知层次结算异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return null;
- }
- }
- //处理选题计数
- public static List<Dictionary<string, int>> getMore(ExamInfo info, int no, List<List<List<string>>> list)
- {
- List<Dictionary<string, int>> recorde = new List<Dictionary<string, int>>();
- try
- {
- for (int i = 0; i < info.papers[no].answers.Count; i++)
- {
- if (info.papers[no].answers[i].Count <= 0)
- {
- recorde.Add(new Dictionary<string, int>());
- continue;
- }
- Dictionary<string, int> optCount = new Dictionary<string, int>();
- foreach (List<List<string>> stu in list)
- {
- if (stu.Count == info.papers[no].answers.Count)
- {
- var item = stu[i];
- foreach (string opt in item)
- {
- if (optCount.ContainsKey(opt))
- {
- optCount[opt] = optCount[opt] + 1;
- }
- else
- {
- optCount[opt] = 1;
- }
- }
- }
- }
- recorde.Add(optCount);
- }
- return recorde;
- }
- catch (Exception)
- {
- return recorde;
- }
- }
- public static async Task createClassResultAsync(ExamInfo info, List<ExamClassResult> examClassResults, ExamSubject subject, int no, AzureCosmosFactory _azureCosmos, DingDing _dingDing, AzureStorageFactory _azureStorage, IHttpClientFactory _httpClient, IConfiguration _configuration)
- {
- //保证试卷信息与科目信息同步
- ExamResult result = new ExamResult();
- //人数总和
- int Count = 0;
- int m = 0;
- double score = 0;
- //标准差
- //double powSum = 0;
- double allScore = info.papers[no].point.Sum();
- List<ClassRange> classRanges = new List<ClassRange>();
- List<string> lostStu = new List<string>();
- List<double> csRate = new List<double>();
- List<List<List<string>>> opt = new List<List<List<string>>>();
- //List<Task<ItemResponse<ExamClassResult>>> tasks = new();
- foreach (ExamClassResult classResult in examClassResults)
- {
- double classSrate = 0;
- if (classResult.subjectId.Equals(subject.id))
- {
- foreach (List<List<string>> op in classResult.ans)
- {
- opt.Add(op);
- }
- //记录缺考学生索引位置
- int index_stu = 0;
- foreach (var ans in classResult.studentAnswers)
- {
- if (ans.Count == 0)
- {
- if (!lostStu.Contains(classResult.studentIds[index_stu]))
- {
- lostStu.Add(classResult.studentIds[index_stu]);
- }
- }
- else
- {
- if (classResult.status[index_stu] == 1)
- {
- if (!lostStu.Contains(classResult.studentIds[index_stu]))
- {
- lostStu.Add(classResult.studentIds[index_stu]);
- }
- }
- }
- index_stu++;
- }
- int index = 0;
- foreach (List<double> scores in classResult.studentScores)
- {
- List<double> newScores = new List<double>();
- //int count = 0;
- foreach (double sc in scores)
- {
- newScores.Add(sc > -1 ? sc : 0);
- }
- classSrate += newScores.Sum();
- score += newScores.Sum();
- result.studentScores.Add(newScores);
- index++;
- }
- //处理班级信息
- ClassRange range = new ClassRange();
- range.id = classResult.info.id;
- range.name = classResult.info.name;
- range.gradeId = classResult.gradeId;
- List<int> ran = new List<int>();
- int stuCount = classResult.studentIds.Count;
- //todo 与实际的缺考人数比较
- int lostStus = classResult.status.Where(c => c == 1).ToList().Count;
- Count += stuCount;
- if (m == 0)
- {
- ran.Add(0);
- ran.Add(stuCount - 1);
- }
- else
- {
- ran.Add(Count - stuCount);
- ran.Add(Count - 1);
- }
- m++;
- range.range = ran;
- classRanges.Add(range);
- //处理学生ID
- foreach (string id in classResult.studentIds)
- {
- result.studentIds.Add(id);
- }
- if (allScore > 0)
- {
- csRate.Add(classResult.studentIds.Count - lostStus > 0 ? Math.Round(classSrate * 1.0 / (classResult.studentIds.Count - lostStus), 2) : 0 / allScore);
- }
- else
- {
- csRate.Add(0);
- }
- //powSum += Math.Pow(classSrate - result.average, 2);
- //处理选项计数内容
- }
- //tasks.Add(_azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new PartitionKey($"{classResult.code}")));
- }
- //await tasks.TaskPage(10);
- /*foreach (string id in result.lostStus) {
- if (!examClassResults[0].studentIds.Contains(id)) {
- int index = result.lostStus.IndexOf(id);
- result.lostStus.RemoveAt(index);
- }
- }*/
- //处理人员变更时被移除的人员
- result.lostStus = lostStu;
- if (result.lostStus.Count > 0)
- {
- for (int i = 0; i < result.lostStus.Count; i++)
- {
- if (!examClassResults[0].studentIds.Contains(result.lostStus[i]))
- {
- result.lostStus.RemoveAt(i);
- }
- }
- }
- result.record = getMore(info, no, opt);
- result.average = result.studentIds.Count - result.lostStus.Count > 0 ? Math.Round(score * 1.0 / (result.studentIds.Count - result.lostStus.Count), 2) : 0;
- double powSum = 0;
- //int sco = 0;
- result.studentIds.ForEach(x =>
- {
- double sc = result.studentScores[result.studentIds.IndexOf(x)].Sum();
- if (!result.lostStus.Contains(x))
- {
- powSum += Math.Pow(sc - result.average, 2);
- }
- });
- result.standard = Math.Round((result.studentIds.Count - result.lostStus.Count) > 0 ? Math.Pow(powSum / (result.studentIds.Count - result.lostStus.Count), 0.5) : 0, 2);
- result.csRate = csRate;
- result.sRate = allScore > 0 ? Math.Round(result.average / allScore * 100, 2) : 0;
- result.classes = classRanges;
- result.code = "ExamResult-" + info.id;
- result.school = info.school;
- result.id = subject.id;
- result.examId = info.id;
- result.subjectId = subject.id;
- result.year = info.year;
- result.paper = info.papers[no];
- //result.point = info.papers[j].point;
- result.scope = info.scope;
- result.name = info.name;
- result.time = info.startTime;
- await examRecordCount(info, subject, _dingDing, no, result, examClassResults, _azureCosmos);
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").UpsertItemAsync(result, new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}"));
- List<ErrorItems> errorItems = new();
- string sqlqueryText = $"select value(c) from c where c.activityId = '{info.id}'and c.subjectId = '{info.subjects[no].id}' and c.stuId in ({string.Join(",", result.studentIds.Select(x => $"'{x}'"))})";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Student").GetItemQueryIterator<ErrorItems>(queryText: sqlqueryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("ErrorItems") }))
- {
- errorItems.Add(item);
- }
- if (errorItems.Count == 0)
- {
- // 新增逻辑 收集错题内容
- BlobDownloadResult index_json;
- if (info.scope.Equals("school"))
- {
- index_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{info.papers[no].blob}/index.json").DownloadContentAsync();
- }
- else
- {
- index_json = await _azureStorage.GetBlobContainerClient($"{info.creatorId}").GetBlobClient($"{info.papers[no].blob}/index.json").DownloadContentAsync();
- }
- //BlobDownloadResult index_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{info.papers[no].blob}/index.json").DownloadContentAsync();
- JObject jo = JObject.Parse(index_json.Content.ToString());
- JArray array = jo.Value<JArray>("slides");
- List<string> urls = new();
- foreach (var ne in array)
- {
- if (!ne["type"].ToString().Equals("compose"))
- {
- urls.Add(ne["url"].ToString());
- }
- }
- string code = string.Empty;
- string pk = string.Empty;
- string table = "School";
- if (info.scope.Equals("school"))
- {
- code = $"ErrorItems-{info.school}";
- pk = $"Item-{info.school}";
- }
- else
- {
- code = "ErrorItems";
- pk = $"Item-{info.creatorId}";
- table = "Teacher";
- }
- // 获取整体的题目ID集合
- List<string> ids = new();
- List<(string id, string pid, int level, string type, List<string> knows)> itemInfos = new();
- foreach (string url in urls)
- {
- string id = url.Replace(".json", "");
- BlobDownloadResult index_item_json;
- if (info.scope.Equals("school"))
- {
- index_item_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{info.papers[no].blob}/{url}").DownloadContentAsync();
- }
- else
- {
- index_item_json = await _azureStorage.GetBlobContainerClient($"{info.creatorId}").GetBlobClient($"{info.papers[no].blob}/{url}").DownloadContentAsync();
- }
- JObject keys = JObject.Parse(index_item_json.Content.ToString());
- string type = keys["exercise"].Value<string>("type");
- int level = keys["exercise"].Value<int>("level");
- var knowledge = keys["exercise"].Value<JArray>("knowledge")?.ToObject<List<string>>();
- string pid = keys.Value<string>("pid");
- itemInfos.Add((id, pid, level, type, knowledge));
- }
- /*await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, table).GetItemQueryStreamIterator(
- queryText: $"select c.id,c.pid,c.level,c.type from c where c.id in ({string.Join(",", ids.Select(o => $"'{o}'"))})", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{pk}") }))
- {
- 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;
- string pid = "";
- if (account.TryGetProperty("pid",out JsonElement element)) {
- pid = element.GetString();
- }
- itemInfos.Add((account.GetProperty("id").GetString(), pid, account.GetProperty("level").GetInt32(), account.GetProperty("type").GetString()));
- }
- }
- }*/
- double[] point = StringHelper.ListTodouble(result.paper.point);
- double[,] res = StringHelper.ListToDouble(result.studentScores);
- var cdm = new ClouDASMatrix(res, point);
- //需要努力的题目
- var ss = cdm.StriveTopic;
- int n = 0;
- List<Task<ItemResponse<ErrorItems>>> task_error = new();
- List<ErrorItems> errors = new();
- foreach (var sIds in result.studentIds)
- {
- ErrorItems error = new()
- {
- ttl = -1,
- code = code,
- id = Guid.NewGuid().ToString(),
- stuId = sIds,
- school = info.school,
- activityId = info.id,
- subjectId = result.subjectId,
- time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
- };
- //顺序学生错题的索引
- int[] item_index = ss[n];
- foreach (var item in item_index)
- {
- Items items = new()
- {
- id = urls[item - 1].Replace(".json", ""),
- blob = info.papers[no].blob
- };
- items.level = itemInfos.Where(c => c.id.Equals(items.id)).FirstOrDefault().level;
- items.type = itemInfos.Where(c => c.id.Equals(items.id)).FirstOrDefault().type;
- items.pId = itemInfos.Where(c => c.id.Equals(items.id)).FirstOrDefault().pid;
- items.knowledge = itemInfos.Where(c => c.id.Equals(items.id)).FirstOrDefault().knows;
- error.its.Add(items);
- }
- errors.Add(error);
- n++;
- task_error.Add(_azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(error, new PartitionKey($"{error.code}")));
- }
- //string connect = _configuration.GetValue<string>("HaBookAuth:Crtmabank") + "https://malearnfunction.chinacloudsites.cn/api/crtmabank";
- string location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
- string urlAction = string.Empty;
- if (location.Contains("China") || location.Contains("China-Dep"))
- {
- urlAction = "https://malearnfunction.chinacloudsites.cn";
- }
- else if (location.Contains("Global"))
- {
- urlAction = "https://malearnfunction.azurewebsites.net";
- }
- else if (location.Contains("Global-Test"))
- {
- urlAction = "https://malearn-test.azurewebsites.net";
- }
- string connect = $"{urlAction}/api/crtmabank";
- var htc = _httpClient.CreateClient();
- if (htc.DefaultRequestHeaders.Contains("x-functions-key"))
- {
- htc.DefaultRequestHeaders.Remove("x-functions-key");
- }
- htc.DefaultRequestHeaders.Add("x-functions-key", "QUzQqbqbnLsTDTeaJy4Br6wUuqPoAlKpzRK2S6PGImRHAzFuySGAeA==");
- string paramJson = JsonConvert.SerializeObject(errors);
- var content = new StringContent(paramJson, Encoding.UTF8, "application/json");
- await htc.PostAsync(connect, content);
- await task_error.TaskPage(10);
- }
- }
- public class Settlement
- {
- public double rate { get; set; }
- public double score { get; set; }
- public List<string> stus { get; set; } = new List<string>();
- public int total { get; set; }
- public double qrate { get; set; }
- }
- }
- }
|