TriggerExam.cs 84 KB

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