TriggerExam.cs 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571
  1. using Azure.Cosmos;
  2. using Azure.Messaging.ServiceBus;
  3. using TEAMModelOS.SDK.DI;
  4. using TEAMModelOS.SDK.Extension;
  5. using TEAMModelOS.SDK;
  6. using TEAMModelOS.SDK.Models;
  7. using TEAMModelOS.SDK.Models.Service;
  8. using HTEXLib.COMM.Helpers;
  9. using ClouDASLibx;
  10. using System.Text.Json;
  11. using System.Collections.Generic;
  12. using System.Threading.Tasks;
  13. using System;
  14. using System.Linq;
  15. using TEAMModelOS.SDK.Models.Service.BI;
  16. using Azure.Storage.Blobs.Models;
  17. using System.IO;
  18. using System.Text;
  19. using System.Text.Json.Nodes;
  20. using TEAMModelOS.SDK.Helper.Common.JsonHelper.JsonPath;
  21. using Newtonsoft.Json.Linq;
  22. using TEAMModelOS.SDK.Models.Cosmos.Student;
  23. using HTEXLib.Helpers.ShapeHelpers;
  24. using TEAMModelOS.Models.Dto;
  25. using TEAMModelOS.SDK.Models.Cosmos.Common;
  26. using DocumentFormat.OpenXml.Office2010.Excel;
  27. using DocumentFormat.OpenXml.Drawing.Charts;
  28. using DocumentFormat.OpenXml.Vml;
  29. namespace TEAMModelOS.FunctionV4
  30. {
  31. public class TriggerExam
  32. {
  33. public static async Task Trigger(CoreAPIHttpService _coreAPIHttpService, AzureCosmosFactory _azureCosmos, AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
  34. CosmosClient client, JsonElement input, TriggerData data)
  35. {
  36. List<ExamClassResult> examClassResults = new();
  37. List<ExamSubject> examSubjects = new();
  38. try
  39. {
  40. if ((data.status != null && data.status.Value == 404))
  41. {
  42. await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(data.id, new PartitionKey(data.code));
  43. ActivityList activity = input.ToObject<ActivityList>();
  44. await ActivityService.DeleteActivity(_coreAPIHttpService, client, _dingDing, activity);
  45. var table_cancel = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  46. List<ChangeRecord> records = await table_cancel.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", data.id } });
  47. foreach (var record in records)
  48. {
  49. try
  50. {
  51. await table_cancel.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  52. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  53. }
  54. catch (Exception)
  55. {
  56. continue;
  57. }
  58. }
  59. await BIStats.SetTypeAddStats(client, _dingDing, data.school, "Exam", -1, careDate: data.startTime);//BI统计增/减量
  60. return;
  61. }
  62. ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(data.id, new Azure.Cosmos.PartitionKey($"{data.code}"));
  63. if (info != null)
  64. {
  65. if (info.scope.Equals("teacher", StringComparison.OrdinalIgnoreCase) || info.scope.Equals("private", StringComparison.OrdinalIgnoreCase))
  66. {
  67. 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}") }))
  68. {
  69. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  70. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  71. {
  72. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  73. {
  74. examClassResults.Add(obj.ToObject<ExamClassResult>());
  75. }
  76. }
  77. }
  78. }
  79. else
  80. {
  81. 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}") }))
  82. {
  83. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  84. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  85. {
  86. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  87. {
  88. examClassResults.Add(obj.ToObject<ExamClassResult>());
  89. }
  90. }
  91. }
  92. }
  93. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  94. string PartitionKey = string.Format("{0}{1}{2}", info.code, "-", info.progress);
  95. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", data.id }, { "PartitionKey", PartitionKey } });
  96. //处理科目信息
  97. List<string> sub = new List<string>();
  98. foreach (ExamSubject subject in info.subjects)
  99. {
  100. sub.Add(subject.id);
  101. }
  102. //整合名单
  103. List<string> classes = ExamService.getClasses(info.classes, info.stuLists);
  104. //ChangeRecord record = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ChangeRecord>(input.Id, new Azure.Cosmos.PartitionKey($"{info.progress}"));
  105. switch (info.progress)
  106. {
  107. case "pending":
  108. var message = new ServiceBusMessage(new { id = data.id, progress = "going", code = data.code }.ToJsonString());
  109. message.ApplicationProperties.Add("name", "Exam");
  110. if (records.Count > 0)
  111. {
  112. try
  113. {
  114. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), records[0].sequenceNumber);
  115. }
  116. catch (Exception)
  117. {
  118. }
  119. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(data.startTime));
  120. records[0].sequenceNumber = start;
  121. await table.SaveOrUpdate<ChangeRecord>(records[0]);
  122. //await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(record, record.id, new Azure.Cosmos.PartitionKey($"{record.code}"));
  123. }
  124. else
  125. {
  126. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(data.startTime));
  127. //string pk = String.Format("{0}{1}{2}", info.code, "-", "pending");
  128. ChangeRecord changeRecord = new ChangeRecord
  129. {
  130. RowKey = data.id,
  131. PartitionKey = PartitionKey,
  132. sequenceNumber = start,
  133. msgId = message.MessageId
  134. };
  135. await table.Save<ChangeRecord>(changeRecord);
  136. //await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  137. }
  138. break;
  139. case "going":
  140. try
  141. {
  142. //向学生或醍摩豆账号发起通知
  143. #region
  144. //Notice notice = new Notice()
  145. //{
  146. // msgId = info.id,
  147. // creation = info.startTime,
  148. // expire = info.endTime,
  149. // creatorId = info.creatorId,
  150. // stuids = studentss,
  151. // tmdids = tmdids,
  152. // type = "notice",//评测参加通知
  153. // priority = "normal",
  154. // school = info.school,
  155. // scope = info.scope,
  156. // //data = new { }.ToJsonString()
  157. // body = new Body { sid = info.id, scode = info.code, spk = info.pk, biztype = "exam-join" }
  158. //};
  159. //var messageBlob = new ServiceBusMessage(notice.ToJsonString());
  160. //messageBlob.ApplicationProperties.Add("name", "Notice");
  161. //await _serviceBus.GetServiceBusClient().SendMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageBlob);
  162. #endregion
  163. //List<string> classes = new List<string>();
  164. //处理活动中间件
  165. List<RGroupList> members = await Activity(_coreAPIHttpService, info, classes, client, _dingDing, sub, examClassResults);
  166. if (examClassResults.Count == 0)
  167. {
  168. foreach (string cla in classes)
  169. {
  170. int m = 0;
  171. RGroupList rGroup = new();
  172. rGroup = members.Where(m => m.id.Equals(cla)).FirstOrDefault();
  173. foreach (ExamSubject subject in info.subjects)
  174. {
  175. string classCode = string.Empty;
  176. string cname = string.Empty;
  177. if (string.IsNullOrEmpty(info.school) || !info.scope.Equals("school", StringComparison.OrdinalIgnoreCase))
  178. {
  179. classCode = "ExamClassResult-" + info.creatorId;
  180. }
  181. else
  182. {
  183. classCode = "ExamClassResult-" + info.school;
  184. }
  185. cname = members.Where(m => m.id.Equals(cla)).FirstOrDefault()?.name;
  186. // 预处理活动中间件信息
  187. ExamClassResult result = new()
  188. {
  189. code = classCode,
  190. examId = info.id,
  191. id = Guid.NewGuid().ToString(),
  192. subjectId = subject.id,
  193. year = info.year,
  194. scope = info.scope
  195. };
  196. result.info.id = cla;
  197. result.info.name = cname;
  198. List<string> ans = new();
  199. List<List<string>> anses = new();
  200. List<List<Details>> marks = new();
  201. List<double> ansPoint = new();
  202. List<(string sId, string scode)> ids = new();
  203. foreach (double p in info.papers[m].point)
  204. {
  205. //Details details = new Details();
  206. //ans.Add(new List<string>());
  207. anses.Add(new List<string>());
  208. marks.Add(new List<Details>());
  209. ansPoint.Add(-1);
  210. }
  211. var sresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"Class-{info.school}"));
  212. if (sresponse.Status == 200)
  213. {
  214. using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
  215. Class classroom = json.ToObject<Class>();
  216. School sc = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(info.school, new Azure.Cosmos.PartitionKey("Base"));
  217. foreach (SDK.Models.Period period in sc.period)
  218. {
  219. if (period.id.Equals(classroom.periodId))
  220. {
  221. foreach (Semester semester in period.semesters)
  222. {
  223. if (semester.start == 1)
  224. {
  225. int year = DateTimeOffset.UtcNow.Year;
  226. int month = DateTimeOffset.UtcNow.Month;
  227. int day = DateTimeOffset.UtcNow.Day;
  228. int time = 0;
  229. if (month == semester.month)
  230. {
  231. time = day >= semester.day ? 0 : 1;
  232. }
  233. else
  234. {
  235. time = month > semester.month ? 0 : 1;
  236. }
  237. int eyear = year - time;
  238. result.gradeId = (eyear - classroom.year).ToString();
  239. }
  240. }
  241. }
  242. }
  243. //result.info.id = classroom.id;
  244. //result.info.name = classroom.name;
  245. //result.gradeId = classroom.year.ToString();
  246. //处理班级人数
  247. /* 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}") }))
  248. {
  249. using var json_stu = await JsonDocument.ParseAsync(item.ContentStream);
  250. if (json_stu.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  251. {
  252. var accounts = json_stu.RootElement.GetProperty("Documents").EnumerateArray();
  253. while (accounts.MoveNext())
  254. {
  255. JsonElement account = accounts.Current;
  256. ids.Add(account.GetProperty("id").GetString());
  257. }
  258. }
  259. }*/
  260. }
  261. /*if (info.scope.Equals("private", StringComparison.OrdinalIgnoreCase))
  262. {
  263. var stuResponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"GroupList"));
  264. if (stuResponse.Status == 200)
  265. {
  266. using var json = await JsonDocument.ParseAsync(stuResponse.ContentStream);
  267. GroupList stuList = json.ToObject<GroupList>();
  268. //result.info.id = stuList.id;
  269. result.info.name = stuList.name;
  270. //处理发布对象为自选名单(个人)
  271. foreach (Member stus in stuList.members)
  272. {
  273. if (!ids.Contains(stus.id))
  274. {
  275. ids.Add(stus.id);
  276. }
  277. }
  278. }
  279. }
  280. else
  281. {
  282. var stuResponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"GroupList-{info.school}"));
  283. if (stuResponse.Status == 200)
  284. {
  285. using var json = await JsonDocument.ParseAsync(stuResponse.ContentStream);
  286. GroupList stuList = json.ToObject<GroupList>();
  287. //result.info.id = stuList.id;
  288. result.info.name = stuList.name;
  289. //处理发布对象为自选名单(校本)
  290. foreach (Member stus in stuList.members)
  291. {
  292. if (!ids.Contains(stus.id))
  293. {
  294. ids.Add(stus.id);
  295. }
  296. }
  297. }
  298. }*/
  299. foreach (RMember member in rGroup.members)
  300. {
  301. ids.Add((member.id, member.code));
  302. }
  303. //ids = members.Where(c => c.id.Equals(cla)).SelectMany(m => m.members).Select(g => g.id).ToList();
  304. foreach (var (sId, scode) in ids)
  305. {
  306. result.mark.Add(marks);
  307. result.studentIds.Add(sId);
  308. //result.scIds.Add(scode ?? "");
  309. result.studentAnswers.Add(ans);
  310. result.studentScores.Add(ansPoint);
  311. result.ans.Add(anses);
  312. result.sum.Add(0);
  313. result.status.Add(1);
  314. }
  315. //result.progress = info.progress;
  316. result.school = info.school;
  317. m++;
  318. await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(result, new Azure.Cosmos.PartitionKey($"{result.code}"));
  319. }
  320. }
  321. }
  322. else
  323. {
  324. //处理单科结算时科目与试卷信息匹配的问题
  325. int gno = 0;
  326. foreach (ExamSubject subject in info.subjects)
  327. {
  328. if (subject.classCount == classes.Count)
  329. {
  330. await createClassResultAsync(info, examClassResults, subject, gno, _azureCosmos, _dingDing, _azureStorage);
  331. }
  332. gno++;
  333. }
  334. var isScore = examClassResults.SelectMany(e => e.studentScores).ToList().Exists(c => c.Contains(-1));
  335. int newStatus = 0;
  336. if (!isScore)
  337. {
  338. newStatus = 1;
  339. }
  340. Settlement settlement = await getMore(client, info, examClassResults);
  341. long nowTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  342. //判断评分状态是否发生变化,便于实时的更新评测基本信息
  343. if (info.average != settlement.score || info.sStatus != newStatus)
  344. {
  345. info.sRate = settlement.rate;
  346. info.sStatus = newStatus;
  347. info.updateTime = nowTime;
  348. info.average = settlement.score;
  349. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ExamInfo>(info, info.id, new PartitionKey(info.code));
  350. }
  351. }
  352. }
  353. catch (Exception e)
  354. {
  355. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测going状态异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  356. }
  357. finally
  358. {
  359. // 发送信息通知
  360. var messageEnd = new ServiceBusMessage(new { id = data.id, progress = "finish", code = data.code }.ToJsonString());
  361. messageEnd.ApplicationProperties.Add("name", "Exam");
  362. if (records.Count > 0)
  363. {
  364. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(data.endTime));
  365. try
  366. {
  367. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), records[0].sequenceNumber);
  368. }
  369. catch (Exception)
  370. {
  371. }
  372. records[0].sequenceNumber = end;
  373. await table.SaveOrUpdate<ChangeRecord>(records[0]);
  374. //await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(record, record.id, new Azure.Cosmos.PartitionKey($"{record.code}"));
  375. }
  376. else
  377. {
  378. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(data.endTime));
  379. //string pk = String.Format("{0}{1}{2}", info.code, "-", "going");
  380. ChangeRecord changeRecord = new ChangeRecord
  381. {
  382. RowKey = data.id,
  383. PartitionKey = PartitionKey,
  384. sequenceNumber = end,
  385. msgId = messageEnd.MessageId
  386. };
  387. await table.Save<ChangeRecord>(changeRecord);
  388. //await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  389. }
  390. }
  391. break;
  392. case "finish":
  393. int fno = 0;
  394. try
  395. {
  396. //用来判定是否完成评分
  397. //bool isScore = true;
  398. await resultStatus(client, examClassResults);
  399. Settlement settlement = await getMore(client, info, examClassResults);
  400. var isScore = examClassResults.SelectMany(e => e.studentScores).ToList().Exists(c => c.Contains(-1));
  401. int newStatus = 0;
  402. if (!isScore)
  403. {
  404. newStatus = 1;
  405. }
  406. await Activity(_coreAPIHttpService, info, classes, client, _dingDing, sub, examClassResults);
  407. foreach (ExamSubject subject in info.subjects)
  408. {
  409. await createClassResultAsync(info, examClassResults, subject, fno, _azureCosmos, _dingDing, _azureStorage);
  410. fno++;
  411. }
  412. //判断均分是否发生变化,便于实时的更新评测基本信息
  413. if (info.sRate != settlement.rate || info.average != settlement.score || info.sStatus != newStatus || info.qRate != settlement.qrate)
  414. {
  415. info.sRate = settlement.rate;
  416. info.average = settlement.score;
  417. info.sStatus = newStatus;
  418. info.lostStu = settlement.stus;
  419. info.stuCount = settlement.total;
  420. info.qRate = settlement.qrate;
  421. //处理试卷活动结束统计账户信息
  422. List<FMember> idList = await GroupListService.GetFinishMemberInfo(_coreAPIHttpService, client, _dingDing, info.school, info.classes, info.stuLists, null);
  423. info.staffIds = idList;
  424. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ExamInfo>(info, info.id, new Azure.Cosmos.PartitionKey(info.code));
  425. }
  426. }
  427. catch (Exception e)
  428. {
  429. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测finish状态异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  430. }
  431. break;
  432. }
  433. }
  434. }
  435. catch (CosmosException e)
  436. {
  437. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.Status}", GroupNames.醍摩豆服務運維群組);
  438. }
  439. catch (Exception e)
  440. {
  441. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-评测结算异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  442. }
  443. }
  444. public static async Task resultStatus(CosmosClient client, List<ExamClassResult> examClassResults)
  445. {
  446. List<Task<ItemResponse<ExamClassResult>>> tasks = new();
  447. //结算单科单班的标准差和平均分
  448. foreach (ExamClassResult classResult in examClassResults)
  449. {
  450. //标记单科单班总得分
  451. double subScore = 0;
  452. //标准差
  453. double sPowSum = 0;
  454. List<double> newSumScore = new List<double>();
  455. int lostStu = classResult.status.Where(c => c == 1).ToList().Count;
  456. var scount = classResult.studentIds.Count - lostStu;
  457. int index = 0;
  458. if (classResult.status.Count > 0)
  459. {
  460. foreach (var sta in classResult.status)
  461. {
  462. if (sta == 1)
  463. {
  464. for (int i = 0; i < classResult.studentScores[index].Count; i++)
  465. {
  466. if (classResult.studentScores[index][i] == -1)
  467. {
  468. classResult.studentScores[index][i] = 0;
  469. }
  470. }
  471. }
  472. else if (sta == 0)
  473. {
  474. //var ans = classResult.studentAnswers[index];
  475. //该学生缺考,历史数据的判定
  476. //if (ans.Count == 0)
  477. //{
  478. for (int i = 0; i < classResult.studentScores[index].Count; i++)
  479. {
  480. if (classResult.studentScores[index][i] == -1)
  481. {
  482. classResult.studentScores[index][i] = 0;
  483. }
  484. }
  485. /*if (ans.Count == 0)
  486. {
  487. classResult.status[index] = 1;
  488. } */
  489. //}
  490. }
  491. index++;
  492. }
  493. }
  494. else
  495. {
  496. List<int> sta = new();
  497. foreach (var id in classResult.studentIds)
  498. {
  499. sta.Add(0);
  500. }
  501. classResult.status = sta;
  502. foreach (var ans in classResult.studentAnswers)
  503. {
  504. //该学生缺考,历史数据的判定
  505. if (ans.Count == 0)
  506. {
  507. for (int i = 0; i < classResult.studentScores[index].Count; i++)
  508. {
  509. if (classResult.studentScores[index][i] == -1)
  510. {
  511. classResult.studentScores[index][i] = 0;
  512. }
  513. }
  514. classResult.status[index] = 1;
  515. }
  516. index++;
  517. }
  518. }
  519. int sIndex = 0;
  520. foreach (List<double> sc in classResult.studentScores)
  521. {
  522. List<double> newSc = new List<double>();
  523. foreach (double ssc in sc)
  524. {
  525. if (ssc == -1)
  526. {
  527. newSc.Add(0);
  528. }
  529. else
  530. {
  531. newSc.Add(ssc);
  532. }
  533. }
  534. double nc = Math.Round(newSc.Sum(), 2);
  535. newSumScore.Add(nc);
  536. subScore += nc;
  537. classResult.sum[sIndex] = nc;
  538. sIndex++;
  539. }
  540. double rateScore = scount > 0 ? Math.Round(subScore * 1.0 / scount, 2) : 0;
  541. foreach (double scs in newSumScore)
  542. {
  543. sPowSum += Math.Pow(scs - rateScore, 2);
  544. }
  545. classResult.standard = Math.Round(scount > 0 ? Math.Pow(sPowSum / scount, 0.5) : 0, 2);
  546. classResult.average = scount > 0 ? Math.Round(subScore / scount, 2) : 0;
  547. classResult.progress = true;
  548. tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new PartitionKey($"{classResult.code}")));
  549. }
  550. await Task.WhenAll(tasks);
  551. }
  552. public static async Task<Settlement> getMore(CosmosClient client, ExamInfo info, List<ExamClassResult> examClassResults)
  553. {
  554. //计算单次考试简易统计信息
  555. Settlement settlement = new();
  556. List<ExamResult> examResults = new();
  557. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamResult>(
  558. queryText: $"select value(c) from c where c.examId = '{info.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}") }))
  559. {
  560. examResults.Add(item);
  561. }
  562. if (examResults.Count > 0)
  563. {
  564. //记录某次考试所有学生得分总分
  565. double score = 0;
  566. double allScore = 0;
  567. int stuCount = 0;
  568. //标准差
  569. double powSum = 0;
  570. List<string> losStu = new List<string>();
  571. //当前完成考试得人数
  572. int total = examResults[0].studentIds.Distinct().Count();
  573. //先与第一个值取并集
  574. losStu = losStu.Union(examResults[0].lostStus).ToList();
  575. foreach (ExamResult examResult in examResults)
  576. {
  577. //取交集
  578. losStu = losStu.Intersect(examResult.lostStus).ToList();
  579. if (info.id == examResult.examId)
  580. {
  581. //处理缺考的学生
  582. List<string> stus = examResult.studentIds.Except(losStu).ToList();
  583. foreach (var id in stus)
  584. {
  585. int index = examResult.studentIds.IndexOf(id);
  586. score += examResult.studentScores[index].Sum();
  587. }
  588. /*foreach (List<double> sc in examResult.studentScores)
  589. {
  590. score += sc.Sum();
  591. }*/
  592. stuCount = examResult.studentIds.Count - losStu.Count;
  593. }
  594. //powSum += Math.Pow(score - examResult.studentIds.Count > 0 ? Math.Round(score * 1.0 / examResult.studentIds.Count, 2) : 0, 2);
  595. }
  596. double NewsRateScore = stuCount > 0 ? Math.Round(score * 1.0 / stuCount, 2) : 0;
  597. foreach (PaperSimple simple in info.papers)
  598. {
  599. allScore += simple.point.Sum();
  600. }
  601. //计算全科标准差
  602. double qk = 0;
  603. foreach (string id in examResults[0].studentIds)
  604. {
  605. //计算整体缺考人数
  606. foreach (var ec in examClassResults)
  607. {
  608. int index = ec.studentIds.IndexOf(id);
  609. if (index > -1)
  610. {
  611. if (ec.status[index] == 1)
  612. {
  613. qk++;
  614. break;
  615. }
  616. }
  617. }
  618. double sc = 0;
  619. foreach (ExamResult result in examResults)
  620. {
  621. if (result.studentScores.Count > 0)
  622. {
  623. sc += result.studentScores[result.studentIds.IndexOf(id)].Sum();
  624. }
  625. }
  626. powSum += Math.Pow(sc - NewsRateScore, 2);
  627. }
  628. info.standard = Math.Round(total > 0 ? Math.Pow(powSum / total, 0.5) : 0, 2);
  629. double NewsRate = allScore > 0 ? Math.Round(NewsRateScore / allScore * 100, 2) : 0;
  630. double qrate = Math.Round(total > 0 ? qk / total * 100 : 0, 2);
  631. settlement.rate = NewsRate;
  632. settlement.score = NewsRateScore;
  633. settlement.stus = losStu;
  634. settlement.total = total;
  635. settlement.qrate = qrate;
  636. }
  637. return settlement;
  638. }
  639. //处理全部学生选题计数
  640. public static async Task examRecordCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, ExamResult er, List<ExamClassResult> classResults, AzureCosmosFactory _azureCosmos)
  641. {
  642. try
  643. {
  644. List<double> scores = new List<double>();
  645. foreach (List<double> sc in er.studentScores)
  646. {
  647. scores.Add(sc.Sum());
  648. }
  649. //确定高分组 最低分数
  650. //var srowallorder = scores.EnumerateIndexed().OrderByDescending(g => g.Item2); //各生總分排序
  651. //var srowallorder = scores.OrderByDescending(g => g);
  652. double[] point = StringHelper.ListTodouble(er.paper.point);
  653. double[,] result = StringHelper.ListToDouble(er.studentScores);
  654. var cdm = new ClouDASMatrix(result, point);
  655. scores.Sort((s1, s2) => { return s2.CompareTo(s1); });
  656. int rhwCount = cdm.SH.Count();
  657. double rhw = cdm.SH.LastOrDefault().Item2;
  658. int rhlCount = cdm.SL.Count();
  659. double rhl = cdm.SL.FirstOrDefault().Item2;
  660. List<string> phs = new();
  661. List<string> pls = new();
  662. //分别获取高分组低分组人员
  663. foreach (var ph in cdm.SH)
  664. {
  665. phs.Add(er.studentIds[ph.Item1]);
  666. }
  667. foreach (var pl in cdm.SL)
  668. {
  669. pls.Add(er.studentIds[pl.Item1]);
  670. }
  671. /* if (scores.Count > 3)
  672. {
  673. rhwCount = Convert.ToInt32(Math.Floor(scores.Count * 0.27));
  674. rhw = rhwCount > 0 ? scores[rhwCount - 1] : 0;
  675. rhlCount = Convert.ToInt32(Math.Ceiling(scores.Count * 0.73));
  676. rhl = rhlCount > 0 ? scores[rhlCount] : 0;
  677. }
  678. else
  679. {
  680. rhwCount = Convert.ToInt32(Math.Floor(scores.Count * 0.27));
  681. rhw = rhwCount > 0 ? scores[rhwCount] : 0;
  682. rhlCount = Convert.ToInt32(Math.Ceiling(scores.Count * 0.73));
  683. rhl = rhlCount > 0 ? scores[rhlCount - 1] : 0;
  684. }*/
  685. /*int rhwCount = Convert.ToInt32(Math.Floor(scores.Count * 0.27));
  686. double rhw = rhwCount > 0 ? scores[rhwCount-1] : 0;
  687. //var rhww = srowallorder.Take(Convert.ToInt32(Math.Floor(scores.Count * 0.27)));
  688. //确定低分组 最高分数
  689. //scores.Sort((s1, s2) => { return s1.CompareTo(s2); });
  690. int rhlCount = Convert.ToInt32(Math.Ceiling(scores.Count * 0.73));
  691. double rhl = rhlCount > 0 ? scores[rhlCount-1] : 0;*/
  692. //var rhll = srowallorder.Skip(Convert.ToInt32(Math.Ceiling(scores.Count * 0.73)));
  693. //存放高分组学生ID
  694. List<string> phId = new();
  695. List<string> plId = new();
  696. List<List<List<string>>> opth = new();
  697. List<List<List<string>>> optl = new();
  698. List<double> akp = await knowledgeCount(info, subject, _dingDing, no, classResults, rhwCount, rhw, rhlCount, rhl, _azureCosmos);
  699. List<double> afp = await fieldCount(info, subject, _dingDing, no, classResults, rhwCount, rhw, rhlCount, rhl, _azureCosmos);
  700. int PHCount = 0;
  701. int PLCount = 0;
  702. foreach (ExamClassResult classResult in classResults)
  703. {
  704. if (classResult.subjectId.Equals(subject.id))
  705. {
  706. foreach (string id in classResult.studentIds)
  707. {
  708. int index = classResult.studentIds.IndexOf(id);
  709. if (classResult.studentScores.Count > 0)
  710. {
  711. if (phs.Contains(id))
  712. {
  713. if (classResult.ans.Count > 0)
  714. {
  715. opth.Add(classResult.ans[index]);
  716. PHCount++;
  717. continue;
  718. }
  719. }
  720. if (pls.Contains(id))
  721. {
  722. if (classResult.ans.Count > 0)
  723. {
  724. optl.Add(classResult.ans[index]);
  725. PLCount++;
  726. continue;
  727. }
  728. }
  729. }
  730. }
  731. }
  732. }
  733. er.phc = getMore(info, no, opth);
  734. er.plc = getMore(info, no, optl);
  735. er.afp = afp;
  736. er.akp = akp;
  737. }
  738. catch (Exception ex)
  739. {
  740. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测作答记录结算异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  741. }
  742. }
  743. public static async Task<List<RGroupList>> Activity(CoreAPIHttpService _coreAPIHttpService, ExamInfo info, List<string> classes, CosmosClient client, DingDing _dingDing, List<string> sub, List<ExamClassResult> results)
  744. {
  745. List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
  746. if (info.groupLists.Count > 0)
  747. {
  748. var group = info.groupLists;
  749. foreach (var gp in group)
  750. {
  751. foreach (KeyValuePair<string, List<string>> pp in gp)
  752. {
  753. ps.Add((pp.Key, pp.Value));
  754. }
  755. }
  756. }
  757. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, classes, info.school, ps);
  758. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  759. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  760. List<StuActivity> stuActivities = new List<StuActivity>();
  761. List<StuActivity> tmdActivities = new List<StuActivity>();
  762. if (addTmdidsCls.IsNotEmpty())
  763. {
  764. addTmdidsCls.ForEach(x =>
  765. {
  766. HashSet<string> classIds = new HashSet<string>();
  767. classLists.ForEach(z =>
  768. {
  769. z.members.ForEach(y =>
  770. {
  771. if (y.id.Equals(x.id) && y.type == 1)
  772. {
  773. classIds.Add(z.id);
  774. }
  775. });
  776. });
  777. bool iss = false;
  778. //标记学生作答状态
  779. int ts = 0;
  780. if (results.Count > 0)
  781. {
  782. foreach (ExamClassResult exam in results)
  783. {
  784. int index = exam.studentIds.IndexOf(x.id);
  785. if (index != -1)
  786. {
  787. if (exam.studentAnswers[index].Count > 0)
  788. {
  789. bool flag = exam.studentScores[index].Exists(x => x == -1);
  790. if (!flag)
  791. {
  792. ts = 1;
  793. iss = true;
  794. break;
  795. }
  796. else
  797. {
  798. ts = 0;
  799. }
  800. }
  801. else
  802. {
  803. ts = -1;
  804. }
  805. }
  806. }
  807. }
  808. else
  809. {
  810. ts = -1;
  811. }
  812. tmdActivities.Add(new StuActivity
  813. {
  814. pk = "Activity",
  815. id = info.id,
  816. code = $"Activity-{x.id}",
  817. type = "Exam",
  818. name = info.name,
  819. source = info.source,
  820. startTime = info.startTime,
  821. endTime = info.endTime,
  822. scode = info.code,
  823. scope = info.scope,
  824. school = info.school,
  825. creatorId = info.creatorId,
  826. subjects = sub,
  827. blob = null,
  828. owner = info.owner,
  829. createTime = info.createTime,
  830. taskStatus = ts,
  831. qamode = info.qamode,
  832. ext = new Dictionary<string, JsonElement>() { { "type", info.examType.ToJsonString().ToObject<JsonElement>() },
  833. { "subjects", info.subjects.ToJsonString().ToObject<JsonElement>() } },
  834. sStatus = iss ? 1 : 0,
  835. classIds = classIds.ToList()
  836. });
  837. });
  838. }
  839. if (addStudentsCls.IsNotEmpty())
  840. {
  841. addStudentsCls.ForEach(x =>
  842. {
  843. HashSet<string> classIds = new HashSet<string>();
  844. classLists.ForEach(z =>
  845. {
  846. z.members.ForEach(y =>
  847. {
  848. if (y.id.Equals(x.id) && y.code.Equals(info.school) && y.type == 2)
  849. {
  850. classIds.Add(z.id);
  851. }
  852. });
  853. });
  854. bool iss = false;
  855. //标记学生作答状态
  856. int ts = 0;
  857. if (results.Count > 0)
  858. {
  859. foreach (ExamClassResult exam in results)
  860. {
  861. int index = exam.studentIds.IndexOf(x.id);
  862. if (index != -1)
  863. {
  864. if (exam.studentAnswers[index].Count > 0)
  865. {
  866. bool flag = exam.studentScores[index].Exists(x => x == -1);
  867. if (!flag)
  868. {
  869. ts = 1;
  870. iss = true;
  871. break;
  872. }
  873. else
  874. {
  875. ts = 0;
  876. }
  877. }
  878. else
  879. {
  880. ts = -1;
  881. }
  882. }
  883. }
  884. }
  885. else
  886. {
  887. ts = -1;
  888. }
  889. stuActivities.Add(new StuActivity
  890. {
  891. pk = "Activity",
  892. id = info.id,
  893. code = $"Activity-{x.code.Replace("Base-", "")}-{x.id}",
  894. type = "Exam",
  895. name = info.name,
  896. source = info.source,
  897. startTime = info.startTime,
  898. endTime = info.endTime,
  899. scode = info.code,
  900. scope = info.scope,
  901. school = info.school,
  902. creatorId = info.creatorId,
  903. subjects = sub,
  904. blob = null,
  905. owner = info.owner,
  906. classIds = classIds.ToList(),
  907. createTime = info.createTime,
  908. qamode = info.qamode,
  909. ext = new Dictionary<string, JsonElement>() { { "type", info.examType.ToJsonString().ToObject<JsonElement>() },
  910. { "subjects", info.subjects.ToJsonString().ToObject<JsonElement>() } },
  911. taskStatus = ts,
  912. sStatus = iss ? 1 : 0,
  913. });
  914. });
  915. }
  916. await ActivityService.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities, null);
  917. return classLists;
  918. }
  919. public static async Task<List<double>> knowledgeCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, List<ExamClassResult> classResults,
  920. double rhwCount, double rhw, double rhlCount, double rhl, AzureCosmosFactory _azureCosmos)
  921. {
  922. List<double> akp = new();
  923. try
  924. {
  925. int phcount = 0;
  926. int plcount = 0;
  927. //存放并去重知识点
  928. HashSet<string> kname = new HashSet<string>();
  929. if (info.papers[no].knowledge.Count > 0)
  930. {
  931. info.papers[no].knowledge.ForEach(kno =>
  932. {
  933. kno.ForEach(k =>
  934. {
  935. kname.Add(k);
  936. });
  937. });
  938. List<string> knowledgeName = new List<string>();
  939. foreach (string cla in kname)
  940. {
  941. knowledgeName.Add(cla);
  942. }
  943. for (int k = 0; k < knowledgeName.Count; k++)
  944. {
  945. if (null == knowledgeName[k])
  946. {
  947. knowledgeName.Remove(knowledgeName[k]);
  948. }
  949. }
  950. foreach (ExamClassResult classResult in classResults)
  951. {
  952. if (classResult.subjectId.Equals(subject.id))
  953. {
  954. //List<int> phc = new List<int>();
  955. List<int> ph = new List<int>();
  956. List<int> pl = new List<int>();
  957. List<int> pc = new List<int>();
  958. List<double> persent = new List<double>();
  959. int lostStu = classResult.status.Where(c => c == 1).ToList().Count;
  960. for (int i = 0; i < knowledgeName.Count; i++)
  961. {
  962. //初始化单个知识点得分
  963. double score = 0;
  964. int n = 0;
  965. int phCount = 0;
  966. int plCount = 0;
  967. int pCount = 0;
  968. double classScore = 0;
  969. foreach (List<string> str in info.papers[no].knowledge)
  970. {
  971. if (str.Contains(knowledgeName[i]))
  972. {
  973. var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
  974. classScore += info.papers[no].point.Count > 0 ? info.papers[no].point[n] * itemPersent : 0;
  975. foreach (string id in classResult.studentIds)
  976. {
  977. int index = classResult.studentIds.IndexOf(id);
  978. if (classResult.studentScores.Count > 0)
  979. {
  980. if (classResult.studentScores[index].Count > 0)
  981. {
  982. score += classResult.studentScores[index][n] == -1 ? 0 : classResult.studentScores[index][n] * itemPersent;
  983. if (classResult.studentScores[index].Sum() >= rhw && phcount < rhwCount)
  984. {
  985. if (classResult.studentScores[index][n] <= 0)
  986. {
  987. phCount++;
  988. }
  989. phcount++;
  990. continue;
  991. }
  992. if (classResult.studentScores[index].Sum() <= rhl && plcount < (info.stuCount - rhlCount))
  993. {
  994. if (classResult.studentScores[index][n] <= 0)
  995. {
  996. plCount++;
  997. }
  998. plcount++;
  999. continue;
  1000. }
  1001. if (classResult.studentScores[index][n] <= 0)
  1002. {
  1003. pCount++;
  1004. }
  1005. }
  1006. }
  1007. }
  1008. }
  1009. n++;
  1010. }
  1011. pc.Add(pCount);
  1012. ph.Add(phCount);
  1013. pl.Add(plCount);
  1014. double per = classResult.studentIds.Count - lostStu > 0 ? Math.Round(score / (classResult.studentIds.Count - lostStu), 2) : 0;
  1015. persent.Add(classScore > 0 ? Math.Round(per / classScore, 2) : 0);
  1016. }
  1017. classResult.phc = ph;
  1018. classResult.plc = pl;
  1019. classResult.pc = pc;
  1020. classResult.krate = persent;
  1021. }
  1022. //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new Azure.Cosmos.PartitionKey($"{classResult.code}"));
  1023. }
  1024. foreach (string k in knowledgeName)
  1025. {
  1026. double score = 0;
  1027. double allScore = 0;
  1028. int count = 0;
  1029. int m = 0;
  1030. foreach (List<string> str in info.papers[no].knowledge) {
  1031. if (str.Contains(k)) {
  1032. var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
  1033. allScore += info.papers[no].point.Count > 0 ? info.papers[no].point[m] * itemPersent : 0;
  1034. }
  1035. m++;
  1036. }
  1037. foreach (ExamClassResult result in classResults)
  1038. {
  1039. if (result.subjectId.Equals(subject.id))
  1040. {
  1041. int n = 0;
  1042. foreach (List<string> str in info.papers[no].knowledge)
  1043. {
  1044. if (str.Contains(k))
  1045. {
  1046. var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
  1047. if (result.studentScores.Count > 0)
  1048. {
  1049. foreach (List<double> sc in result.studentScores)
  1050. {
  1051. double tsc = sc[n] == -1 ? 0 : sc[n];
  1052. score += (tsc * itemPersent);
  1053. }
  1054. }
  1055. }
  1056. n++;
  1057. }
  1058. count += result.studentIds.Count;
  1059. }
  1060. }
  1061. double per = count - info.lostStu.Count > 0 ? Math.Round(score / (count - info.lostStu.Count), 2) : 0;
  1062. akp.Add(allScore > 0 ? Math.Round(per / allScore, 2) : 0);
  1063. }
  1064. }
  1065. return akp;
  1066. }
  1067. catch (Exception ex)
  1068. {
  1069. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测知识点结算异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1070. return null;
  1071. }
  1072. }
  1073. public static async Task<List<double>> fieldCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, List<ExamClassResult> classResults,
  1074. double rhwCount, double rhw, double rhlCount, double rhl, AzureCosmosFactory _azureCosmos)
  1075. {
  1076. List<double> afp = new();
  1077. try
  1078. {
  1079. int phcount = 0;
  1080. int plcount = 0;
  1081. //存放并去重知识点
  1082. List<int> knowledgeName = new List<int>() { 1, 2, 3, 4, 5, 6 };
  1083. /* knowledgeName.Add(1);
  1084. knowledgeName.Add(2);
  1085. knowledgeName.Add(3);
  1086. knowledgeName.Add(4);
  1087. knowledgeName.Add(5);
  1088. knowledgeName.Add(6);*/
  1089. foreach (ExamClassResult classResult in classResults)
  1090. {
  1091. if (classResult.subjectId.Equals(subject.id))
  1092. {
  1093. //List<int> phc = new List<int>();
  1094. List<int> ph = new List<int>();
  1095. List<int> pl = new List<int>();
  1096. List<int> pc = new List<int>();
  1097. List<double> persent = new List<double>();
  1098. int lostStu = classResult.status.Where(c => c == 1).ToList().Count;
  1099. for (int i = 0; i < knowledgeName.Count; i++)
  1100. {
  1101. //初始化单个知识点得分
  1102. double score = 0;
  1103. int n = 0;
  1104. int phCount = 0;
  1105. int plCount = 0;
  1106. int pCount = 0;
  1107. double classScore = 0;
  1108. if (info.papers[no].field.Count > 0)
  1109. {
  1110. foreach (int str in info.papers[no].field)
  1111. {
  1112. if (str == knowledgeName[i])
  1113. {
  1114. var itemPersent = 1;
  1115. classScore += info.papers[no].point.Count > 0 ? info.papers[no].point[n] * itemPersent : 0;
  1116. foreach (string id in classResult.studentIds)
  1117. {
  1118. int index = classResult.studentIds.IndexOf(id);
  1119. if (classResult.studentScores.Count > 0)
  1120. {
  1121. if (classResult.studentScores[index].Count > 0)
  1122. {
  1123. score += classResult.studentScores[index][n] == -1 ? 0 : classResult.studentScores[index][n];
  1124. if (classResult.studentScores[index].Sum() >= rhw && phcount < rhwCount)
  1125. {
  1126. if (classResult.studentScores[index][n] <= 0)
  1127. {
  1128. phCount++;
  1129. }
  1130. phcount++;
  1131. continue;
  1132. }
  1133. if (classResult.studentScores[index].Sum() <= rhl && plcount < (info.stuCount - rhlCount))
  1134. {
  1135. if (classResult.studentScores[index][n] <= 0)
  1136. {
  1137. plCount++;
  1138. }
  1139. plcount++;
  1140. continue;
  1141. }
  1142. if (classResult.studentScores[index][n] <= 0)
  1143. {
  1144. pCount++;
  1145. }
  1146. }
  1147. }
  1148. }
  1149. }
  1150. n++;
  1151. }
  1152. pc.Add(pCount);
  1153. ph.Add(phCount);
  1154. pl.Add(plCount);
  1155. double per = classResult.studentIds.Count - lostStu > 0 ? Math.Round(score / (classResult.studentIds.Count - lostStu), 2) : 0;
  1156. persent.Add(classScore > 0 ? Math.Round(per / classScore, 2) : 0);
  1157. }
  1158. }
  1159. classResult.fphc = ph;
  1160. classResult.fplc = pl;
  1161. classResult.fpc = pc;
  1162. classResult.frate = persent;
  1163. }
  1164. //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new Azure.Cosmos.PartitionKey($"{classResult.code}"));
  1165. }
  1166. for (int i = 0; i < knowledgeName.Count; i++)
  1167. {
  1168. double score = 0;
  1169. double allScore = 0;
  1170. int count = 0;
  1171. int m = 0;
  1172. foreach (int str in info.papers[no].field)
  1173. {
  1174. if (str == knowledgeName[i]) {
  1175. var itemPersent = 1;
  1176. allScore += info.papers[no].point.Count > 0 ? info.papers[no].point[m] * itemPersent : 0;
  1177. }
  1178. m++;
  1179. }
  1180. foreach (ExamClassResult result in classResults)
  1181. {
  1182. if (result.subjectId.Equals(subject.id))
  1183. {
  1184. int n = 0;
  1185. foreach (int str in info.papers[no].field)
  1186. {
  1187. var itemPersent = 1;
  1188. if (str == knowledgeName[i])
  1189. {
  1190. if (result.studentScores.Count > 0)
  1191. {
  1192. foreach (List<double> sc in result.studentScores)
  1193. {
  1194. double tsc = sc[n] == -1 ? 0 : sc[n];
  1195. score += tsc * itemPersent;
  1196. }
  1197. }
  1198. }
  1199. n++;
  1200. }
  1201. count += result.studentIds.Count;
  1202. }
  1203. }
  1204. double per = count - info.lostStu.Count > 0 ? Math.Round(score / (count - info.lostStu.Count), 2) : 0;
  1205. afp.Add(allScore > 0 ? Math.Round(per / allScore, 2) : 0);
  1206. }
  1207. return afp;
  1208. }
  1209. catch (Exception ex)
  1210. {
  1211. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测认知层次结算异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1212. return null;
  1213. }
  1214. }
  1215. //处理选题计数
  1216. public static List<Dictionary<string, int>> getMore(ExamInfo info, int no, List<List<List<string>>> list)
  1217. {
  1218. List<Dictionary<string, int>> recorde = new List<Dictionary<string, int>>();
  1219. try
  1220. {
  1221. for (int i = 0; i < info.papers[no].answers.Count; i++)
  1222. {
  1223. if (info.papers[no].answers[i].Count <= 0)
  1224. {
  1225. recorde.Add(new Dictionary<string, int>());
  1226. continue;
  1227. }
  1228. Dictionary<string, int> optCount = new Dictionary<string, int>();
  1229. foreach (List<List<string>> stu in list)
  1230. {
  1231. if (stu.Count == info.papers[no].answers.Count)
  1232. {
  1233. var item = stu[i];
  1234. foreach (string opt in item)
  1235. {
  1236. if (optCount.ContainsKey(opt))
  1237. {
  1238. optCount[opt] = optCount[opt] + 1;
  1239. }
  1240. else
  1241. {
  1242. optCount[opt] = 1;
  1243. }
  1244. }
  1245. }
  1246. }
  1247. recorde.Add(optCount);
  1248. }
  1249. return recorde;
  1250. }
  1251. catch (Exception)
  1252. {
  1253. return recorde;
  1254. }
  1255. }
  1256. public static async Task createClassResultAsync(ExamInfo info, List<ExamClassResult> examClassResults, ExamSubject subject, int no, AzureCosmosFactory _azureCosmos, DingDing _dingDing, AzureStorageFactory _azureStorage)
  1257. {
  1258. //保证试卷信息与科目信息同步
  1259. ExamResult result = new ExamResult();
  1260. //人数总和
  1261. int Count = 0;
  1262. int m = 0;
  1263. double score = 0;
  1264. //标准差
  1265. //double powSum = 0;
  1266. double allScore = info.papers[no].point.Sum();
  1267. List<ClassRange> classRanges = new List<ClassRange>();
  1268. List<string> lostStu = new List<string>();
  1269. List<double> csRate = new List<double>();
  1270. List<List<List<string>>> opt = new List<List<List<string>>>();
  1271. //List<Task<ItemResponse<ExamClassResult>>> tasks = new();
  1272. foreach (ExamClassResult classResult in examClassResults)
  1273. {
  1274. double classSrate = 0;
  1275. if (classResult.subjectId.Equals(subject.id))
  1276. {
  1277. foreach (List<List<string>> op in classResult.ans)
  1278. {
  1279. opt.Add(op);
  1280. }
  1281. //记录缺考学生索引位置
  1282. int index_stu = 0;
  1283. foreach (var ans in classResult.studentAnswers)
  1284. {
  1285. if (ans.Count == 0)
  1286. {
  1287. if (!lostStu.Contains(classResult.studentIds[index_stu]))
  1288. {
  1289. lostStu.Add(classResult.studentIds[index_stu]);
  1290. }
  1291. }
  1292. index_stu++;
  1293. }
  1294. int index = 0;
  1295. foreach (List<double> scores in classResult.studentScores)
  1296. {
  1297. List<double> newScores = new List<double>();
  1298. //int count = 0;
  1299. foreach (double sc in scores)
  1300. {
  1301. newScores.Add(sc > -1 ? sc : 0);
  1302. }
  1303. classSrate += newScores.Sum();
  1304. score += newScores.Sum();
  1305. result.studentScores.Add(newScores);
  1306. index++;
  1307. }
  1308. //处理班级信息
  1309. ClassRange range = new ClassRange();
  1310. range.id = classResult.info.id;
  1311. range.name = classResult.info.name;
  1312. range.gradeId = classResult.gradeId;
  1313. List<int> ran = new List<int>();
  1314. int stuCount = classResult.studentIds.Count;
  1315. //todo 与实际的缺考人数比较
  1316. int lostStus = classResult.status.Where(c => c == 1).ToList().Count;
  1317. Count += stuCount;
  1318. if (m == 0)
  1319. {
  1320. ran.Add(0);
  1321. ran.Add(stuCount - 1);
  1322. }
  1323. else
  1324. {
  1325. ran.Add(Count - stuCount);
  1326. ran.Add(Count - 1);
  1327. }
  1328. m++;
  1329. range.range = ran;
  1330. classRanges.Add(range);
  1331. //处理学生ID
  1332. foreach (string id in classResult.studentIds)
  1333. {
  1334. result.studentIds.Add(id);
  1335. }
  1336. if (allScore > 0)
  1337. {
  1338. csRate.Add(classResult.studentIds.Count - lostStus > 0 ? Math.Round(classSrate * 1.0 / (classResult.studentIds.Count - lostStus), 2) : 0 / allScore);
  1339. }
  1340. else
  1341. {
  1342. csRate.Add(0);
  1343. }
  1344. //powSum += Math.Pow(classSrate - result.average, 2);
  1345. //处理选项计数内容
  1346. }
  1347. //tasks.Add(_azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new PartitionKey($"{classResult.code}")));
  1348. }
  1349. //await tasks.TaskPage(10);
  1350. /*foreach (string id in result.lostStus) {
  1351. if (!examClassResults[0].studentIds.Contains(id)) {
  1352. int index = result.lostStus.IndexOf(id);
  1353. result.lostStus.RemoveAt(index);
  1354. }
  1355. }*/
  1356. //处理人员变更时被移除的人员
  1357. if (result.lostStus.Count > 0)
  1358. {
  1359. for (int i = 0; i < result.lostStus.Count; i++)
  1360. {
  1361. if (!examClassResults[0].studentIds.Contains(result.lostStus[i]))
  1362. {
  1363. result.lostStus.RemoveAt(i);
  1364. }
  1365. }
  1366. }
  1367. result.lostStus = lostStu;
  1368. result.record = getMore(info, no, opt);
  1369. result.average = result.studentIds.Count - result.lostStus.Count > 0 ? Math.Round(score * 1.0 / (result.studentIds.Count - result.lostStus.Count), 2) : 0;
  1370. double powSum = 0;
  1371. //int sco = 0;
  1372. result.studentIds.ForEach(x => {
  1373. double sc = result.studentScores[result.studentIds.IndexOf(x)].Sum();
  1374. powSum += Math.Pow(sc - result.average, 2);
  1375. });
  1376. result.standard = Math.Round((result.studentIds.Count - result.lostStus.Count) > 0 ? Math.Pow(powSum / (result.studentIds.Count - result.lostStus.Count), 0.5) : 0, 2);
  1377. result.csRate = csRate;
  1378. result.sRate = allScore > 0 ? Math.Round(result.average / allScore * 100, 2) : 0;
  1379. result.classes = classRanges;
  1380. result.code = "ExamResult-" + info.id;
  1381. result.school = info.school;
  1382. result.id = subject.id;
  1383. result.examId = info.id;
  1384. result.subjectId = subject.id;
  1385. result.year = info.year;
  1386. result.paper = info.papers[no];
  1387. //result.point = info.papers[j].point;
  1388. result.scope = info.scope;
  1389. result.name = info.name;
  1390. result.time = info.startTime;
  1391. await examRecordCount(info, subject, _dingDing, no, result, examClassResults, _azureCosmos);
  1392. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").UpsertItemAsync(result, new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}"));
  1393. List<ErrorItems> errorItems = new();
  1394. 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}'"))})";
  1395. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Student").GetItemQueryIterator<ErrorItems>(queryText: sqlqueryText, requestOptions: new QueryRequestOptions() {PartitionKey = new PartitionKey("ErrorItems") }))
  1396. {
  1397. errorItems.Add(item);
  1398. }
  1399. if (errorItems.Count == 0) {
  1400. // 新增逻辑 收集错题内容
  1401. BlobDownloadResult index_json;
  1402. if (info.scope.Equals("school"))
  1403. {
  1404. index_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{info.papers[no].blob}/index.json").DownloadContentAsync();
  1405. }
  1406. else {
  1407. index_json = await _azureStorage.GetBlobContainerClient($"{info.creatorId}").GetBlobClient($"{info.papers[no].blob}/index.json").DownloadContentAsync();
  1408. }
  1409. //BlobDownloadResult index_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{info.papers[no].blob}/index.json").DownloadContentAsync();
  1410. JObject jo = JObject.Parse(index_json.Content.ToString());
  1411. JArray array = jo.Value<JArray>("slides");
  1412. List<string> urls = new();
  1413. foreach (var ne in array)
  1414. {
  1415. if (!ne["type"].ToString().Equals("compose")) {
  1416. urls.Add(ne["url"].ToString());
  1417. }
  1418. }
  1419. string code = string.Empty;
  1420. string pk = string.Empty;
  1421. string table = "School";
  1422. if (info.scope.Equals("school"))
  1423. {
  1424. code = $"ErrorItems-{info.school}";
  1425. pk = $"Item-{info.school}";
  1426. }
  1427. else
  1428. {
  1429. code = "ErrorItems";
  1430. pk = $"Item-{info.creatorId}";
  1431. table = "Teacher";
  1432. }
  1433. // 获取整体的题目ID集合
  1434. List<string> ids = new();
  1435. List<(string id, string pid, int level, string type, List<string> knows)> itemInfos = new();
  1436. foreach (string url in urls)
  1437. {
  1438. string id = url.Replace(".json", "");
  1439. BlobDownloadResult index_item_json;
  1440. if (info.scope.Equals("school"))
  1441. {
  1442. index_item_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{info.papers[no].blob}/{url}").DownloadContentAsync();
  1443. }
  1444. else
  1445. {
  1446. index_item_json = await _azureStorage.GetBlobContainerClient($"{info.creatorId}").GetBlobClient($"{info.papers[no].blob}/{url}").DownloadContentAsync();
  1447. }
  1448. JObject keys = JObject.Parse(index_item_json.Content.ToString());
  1449. string type = keys["exercise"].Value<string>("type");
  1450. int level = keys["exercise"].Value<int>("level");
  1451. var knowledge = keys["exercise"].Value<JArray>("knowledge")?.ToObject<List<string>>();
  1452. string pid = keys.Value<string>("pid");
  1453. itemInfos.Add((id, pid, level, type, knowledge));
  1454. }
  1455. /*await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, table).GetItemQueryStreamIterator(
  1456. 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}") }))
  1457. {
  1458. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1459. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1460. {
  1461. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1462. while (accounts.MoveNext())
  1463. {
  1464. JsonElement account = accounts.Current;
  1465. string pid = "";
  1466. if (account.TryGetProperty("pid",out JsonElement element)) {
  1467. pid = element.GetString();
  1468. }
  1469. itemInfos.Add((account.GetProperty("id").GetString(), pid, account.GetProperty("level").GetInt32(), account.GetProperty("type").GetString()));
  1470. }
  1471. }
  1472. }*/
  1473. double[] point = StringHelper.ListTodouble(result.paper.point);
  1474. double[,] res = StringHelper.ListToDouble(result.studentScores);
  1475. var cdm = new ClouDASMatrix(res, point);
  1476. //需要努力的题目
  1477. var ss = cdm.StriveTopic;
  1478. int n = 0;
  1479. List<Task<ItemResponse<ErrorItems>>> task_error = new();
  1480. foreach (var sIds in result.studentIds)
  1481. {
  1482. ErrorItems error = new()
  1483. {
  1484. ttl = -1,
  1485. code = code,
  1486. id = Guid.NewGuid().ToString(),
  1487. stuId = sIds,
  1488. school = info.school,
  1489. activityId = info.id,
  1490. subjectId = result.subjectId,
  1491. time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1492. };
  1493. //顺序学生错题的索引
  1494. int[] item_index = ss[n];
  1495. foreach (var item in item_index)
  1496. {
  1497. Items items = new()
  1498. {
  1499. id = urls[item - 1].Replace(".json", ""),
  1500. blob = info.papers[no].blob
  1501. };
  1502. items.level = itemInfos.Where(c => c.id.Equals(items.id)).FirstOrDefault().level;
  1503. items.type = itemInfos.Where(c => c.id.Equals(items.id)).FirstOrDefault().type;
  1504. items.pId = itemInfos.Where(c => c.id.Equals(items.id)).FirstOrDefault().pid;
  1505. items.knowledge = itemInfos.Where(c => c.id.Equals(items.id)).FirstOrDefault().knows;
  1506. error.its.Add(items);
  1507. }
  1508. n++;
  1509. task_error.Add(_azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(error, new PartitionKey($"{error.code}")));
  1510. }
  1511. await task_error.TaskPage(10);
  1512. }
  1513. }
  1514. public class Settlement
  1515. {
  1516. public double rate { get; set; }
  1517. public double score { get; set; }
  1518. public List<string> stus { get; set; } = new List<string>();
  1519. public int total { get; set; }
  1520. public double qrate { get; set; }
  1521. }
  1522. }
  1523. }