12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229 |
- using Azure.Cosmos;
- using Azure.Messaging.ServiceBus;
- using Microsoft.Azure.Documents;
- 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;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK.Models.Service;
- using HTEXLib.COMM.Helpers;
- using System.Net.Http;
- 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)
- {
- 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 _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
- }
- catch (Exception)
- {
- continue;
- }
- }
- 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>();
- 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)
- {
- await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), records[0].sequenceNumber);
- 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<string>();
- List<List<string>> anses = new List<List<string>>();
- List<List<Details>> marks = new List<List<Details>>();
- List<double> ansPoint = new List<double>();
- List<(string sId, string scode)> ids = new List<(string sId, string scode)>();
- 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>();
- School sc = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(info.school, new Azure.Cosmos.PartitionKey("Base"));
- foreach (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(0);
- }
- //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);
- }
- 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, examClassResults);
- long nowTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- //判断评分状态是否发生变化,便于实时的更新评测基本信息
- if ((info.updateTime != nowTime && 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}", 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));
- await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), records[0].sequenceNumber);
- 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;
- Settlement settlement = await getMore(client, info, examClassResults);
- var isScore = examClassResults.SelectMany(e => e.studentScores).ToList().Exists(c => c.Contains(-1));
- int newStatus = 0;
- if (!isScore)
- {
- newStatus = 1;
- }
- //处理活动中间件
- List<StuActivity> stus = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<StuActivity>(
- queryText: $"select c.id from c where c.id = '{info.id}'"))
- {
- stus.Add(item);
- }
- if (info.source.Equals("1") && stus.Count == 0)
- {
- await Activity(_coreAPIHttpService, info, classes, client, _dingDing, sub, examClassResults);
- }
- foreach (ExamSubject subject in info.subjects)
- {
- await createClassResultAsync(info, examClassResults, subject, fno, _azureCosmos, _dingDing, _azureStorage);
- fno++;
- }
- //info.lostStu = losStu;
- /*//补充历史数据的容器名称
- if (string.IsNullOrEmpty(info.cn)) {
- if (info.scope.Equals("school"))
- {
- info.cn = info.school;
- }
- else {
- info.cn = info.creatorId;
- }
- }*/
- //判断均分是否发生变化,便于实时的更新评测基本信息
- if (info.sRate != settlement.rate || info.average != settlement.score || info.sStatus != newStatus)
- {
- info.sRate = settlement.rate;
- info.average = settlement.score;
- info.sStatus = newStatus;
- info.lostStu = settlement.stus;
- info.stuCount = settlement.total;
- 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}", GroupNames.成都开发測試群組);
- }
- break;
- }
- }
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDB异常{e.StackTrace}{e.Message}\n{e.Status}", GroupNames.成都开发測試群組);
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-评测结算异常{e.Message}\n{e.StackTrace}", GroupNames.成都开发測試群組);
- }
- }
- public static async Task<Settlement> getMore(CosmosClient client, ExamInfo info, List<ExamClassResult> examClassResults)
- {
- //计算单次考试简易统计信息
- 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)
- {
- List<Task<ItemResponse<ExamClassResult>>> tasks = new List<Task<ItemResponse<ExamClassResult>>>();
- //结算单科单班的标准差和平均分
- foreach (ExamClassResult classResult in examClassResults)
- {
- //标记单科单班总得分
- double subScore = 0;
- //标准差
- double sPowSum = 0;
- List<double> newSumScore = new List<double>();
- var scount = classResult.studentIds.Count;
- int index = 0;
- foreach (var ans in classResult.studentAnswers) {
- //该学生缺考
- if (ans.Count == 0) {
- for (int i =0; i < classResult.studentScores[index].Count; i++) {
- classResult.studentScores[index][i] = 0;
- }
- }
- index++;
- }
- 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 = newSc.Sum();
- newSumScore.Add(nc);
- subScore += nc;
- }
- double rateScore = scount > 0 ? Math.Round(subScore * 1.0 / scount, 2) : 0;
- foreach (double scs in newSumScore)
- {
- 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);
- //记录某次考试所有学生得分总分
- double score = 0;
- double allScore = 0;
- int stuCount = 0;
- //标准差
- double powSum = 0;
- List<string> losStu = new List<string>();
- //当前完成考试得人数
- int total = examResults[0].studentIds.Count;
- //先与第一个值取并集
- losStu = losStu.Union(examResults[0].lostStus).ToList();
- foreach (ExamResult examResult in examResults)
- {
- if (info.id == examResult.examId)
- {
- foreach (List<double> sc in examResult.studentScores)
- {
- score += sc.Sum();
- }
- stuCount = examResult.studentIds.Count;
- }
- //powSum += Math.Pow(score - examResult.studentIds.Count > 0 ? Math.Round(score * 1.0 / examResult.studentIds.Count, 2) : 0, 2);
- //取交集
- losStu = losStu.Intersect(examResult.lostStus).ToList();
- }
- 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 examResults[0].studentIds)
- {
- double sc = 0;
- foreach (ExamResult result in examResults)
- {
- sc += result.studentScores[result.studentIds.IndexOf(id)].Sum();
- }
- powSum += Math.Pow(sc - NewsRateScore, 2);
- }
- info.standard = Math.Round(total > 0 ? Math.Pow(powSum / total, 0.5) : 0, 2);
- double NewsRate = allScore > 0 ? Math.Round(NewsRateScore / allScore * 100, 2) : 0;
- settlement.rate = NewsRate;
- settlement.score = NewsRateScore;
- settlement.stus = losStu;
- settlement.total = total;
- }
- return settlement;
- }
- //处理全部学生选题计数
- public static async Task examRecordCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, ExamResult result, List<ExamClassResult> classResults, AzureCosmosFactory _azureCosmos)
- {
- try
- {
- List<double> scores = new List<double>();
- foreach (List<double> sc in result.studentScores)
- {
- scores.Add(sc.Sum());
- }
- //确定高分组 最低分数
- scores.Sort((s1, s2) => { return s2.CompareTo(s1); });
- double rhwCount = Math.Floor(scores.Count * 0.27);
- double rhw = rhwCount > 0 ? scores[int.Parse(rhwCount.ToString("0"))] : 0;
- //确定低分组 最高分数
- //scores.Sort((s1, s2) => { return s1.CompareTo(s2); });
- double rhlCount = Math.Ceiling(scores.Count * 0.73);
- double rhl = rhlCount > 0 ? scores[int.Parse(rhlCount.ToString("0")) - 1] : 0;
- //存放高分组学生ID
- List<string> phId = new List<string>();
- List<string> plId = new List<string>();
- List<List<List<string>>> opth = new List<List<List<string>>>();
- List<List<List<string>>> optl = new List<List<List<string>>>();
- await knowledgeCount(info, subject, _dingDing, no, classResults, rhwCount, rhw, rhlCount, rhl, _azureCosmos);
- 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 (classResult.studentScores[index].Sum() >= rhw && PHCount < rhwCount)
- {
- if (classResult.ans.Count > 0)
- {
- opth.Add(classResult.ans[index]);
- PHCount++;
- continue;
- }
- }
- if (classResult.studentScores[index].Sum() <= rhl && PLCount < (scores.Count - rhlCount))
- {
- if (classResult.ans.Count > 0)
- {
- optl.Add(classResult.ans[index]);
- PLCount++;
- continue;
- }
- }
- }
- }
- }
- }
- result.phc = getMore(info, no, opth);
- result.plc = getMore(info, no, optl);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测作答记录结算异常{ex.Message}\n{ex.StackTrace}", 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.GetStutmdidListids(_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,
- ext = new Dictionary<string, JsonElement>() { { "type", info.type.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,
- ext = new Dictionary<string, JsonElement>() { { "type", info.type.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 knowledgeCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, List<ExamClassResult> classResults,
- double rhwCount, double rhw, double rhlCount, double rhl, AzureCosmosFactory _azureCosmos)
- {
- 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>();
- for (int i = 0; i < knowledgeName.Count; i++)
- {
- //初始化单个知识点得分
- double score = 0;
- double allScore = 0;
- int n = 0;
- int phCount = 0;
- int plCount = 0;
- int pCount = 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;
- allScore += 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 > 0 ? Math.Round(score / classResult.studentIds.Count, 2) : 0;
- persent.Add(allScore > 0 ? per / allScore : 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}"));
- }
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测知识点结算异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- }
- }
- public static async Task fieldCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, List<ExamClassResult> classResults,
- double rhwCount, double rhw, double rhlCount, double rhl, AzureCosmosFactory _azureCosmos)
- {
- 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>();
- for (int i = 0; i < knowledgeName.Count; i++)
- {
- //初始化单个知识点得分
- double score = 0;
- double allScore = 0;
- int n = 0;
- int phCount = 0;
- int plCount = 0;
- int pCount = 0;
- if (info.papers[no].field.Count > 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[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 > 0 ? Math.Round(score / classResult.studentIds.Count, 2) : 0;
- persent.Add(allScore > 0 ? per / allScore : 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}"));
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测认知层次结算异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- }
- }
- //处理选题计数
- 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)
- {
- //保证试卷信息与科目信息同步
- 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>>>();
- 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]);
- }
- }
- 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);
- /*if (sc == -1)
- {
- count++;
- }*/
- }
- /*if (count == scores.Count)
- {
- if (!lostStu.Contains(classResult.studentIds[index]))
- {
- lostStu.Add(classResult.studentIds[index]);
- }
- //mcount++;
- }*/
- 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;
- 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 > 0 ? Math.Round(classSrate * 1.0 / classResult.studentIds.Count, 2) : 0 / allScore);
- }
- else
- {
- csRate.Add(0);
- }
- //powSum += Math.Pow(classSrate - result.average, 2);
- //处理选项计数内容
- }
- }
- /*foreach (string id in result.lostStus) {
- if (!examClassResults[0].studentIds.Contains(id)) {
- int index = result.lostStus.IndexOf(id);
- result.lostStus.RemoveAt(index);
- }
- }*/
- //处理人员变更时被移除的人员
- 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);
- }
- }
- }
- await examRecordCount(info, subject, _dingDing, no, result, examClassResults, _azureCosmos);
- result.record = getMore(info, no, opt);
- result.average = result.studentIds.Count > 0 ? Math.Round(score * 1.0 / result.studentIds.Count, 2) : 0;
- double stand = 0;
- int sco = 0;
- foreach (ExamClassResult classResult in examClassResults)
- {
- //double classSrate = 0;
- if (classResult.subjectId.Equals(subject.id))
- {
- stand += classResult.standard;
- sco++;
- }
- }
- result.standard = sco > 0 ? Math.Round(stand / sco, 2) : 0;
- result.csRate = csRate;
- result.lostStus = lostStu;
- 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 _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").UpsertItemAsync(result, new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}"));
- }
- 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; }
- }
- }
- }
|