TriggerExam.cs 120 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192
  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 Newtonsoft.Json.Linq;
  21. using TEAMModelOS.SDK.Models.Cosmos.Student;
  22. using HTEXLib.Helpers.ShapeHelpers;
  23. using TEAMModelOS.Models.Dto;
  24. using TEAMModelOS.SDK.Models.Cosmos.Common;
  25. using DocumentFormat.OpenXml.Office2010.Excel;
  26. using DocumentFormat.OpenXml.Drawing.Charts;
  27. using DocumentFormat.OpenXml.Vml;
  28. using System.Net.Http;
  29. using Newtonsoft.Json;
  30. using System.Net;
  31. using System.Security.Policy;
  32. using Microsoft.Extensions.Configuration;
  33. using DocumentFormat.OpenXml.EMMA;
  34. using Microsoft.Extensions.Options;
  35. using TEAMModelOS.Models;
  36. using Microsoft.AspNetCore.Razor.TagHelpers;
  37. using HtmlAgilityPack;
  38. using Azure.Storage.Blobs;
  39. using System.ComponentModel;
  40. namespace TEAMModelOS.FunctionV4
  41. {
  42. public class TriggerExam
  43. {
  44. public static async Task Trigger(CoreAPIHttpService _coreAPIHttpService, AzureCosmosFactory _azureCosmos, AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
  45. CosmosClient client, JsonElement input, TriggerData data, IHttpClientFactory _httpClient, IConfiguration _configuration, HttpTrigger _httpTrigger)
  46. {
  47. List<ExamClassResult> examClassResults = new();
  48. List<ExamSubject> examSubjects = new();
  49. try
  50. {
  51. if ((data.status != null && data.status.Value == 404))
  52. {
  53. await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(data.id, new PartitionKey(data.code));
  54. ActivityList activity = input.ToObject<ActivityList>();
  55. await IESActivityService.DeleteActivity(_coreAPIHttpService, client, _dingDing, activity);
  56. var table_cancel = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  57. List<ChangeRecord> records = await table_cancel.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", data.id } });
  58. foreach (var record in records)
  59. {
  60. try
  61. {
  62. await table_cancel.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  63. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  64. }
  65. catch (Exception)
  66. {
  67. continue;
  68. }
  69. }
  70. await BIStats.SetTypeAddStats(client, _dingDing, data.school, "Exam", -1, careDate: data.startTime);//BI统计增/减量
  71. return;
  72. }
  73. ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(data.id, new Azure.Cosmos.PartitionKey($"{data.code}"));
  74. if (info != null)
  75. {
  76. if (info.scope.Equals("teacher", StringComparison.OrdinalIgnoreCase) || info.scope.Equals("private", StringComparison.OrdinalIgnoreCase))
  77. {
  78. 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}") }))
  79. {
  80. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  81. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  82. {
  83. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  84. {
  85. examClassResults.Add(obj.ToObject<ExamClassResult>());
  86. }
  87. }
  88. }
  89. }
  90. else
  91. {
  92. 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}") }))
  93. {
  94. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  95. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  96. {
  97. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  98. {
  99. examClassResults.Add(obj.ToObject<ExamClassResult>());
  100. }
  101. }
  102. }
  103. }
  104. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  105. string PartitionKey = string.Format("{0}{1}{2}", info.code, "-", info.progress);
  106. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", data.id }, { "PartitionKey", PartitionKey } });
  107. //处理科目信息
  108. List<string> sub = new List<string>();
  109. School sc = new();
  110. if (!string.IsNullOrEmpty(info.school) && !info.school.Equals("SYSTEM_NO_SCHOOL"))
  111. {
  112. sc = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(info.school, new Azure.Cosmos.PartitionKey("Base"));
  113. }
  114. foreach (ExamSubject subject in info.subjects)
  115. {
  116. sub.Add(subject.id);
  117. }
  118. //整合名单
  119. List<string> classes = ExamService.getClasses(info.classes, info.stuLists);
  120. //ChangeRecord record = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ChangeRecord>(input.Id, new Azure.Cosmos.PartitionKey($"{info.progress}"));
  121. switch (info.progress)
  122. {
  123. case "pending":
  124. var message = new ServiceBusMessage(new { id = data.id, progress = "going", code = data.code }.ToJsonString());
  125. message.ApplicationProperties.Add("name", "Exam");
  126. if (records.Count > 0)
  127. {
  128. try
  129. {
  130. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), records[0].sequenceNumber);
  131. }
  132. catch (Exception)
  133. {
  134. }
  135. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(data.startTime));
  136. records[0].sequenceNumber = start;
  137. await table.SaveOrUpdate<ChangeRecord>(records[0]);
  138. //await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(record, record.id, new Azure.Cosmos.PartitionKey($"{record.code}"));
  139. }
  140. else
  141. {
  142. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(data.startTime));
  143. //string pk = String.Format("{0}{1}{2}", info.code, "-", "pending");
  144. ChangeRecord changeRecord = new ChangeRecord
  145. {
  146. RowKey = data.id,
  147. PartitionKey = PartitionKey,
  148. sequenceNumber = start,
  149. msgId = message.MessageId
  150. };
  151. await table.Save<ChangeRecord>(changeRecord);
  152. //await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  153. }
  154. break;
  155. case "going":
  156. try
  157. {
  158. //向学生或醍摩豆账号发起通知
  159. #region
  160. //Notice notice = new Notice()
  161. //{
  162. // msgId = info.id,
  163. // creation = info.startTime,
  164. // expire = info.endTime,
  165. // creatorId = info.creatorId,
  166. // stuids = studentss,
  167. // tmdids = tmdids,
  168. // type = "notice",//评测参加通知
  169. // priority = "normal",
  170. // school = info.school,
  171. // scope = info.scope,
  172. // //data = new { }.ToJsonString()
  173. // body = new Body { sid = info.id, scode = info.code, spk = info.pk, biztype = "exam-join" }
  174. //};
  175. //var messageBlob = new ServiceBusMessage(notice.ToJsonString());
  176. //messageBlob.ApplicationProperties.Add("name", "Notice");
  177. //await _serviceBus.GetServiceBusClient().SendMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageBlob);
  178. #endregion
  179. //List<string> classes = new List<string>();
  180. //处理活动中间件
  181. List<RGroupList> members = await Activity(_coreAPIHttpService, info, classes, client, _dingDing, sub, examClassResults);
  182. if (examClassResults.Count == 0)
  183. {
  184. List<Task<ItemResponse<ExamClassResult>>> tasks = new List<Task<ItemResponse<ExamClassResult>>>();
  185. foreach (string cla in classes)
  186. {
  187. int m = 0;
  188. RGroupList rGroup = new();
  189. rGroup = members.Where(m => m.id.Equals(cla)).FirstOrDefault();
  190. foreach (ExamSubject subject in info.subjects)
  191. {
  192. string classCode = string.Empty;
  193. string cname = string.Empty;
  194. if (string.IsNullOrEmpty(info.school) || !info.scope.Equals("school", StringComparison.OrdinalIgnoreCase))
  195. {
  196. classCode = "ExamClassResult-" + info.creatorId;
  197. }
  198. else
  199. {
  200. classCode = "ExamClassResult-" + info.school;
  201. }
  202. cname = members.Where(m => m.id.Equals(cla)).FirstOrDefault()?.name;
  203. // 预处理活动中间件信息
  204. ExamClassResult result = new()
  205. {
  206. code = classCode,
  207. examId = info.id,
  208. id = Guid.NewGuid().ToString(),
  209. subjectId = subject.id,
  210. year = info.year,
  211. scope = info.scope
  212. };
  213. result.info.id = cla;
  214. result.info.name = cname;
  215. List<string> ans = new();
  216. List<List<string>> anses = new();
  217. List<List<Details>> marks = new();
  218. List<double> ansPoint = new();
  219. List<(string sId, string scode)> ids = new();
  220. foreach (double p in info.papers[m].point)
  221. {
  222. //Details details = new Details();
  223. //ans.Add(new List<string>());
  224. anses.Add(new List<string>());
  225. marks.Add(new List<Details>());
  226. ansPoint.Add(-1);
  227. }
  228. var sresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"Class-{info.school}"));
  229. if (sresponse.Status == 200)
  230. {
  231. using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
  232. Class classroom = json.ToObject<Class>();
  233. foreach (SDK.Models.Period period in sc.period)
  234. {
  235. if (period.id.Equals(classroom.periodId))
  236. {
  237. foreach (Semester semester in period.semesters)
  238. {
  239. if (semester.start == 1)
  240. {
  241. int year = DateTimeOffset.UtcNow.Year;
  242. int month = DateTimeOffset.UtcNow.Month;
  243. int day = DateTimeOffset.UtcNow.Day;
  244. int time = 0;
  245. if (month == semester.month)
  246. {
  247. time = day >= semester.day ? 0 : 1;
  248. }
  249. else
  250. {
  251. time = month > semester.month ? 0 : 1;
  252. }
  253. int eyear = year - time;
  254. result.gradeId = (eyear - classroom.year).ToString();
  255. }
  256. }
  257. }
  258. }
  259. //result.info.id = classroom.id;
  260. //result.info.name = classroom.name;
  261. //result.gradeId = classroom.year.ToString();
  262. //处理班级人数
  263. /* 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}") }))
  264. {
  265. using var json_stu = await JsonDocument.ParseAsync(item.ContentStream);
  266. if (json_stu.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  267. {
  268. var accounts = json_stu.RootElement.GetProperty("Documents").EnumerateArray();
  269. while (accounts.MoveNext())
  270. {
  271. JsonElement account = accounts.Current;
  272. ids.Add(account.GetProperty("id").GetString());
  273. }
  274. }
  275. }*/
  276. }
  277. /*if (info.scope.Equals("private", StringComparison.OrdinalIgnoreCase))
  278. {
  279. var stuResponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"GroupList"));
  280. if (stuResponse.Status == 200)
  281. {
  282. using var json = await JsonDocument.ParseAsync(stuResponse.ContentStream);
  283. GroupList stuList = json.ToObject<GroupList>();
  284. //result.info.id = stuList.id;
  285. result.info.name = stuList.name;
  286. //处理发布对象为自选名单(个人)
  287. foreach (Member stus in stuList.members)
  288. {
  289. if (!ids.Contains(stus.id))
  290. {
  291. ids.Add(stus.id);
  292. }
  293. }
  294. }
  295. }
  296. else
  297. {
  298. var stuResponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"GroupList-{info.school}"));
  299. if (stuResponse.Status == 200)
  300. {
  301. using var json = await JsonDocument.ParseAsync(stuResponse.ContentStream);
  302. GroupList stuList = json.ToObject<GroupList>();
  303. //result.info.id = stuList.id;
  304. result.info.name = stuList.name;
  305. //处理发布对象为自选名单(校本)
  306. foreach (Member stus in stuList.members)
  307. {
  308. if (!ids.Contains(stus.id))
  309. {
  310. ids.Add(stus.id);
  311. }
  312. }
  313. }
  314. }*/
  315. foreach (RMember member in rGroup.members)
  316. {
  317. ids.Add((member.id, member.code));
  318. }
  319. //ids = members.Where(c => c.id.Equals(cla)).SelectMany(m => m.members).Select(g => g.id).ToList();
  320. List<string> blobs = new();
  321. if (info.qamode == 2) {
  322. blobs = info.papers.Where(c => c.subjectId.Equals(subject.id)).Select(c => c.blob).ToList();
  323. }
  324. foreach (var (sId, scode) in ids)
  325. {
  326. result.mark.Add(marks);
  327. result.studentIds.Add(sId);
  328. //result.scIds.Add(scode ?? "");
  329. result.studentAnswers.Add(ans);
  330. result.studentScores.Add(ansPoint);
  331. result.ans.Add(anses);
  332. result.sum.Add(0);
  333. result.status.Add(1);
  334. if (info.qamode == 2) {
  335. result.paper.Add(blobs[new Random().Next(blobs.Count)]);
  336. }
  337. }
  338. //result.progress = info.progress;
  339. result.school = info.school;
  340. m++;
  341. tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(result, new PartitionKey($"{result.code}")));
  342. }
  343. }
  344. await tasks.TaskPage(10);
  345. }
  346. else
  347. {
  348. //处理单科结算时科目与试卷信息匹配的问题
  349. int gno = 0;
  350. foreach (ExamSubject subject in info.subjects)
  351. {
  352. if (subject.classCount == classes.Count)
  353. {
  354. await createClassResultAsync(info, examClassResults, subject, gno, _azureCosmos, _dingDing, _azureStorage, _httpClient, _configuration);
  355. }
  356. gno++;
  357. }
  358. var isScore = examClassResults.SelectMany(e => e.studentScores).ToList().Exists(c => c.Contains(-1));
  359. int newStatus = 0;
  360. if (!isScore)
  361. {
  362. newStatus = 1;
  363. }
  364. Settlement settlement = await getMore(client, info);
  365. long nowTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  366. //判断评分状态是否发生变化,便于实时的更新评测基本信息
  367. if (info.average != settlement.score || info.sStatus != newStatus)
  368. {
  369. info.sRate = settlement.rate;
  370. info.sStatus = newStatus;
  371. info.updateTime = nowTime;
  372. info.average = settlement.score;
  373. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ExamInfo>(info, info.id, new PartitionKey(info.code));
  374. }
  375. }
  376. }
  377. catch (Exception e)
  378. {
  379. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测going状态异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  380. }
  381. finally
  382. {
  383. // 发送信息通知
  384. var messageEnd = new ServiceBusMessage(new { id = data.id, progress = "finish", code = data.code }.ToJsonString());
  385. messageEnd.ApplicationProperties.Add("name", "Exam");
  386. if (records.Count > 0)
  387. {
  388. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(data.endTime));
  389. try
  390. {
  391. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), records[0].sequenceNumber);
  392. }
  393. catch (Exception)
  394. {
  395. }
  396. records[0].sequenceNumber = end;
  397. await table.SaveOrUpdate<ChangeRecord>(records[0]);
  398. //await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(record, record.id, new Azure.Cosmos.PartitionKey($"{record.code}"));
  399. }
  400. else
  401. {
  402. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(data.endTime));
  403. //string pk = String.Format("{0}{1}{2}", info.code, "-", "going");
  404. ChangeRecord changeRecord = new ChangeRecord
  405. {
  406. RowKey = data.id,
  407. PartitionKey = PartitionKey,
  408. sequenceNumber = end,
  409. msgId = messageEnd.MessageId
  410. };
  411. await table.Save<ChangeRecord>(changeRecord);
  412. //await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  413. }
  414. }
  415. break;
  416. case "finish":
  417. int fno = 0;
  418. try
  419. {
  420. //await SetLearnRecordContent(info, data, _azureStorage, _azureCosmos);
  421. //用来判定是否完成评分
  422. //bool isScore = true;
  423. await resultStatus(client, examClassResults);
  424. await Activity(_coreAPIHttpService, info, classes, client, _dingDing, sub, examClassResults);
  425. foreach (ExamSubject subject in info.subjects)
  426. {
  427. await createClassResultAsync(info, examClassResults, subject, fno, _azureCosmos, _dingDing, _azureStorage, _httpClient, _configuration);
  428. fno++;
  429. }
  430. Settlement settlement = await getMore(client, info);
  431. var isScore = examClassResults.SelectMany(e => e.studentScores).ToList().Exists(c => c.Contains(-1));
  432. int newStatus = 0;
  433. if (!isScore)
  434. {
  435. newStatus = 1;
  436. }
  437. //判断均分是否发生变化,便于实时的更新评测基本信息
  438. if (info.sRate != settlement.rate || info.average != settlement.score || info.sStatus != newStatus || info.qRate != settlement.qrate)
  439. {
  440. info.sRate = settlement.rate;
  441. info.average = settlement.score;
  442. info.sStatus = newStatus;
  443. info.lostStu = settlement.stus;
  444. info.stuCount = settlement.total;
  445. info.qRate = settlement.qrate;
  446. //新增数据推送 obj => Portrait
  447. Portrait portrait = new()
  448. {
  449. schoolCode = info.school,
  450. periodId = info.period.id,
  451. subjectId = "subject_intelligence"
  452. };
  453. //作答合格率
  454. var sta = examClassResults.SelectMany(x => x.status).ToList();
  455. /* var stus = examClassResults.SelectMany(x => x.studentIds).ToList();
  456. var stuScores = examClassResults.SelectMany(x => x.studentScores).ToList();*/
  457. var ansCount = sta.Where(x => x == 0).ToList();
  458. var persent = ansCount.Count * 1.0 / sta.Count * 100;
  459. var period = sc.period.Where(x => x.id.Equals(info.period.id)).FirstOrDefault();
  460. List<string> subjects = info.subjects.Select(x => x.id).ToList();
  461. //获取学期信息
  462. if (null != period && persent >= 60 && !subjects.Contains("subject_painting") && !subjects.Contains("subject_music"))
  463. {
  464. var (currSemester, studyYear, currSemesterDate, date, nextSemester) = SchoolService.GetSemester(period, info.startTime);
  465. //获取学生信息
  466. (List<RMember> rmembers, List<RGroupList> groups) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, info.classes, info.school);
  467. foreach (var member in rmembers)
  468. {
  469. if (info.lostStu.Contains(member.id))
  470. {
  471. continue;
  472. }
  473. PortraitStudent student = new()
  474. {
  475. studentId = member.id,
  476. name = member.name,
  477. classId = member.classId
  478. };
  479. var ec = examClassResults.Where(c => c.studentIds.Contains(member.id)).ToList();
  480. double scores = 0;
  481. List<(string subjectId, double score)> subScore = new();
  482. foreach (var eclass in ec)
  483. {
  484. int index_stu = eclass.studentIds.IndexOf(member.id);
  485. scores += eclass.sum[index_stu];
  486. subScore.Add((eclass.subjectId, eclass.sum[index_stu]));
  487. }
  488. SemesterData semesterData = new()
  489. {
  490. examName = info.name,
  491. examId = info.id,
  492. examDate = info.startTime,
  493. examType = info.examType?.name,
  494. year = info.year,
  495. semesterId = currSemester.id,
  496. totalScore = info.papers.SelectMany(x => x.point).Sum(),
  497. sumScore = scores,
  498. excellenceRate = 0,
  499. passRate = 0,
  500. };
  501. int index = 0;
  502. foreach (var sj in info.subjects)
  503. {
  504. ItemScore item = new()
  505. {
  506. id = sj.id,
  507. name = sj.name,
  508. score = subScore.Where(c => c.subjectId.Equals(sj.id)).FirstOrDefault().score,
  509. time = info.startTime,
  510. totalScore = info.papers[index].point.Sum(),
  511. type = sj.id
  512. };
  513. index++;
  514. semesterData.itemScore.Add(item);
  515. }
  516. student.semesterData.Add(semesterData);
  517. portrait.students.Add(student);
  518. }
  519. string location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
  520. var (status, json) = await _httpTrigger.RequestHttpTrigger(portrait, location, "upsert-student-portrait");
  521. }
  522. //PortraitStudent student = new();
  523. //处理试卷活动结束统计账户信息
  524. List<FMember> idList = await GroupListService.GetFinishMemberInfo(_coreAPIHttpService, client, _dingDing, info.school, info.classes, info.stuLists, null);
  525. info.staffIds = idList;
  526. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ExamInfo>(info, info.id, new Azure.Cosmos.PartitionKey(info.code));
  527. }
  528. await SetLearnRecordContent(info, data, _azureStorage, _azureCosmos);
  529. }
  530. catch (Exception e)
  531. {
  532. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测finish状态异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  533. }
  534. break;
  535. }
  536. }
  537. }
  538. catch (CosmosException e)
  539. {
  540. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.Status}", GroupNames.醍摩豆服務運維群組);
  541. }
  542. catch (Exception e)
  543. {
  544. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-评测结算异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  545. }
  546. }
  547. private static async Task SetLearnRecordContent(ExamInfo info, TriggerData data, AzureStorageFactory _azureStorage, AzureCosmosFactory _azureCosmos)
  548. {
  549. try
  550. {
  551. if (info.papers.Count > 0)
  552. {
  553. for (int i = 0; i < info.papers.Count; i++)
  554. {// 每一個科目的試卷
  555. string rootName = "";
  556. //if (info.school == "SYSTEM_NO_SCHOOL")
  557. if (info.scope == "private")
  558. {// 未入校老師的評量
  559. rootName = info.creatorId;
  560. }
  561. else
  562. {// 如果有學校代碼
  563. rootName = info.school;
  564. }
  565. if (_azureStorage.GetBlobContainerClient(rootName).GetBlobClient($"{info.papers[i].blob}/index.json").Exists())
  566. {// 如果試卷的blob存在,再開始
  567. BlobDownloadResult paperblobDownload = await _azureStorage.GetBlobContainerClient(rootName).GetBlobClient($"{info.papers[i].blob}/index.json").DownloadContentAsync();
  568. PaperIndex paperIndex = paperblobDownload.Content.ToObjectFromJson<PaperIndex>();
  569. List<LearnRecordItem> learnRecordItems = new();
  570. StringBuilder sbsql = new StringBuilder($" SELECT * FROM c WHERE c.examId = '{info.id}' and c.pk = 'ExamClassResult' and c.subjectId = '{info.subjects[i].id}' ");
  571. #region === 開始拼裝資料 ===
  572. if (info.classes.Count > 0 || info.stuLists.Count > 0)
  573. {
  574. // 組合SQL
  575. if (info.classes.Count > 0)
  576. {// 按照classes取ans.json
  577. sbsql.Append($" and ARRAY_CONTAINS({System.Text.Json.JsonSerializer.Serialize(info.classes)}, c.info.id)");
  578. }
  579. else if (info.stuLists.Count > 0)
  580. {
  581. sbsql.Append($" and ARRAY_CONTAINS({System.Text.Json.JsonSerializer.Serialize(info.stuLists)}, c.info.id)");
  582. }
  583. // 取學生答案及學生名單
  584. var client = _azureCosmos.GetCosmosClient();
  585. Dictionary<string, List<string>> stuDic = new Dictionary<string, List<string>>();
  586. if (!string.IsNullOrWhiteSpace(info.school) && !stuDic.ContainsKey(info.school))
  587. {
  588. stuDic.Add(info.school, new List<string>());
  589. }
  590. List<StudentAnswers> studentAnswersList = new List<StudentAnswers>();
  591. List<string> stuListForSql = new List<string>();
  592. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Common).GetItemQueryIterator<StudentAnswers>(queryText: sbsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{rootName}") }))
  593. {
  594. studentAnswersList.Add(item);
  595. stuListForSql = stuListForSql.Union(item.studentIds).ToList();
  596. }
  597. //取得學校的學生名單
  598. List<string> stuOpenIdList = new List<string>();
  599. if(!string.IsNullOrWhiteSpace(info.school))
  600. {
  601. StringBuilder stusql = new StringBuilder($"SELECT VALUE c.id FROM c WHERE c.pk = 'Base' AND ARRAY_CONTAINS({System.Text.Json.JsonSerializer.Serialize(stuListForSql)}, c.id)");
  602. await foreach (string item in client.GetContainer(Constant.TEAMModelOS, Constant.Student).GetItemQueryIterator<string>(queryText: stusql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{info.school}") }))
  603. {
  604. stuDic[info.school].Add(item);
  605. }
  606. }
  607. // 按照取出的學生答案blob 對答案 組合資料
  608. foreach (var studentAnswers in studentAnswersList)
  609. {// 每一個班級
  610. foreach (var studentAnswersBlob in studentAnswers.studentAnswers)
  611. {// 每一個學生
  612. if (studentAnswersBlob.Count > 0)
  613. {// 有學生的答案才開始
  614. if (_azureStorage.GetBlobContainerClient(rootName).GetBlobClient($"/exam/{studentAnswersBlob[0]}").Exists())
  615. {// 如果blob存在才開始
  616. BlobDownloadResult ansblobDownload = await _azureStorage.GetBlobContainerClient(rootName).GetBlobClient($"/exam/{studentAnswersBlob[0]}").DownloadContentAsync();
  617. List<List<string>> ansList = JsonConvert.DeserializeObject<List<List<string>>>(ansblobDownload.Content.ToString());
  618. // 從blob路徑取出學生id
  619. string[] arr = studentAnswersBlob[0].Split('/');
  620. string stuid = arr[arr.Length - 2];
  621. #region ===StartExam 開始課堂===
  622. LearnRecordItem LRItem_StartExam = new();
  623. LRItem_StartExam.verb = "StartExam";
  624. LRItem_StartExam.actor = getStuId(info.school, stuid, stuDic);
  625. LRItem_StartExam.time = info.createTime;
  626. LRItem_StartExam.ID = info.id;
  627. LRItem_StartExam.Desc = info.name;
  628. LRItem_StartExam.Correct = null;
  629. LRItem_StartExam.Choices = null;
  630. LRItem_StartExam.ExamQuesQty = info.papers[i].point.Count;
  631. LRItem_StartExam.TotalScore = 0;
  632. foreach (var pointItem in info.papers[i].point)
  633. {
  634. LRItem_StartExam.TotalScore = LRItem_StartExam.TotalScore + pointItem;
  635. }
  636. LRItem_StartExam.Success = null;
  637. learnRecordItems.Add(LRItem_StartExam);
  638. #endregion
  639. #region ===評量題目===
  640. for (int j = 0; j < ansList.Count; j++)
  641. {
  642. #region === 判斷題型 ===
  643. // 這五種題型才記錄
  644. if (paperIndex.slides[j].type == "single" ||
  645. paperIndex.slides[j].type == "multiple" ||
  646. paperIndex.slides[j].type == "judge" ||
  647. paperIndex.slides[j].type == "complete" ||
  648. paperIndex.slides[j].type == "subjective")
  649. {
  650. LearnRecordItem learnRecordItem = new();
  651. // 單選
  652. if (paperIndex.slides[j].type == "single") { learnRecordItem.verb = "AnsSingle"; }
  653. // 複選
  654. if (paperIndex.slides[j].type == "multiple") { learnRecordItem.verb = "AnsMultiple"; }
  655. // 是非
  656. if (paperIndex.slides[j].type == "judge") { learnRecordItem.verb = "AnsJudge"; }
  657. // 填充
  658. if (paperIndex.slides[j].type == "complete") { learnRecordItem.verb = "AnsComplete"; }
  659. // 問答
  660. if (paperIndex.slides[j].type == "subjective") { learnRecordItem.verb = "AnsSubjective"; }
  661. learnRecordItem.actor = getStuId(info.school, stuid, stuDic);
  662. learnRecordItem.time = data.endTime;
  663. string[] arrurlsingle = paperIndex.slides[j].url.Split('.');
  664. learnRecordItem.ID = arrurlsingle[0];
  665. #region === 設定Correct Choices Desc===
  666. if (_azureStorage.GetBlobContainerClient(rootName).GetBlobClient($"{info.papers[i].blob}/{paperIndex.slides[j].url}").Exists())
  667. {
  668. BlobDownloadResult itemblobDownload = await _azureStorage.GetBlobContainerClient(rootName).GetBlobClient($"{info.papers[i].blob}/{paperIndex.slides[j].url}").DownloadContentAsync();
  669. QuestionData questionData = itemblobDownload.Content.ToObjectFromJson<QuestionData>();
  670. setCorrectChoices(questionData, learnRecordItem);
  671. // 使用HtmlAgilityPack解析HTML
  672. HtmlDocument doc = new HtmlDocument();
  673. doc.LoadHtml(questionData.item[0].question);
  674. // 先刪除所有<img>標籤
  675. foreach (var imgNode in doc.DocumentNode.Descendants("img").ToArray())
  676. {
  677. imgNode.Remove();
  678. }
  679. // 再取純文字
  680. learnRecordItem.Desc = doc.DocumentNode.InnerText;
  681. }
  682. #endregion
  683. learnRecordItem.ExamQuesQty = null;
  684. learnRecordItem.TotalScore = null;
  685. learnRecordItem.Points = paperIndex.slides[j].scoring == null ? new List<string>() : paperIndex.slides[j].scoring.knowledge;
  686. //比對答案
  687. learnRecordItem.Success = paperIndex.slides[j].scoring == null ? null : (paperIndex.slides[j].scoring.ans.SequenceEqual(ansList[j]) ? true : false);
  688. learnRecordItems.Add(learnRecordItem);
  689. }
  690. #endregion
  691. }
  692. #endregion
  693. #region ===EndExam 結束課堂===
  694. LearnRecordItem LRItem_EndExam = new();
  695. LRItem_EndExam.verb = "EndExam";
  696. LRItem_EndExam.actor = getStuId(info.school, stuid, stuDic);
  697. LRItem_EndExam.time = info.endTime;
  698. LRItem_EndExam.ID = info.id;
  699. LRItem_EndExam.Desc = info.name;
  700. LRItem_EndExam.Correct = null;
  701. LRItem_EndExam.Choices = null;
  702. LRItem_EndExam.ExamQuesQty = info.papers[i].point.Count;
  703. LRItem_EndExam.TotalScore = 0;
  704. foreach (var pointItem in info.papers[i].point)
  705. {
  706. LRItem_EndExam.TotalScore = LRItem_EndExam.TotalScore + pointItem;
  707. }
  708. LRItem_EndExam.Success = null;
  709. learnRecordItems.Add(LRItem_EndExam);
  710. #endregion
  711. }
  712. }
  713. }
  714. }
  715. }
  716. #endregion
  717. if (learnRecordItems.Count > 0)
  718. {
  719. #region 寫入blob
  720. // 容器名称
  721. string containerName = "twmoeld";
  722. // 新文件的名称
  723. string blobName = $"/{DateTime.Now.ToString("yyyyMMdd")}/{info.id}.json";
  724. // 要上传的文件内容
  725. string fileContent = Newtonsoft.Json.JsonConvert.SerializeObject(learnRecordItems);
  726. // 获取容器引用
  727. BlobContainerClient containerClient = _azureStorage.GetBlobContainerClient(containerName);
  728. // 获取 Blob 客户端
  729. BlobClient blobClient = containerClient.GetBlobClient(blobName);
  730. // 将文件内容上传到 Blob
  731. using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(fileContent)))
  732. {
  733. await blobClient.UploadAsync(stream, true);
  734. }
  735. #endregion
  736. }
  737. }
  738. }
  739. }
  740. }
  741. catch (Exception ex)
  742. {
  743. }
  744. }
  745. /// <summary>
  746. /// 取得學習紀錄的actor
  747. /// </summary>
  748. /// <param name="learnRecordItem"></param>
  749. /// <param name="school"></param>
  750. /// <param name="stuid"></param>
  751. /// <returns></returns>
  752. private static string getStuId(string school, string stuid, Dictionary<string, List<string>> stuDic)
  753. {
  754. if (!string.IsNullOrWhiteSpace(school) && stuDic.ContainsKey(school) && stuDic[school].Contains(stuid))
  755. {// 校內帳號用組合的 "Base-hbgl,473891247381"
  756. return $"Base-{school.Trim()},{stuid}";
  757. }
  758. else
  759. {// 未入校老師的評量
  760. return stuid;
  761. }
  762. }
  763. private static void setCorrectChoices(QuestionData questionData, LearnRecordItem learnRecordItem)
  764. {
  765. #region === Correct Choices ===
  766. #region === 是非題邏輯 ===
  767. if (questionData.exercise.type == "judge" && questionData.exercise.answer.Count > 0)
  768. {// 如果是是非題 正確答案要用true false的方式設定
  769. if (questionData.exercise.answer[0] == "A")
  770. {
  771. learnRecordItem.Correct = new string[] { "true" };
  772. }
  773. else
  774. {
  775. learnRecordItem.Correct = new string[] { "false" };
  776. }
  777. }
  778. else
  779. {// 防呆 去html標籤
  780. if (questionData.exercise.answer.Count > 0)
  781. {
  782. List<string> anslist = new();
  783. foreach (var answer in questionData.exercise.answer)
  784. {
  785. // 使用HtmlAgilityPack解析HTML
  786. HtmlDocument doc = new HtmlDocument();
  787. doc.LoadHtml(answer);
  788. // 再取純文字
  789. anslist.Add(doc.DocumentNode.InnerText);
  790. }
  791. learnRecordItem.Correct = anslist;
  792. }
  793. else
  794. {
  795. learnRecordItem.Correct = questionData.exercise.answer;
  796. }
  797. }
  798. #endregion
  799. if (questionData.item[0].option.Count > 0)
  800. {// 如果有選項資料 記錄起來
  801. foreach (var option in questionData.item[0].option)
  802. {
  803. ChoicesItem item = new();
  804. item.id = option.code;
  805. if (questionData.exercise.type == "judge")
  806. {// 如果是是非題 固定選項
  807. if (option.code == "A")
  808. {
  809. item.description.zhTW = "是";
  810. }
  811. else
  812. {
  813. item.description.zhTW = "否";
  814. }
  815. }
  816. else
  817. {
  818. if (string.IsNullOrWhiteSpace(option.value))
  819. {
  820. item.description.zhTW = $"選項{option.code}";
  821. }
  822. else
  823. {
  824. // 使用HtmlAgilityPack解析HTML
  825. HtmlDocument doc = new HtmlDocument();
  826. doc.LoadHtml(option.value);
  827. // 再取純文字
  828. item.description.zhTW = doc.DocumentNode.InnerText;
  829. }
  830. }
  831. learnRecordItem.Choices.Add(item);
  832. }
  833. }
  834. #endregion
  835. }
  836. public static async Task resultStatus(CosmosClient client, List<ExamClassResult> examClassResults)
  837. {
  838. List<Task<ItemResponse<ExamClassResult>>> tasks = new();
  839. //结算单科单班的标准差和平均分
  840. foreach (ExamClassResult classResult in examClassResults)
  841. {
  842. //标记单科单班总得分
  843. double subScore = 0;
  844. //标准差
  845. double sPowSum = 0;
  846. List<double> newSumScore = new List<double>();
  847. List<double> effectiveScore = new List<double>();
  848. int lostStu = classResult.status.Where(c => c == 1).ToList().Count;
  849. var scount = classResult.studentIds.Count - lostStu;
  850. int index = 0;
  851. if (classResult.status.Count > 0)
  852. {
  853. foreach (var sta in classResult.status)
  854. {
  855. if (sta == 1)
  856. {
  857. for (int i = 0; i < classResult.studentScores[index].Count; i++)
  858. {
  859. if (classResult.studentScores[index][i] == -1)
  860. {
  861. classResult.studentScores[index][i] = 0;
  862. }
  863. }
  864. }
  865. else if (sta == 0)
  866. {
  867. //var ans = classResult.studentAnswers[index];
  868. //该学生缺考,历史数据的判定
  869. //if (ans.Count == 0)
  870. //{
  871. for (int i = 0; i < classResult.studentScores[index].Count; i++)
  872. {
  873. if (classResult.studentScores[index][i] == -1)
  874. {
  875. classResult.studentScores[index][i] = 0;
  876. }
  877. }
  878. /*if (ans.Count == 0)
  879. {
  880. classResult.status[index] = 1;
  881. } */
  882. //}
  883. }
  884. index++;
  885. }
  886. }
  887. else
  888. {
  889. List<int> sta = new();
  890. foreach (var id in classResult.studentIds)
  891. {
  892. sta.Add(0);
  893. }
  894. classResult.status = sta;
  895. foreach (var ans in classResult.studentAnswers)
  896. {
  897. //该学生缺考,历史数据的判定
  898. if (ans.Count == 0)
  899. {
  900. for (int i = 0; i < classResult.studentScores[index].Count; i++)
  901. {
  902. if (classResult.studentScores[index][i] == -1)
  903. {
  904. classResult.studentScores[index][i] = 0;
  905. }
  906. }
  907. classResult.status[index] = 1;
  908. }
  909. index++;
  910. }
  911. }
  912. int sIndex = 0;
  913. foreach (List<double> sc in classResult.studentScores)
  914. {
  915. List<double> newSc = new List<double>();
  916. foreach (double ssc in sc)
  917. {
  918. if (ssc == -1)
  919. {
  920. newSc.Add(0);
  921. }
  922. else
  923. {
  924. newSc.Add(ssc);
  925. }
  926. }
  927. double nc = Math.Round(newSc.Sum(), 2);
  928. if (classResult.status[sIndex] == 0)
  929. {
  930. effectiveScore.Add(nc);
  931. };
  932. newSumScore.Add(nc);
  933. subScore += nc;
  934. classResult.sum[sIndex] = nc;
  935. sIndex++;
  936. }
  937. double rateScore = scount > 0 ? Math.Round(subScore * 1.0 / scount, 2) : 0;
  938. //有效分数
  939. foreach (double scs in effectiveScore)
  940. {
  941. sPowSum += Math.Pow(scs - rateScore, 2);
  942. }
  943. classResult.standard = Math.Round(scount > 0 ? Math.Pow(sPowSum / scount, 0.5) : 0, 2);
  944. classResult.average = scount > 0 ? Math.Round(subScore / scount, 2) : 0;
  945. classResult.progress = true;
  946. tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new PartitionKey($"{classResult.code}")));
  947. }
  948. await Task.WhenAll(tasks);
  949. }
  950. public static async Task<Settlement> getMore(CosmosClient client, ExamInfo info)
  951. {
  952. //计算单次考试简易统计信息
  953. Settlement settlement = new();
  954. List<ExamResult> examResults = new();
  955. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamResult>(
  956. queryText: $"select value(c) from c where c.examId = '{info.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}") }))
  957. {
  958. examResults.Add(item);
  959. }
  960. if (examResults.Count > 0)
  961. {
  962. //记录某次考试所有学生得分总分
  963. double score = 0;
  964. double allScore = 0;
  965. int stuCount = 0;
  966. //标准差
  967. double powSum = 0;
  968. List<string> losStu = new List<string>();
  969. //当前完成考试得人数
  970. int total = examResults[0].studentIds.Distinct().Count();
  971. //先与第一个值取并集
  972. losStu = losStu.Union(examResults[0].lostStus).ToList();
  973. foreach (ExamResult examResult in examResults)
  974. {
  975. //取交集
  976. losStu = losStu.Intersect(examResult.lostStus).ToList();
  977. }
  978. //处理缺考的学生
  979. List<string> stus = examResults[0].studentIds.Except(losStu).ToList();
  980. foreach (ExamResult examResult in examResults)
  981. {
  982. foreach (var id in stus)
  983. {
  984. int index = examResult.studentIds.IndexOf(id);
  985. score += examResult.studentScores[index].Sum();
  986. }
  987. }
  988. stuCount = total - losStu.Count;
  989. double NewsRateScore = stuCount > 0 ? Math.Round(score * 1.0 / stuCount, 2) : 0;
  990. foreach (PaperSimple simple in info.papers)
  991. {
  992. allScore += simple.point.Sum();
  993. }
  994. //计算全科标准差
  995. foreach (string id in stus)
  996. {
  997. double sc = 0;
  998. foreach (ExamResult result in examResults)
  999. {
  1000. if (result.studentScores.Count > 0)
  1001. {
  1002. sc += result.studentScores[result.studentIds.IndexOf(id)].Sum();
  1003. }
  1004. }
  1005. powSum += Math.Pow(sc - NewsRateScore, 2);
  1006. }
  1007. info.standard = Math.Round(total - losStu.Count > 0 ? Math.Pow(powSum / (total - losStu.Count), 0.5) : 0, 2);
  1008. double NewsRate = allScore > 0 ? Math.Round(NewsRateScore / allScore * 100, 2) : 0;
  1009. double qrate = Math.Round(total > 0 ? losStu.Count * 1.0 / total * 100 : 0, 2);
  1010. settlement.rate = NewsRate;
  1011. settlement.score = NewsRateScore;
  1012. settlement.stus = losStu;
  1013. settlement.total = total;
  1014. settlement.qrate = qrate;
  1015. }
  1016. return settlement;
  1017. }
  1018. //处理全部学生选题计数
  1019. public static async Task examRecordCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, ExamResult er, List<ExamClassResult> classResults, AzureCosmosFactory _azureCosmos)
  1020. {
  1021. try
  1022. {
  1023. List<double> scores = new List<double>();
  1024. foreach (List<double> sc in er.studentScores)
  1025. {
  1026. scores.Add(sc.Sum());
  1027. }
  1028. //确定高分组 最低分数
  1029. //var srowallorder = scores.EnumerateIndexed().OrderByDescending(g => g.Item2); //各生總分排序
  1030. //var srowallorder = scores.OrderByDescending(g => g);
  1031. double[] point = StringHelper.ListTodouble(er.paper.point);
  1032. double[,] result = StringHelper.ListToDouble(er.studentScores);
  1033. var cdm = new ClouDASMatrix(result, point);
  1034. scores.Sort((s1, s2) => { return s2.CompareTo(s1); });
  1035. int rhwCount = cdm.SH.Count();
  1036. double rhw = cdm.SH.LastOrDefault().Item2;
  1037. int rhlCount = cdm.SL.Count();
  1038. double rhl = cdm.SL.FirstOrDefault().Item2;
  1039. List<string> phs = new();
  1040. List<string> pls = new();
  1041. //分别获取高分组低分组人员
  1042. foreach (var ph in cdm.SH)
  1043. {
  1044. phs.Add(er.studentIds[ph.Item1]);
  1045. }
  1046. foreach (var pl in cdm.SL)
  1047. {
  1048. pls.Add(er.studentIds[pl.Item1]);
  1049. }
  1050. /* if (scores.Count > 3)
  1051. {
  1052. rhwCount = Convert.ToInt32(Math.Floor(scores.Count * 0.27));
  1053. rhw = rhwCount > 0 ? scores[rhwCount - 1] : 0;
  1054. rhlCount = Convert.ToInt32(Math.Ceiling(scores.Count * 0.73));
  1055. rhl = rhlCount > 0 ? scores[rhlCount] : 0;
  1056. }
  1057. else
  1058. {
  1059. rhwCount = Convert.ToInt32(Math.Floor(scores.Count * 0.27));
  1060. rhw = rhwCount > 0 ? scores[rhwCount] : 0;
  1061. rhlCount = Convert.ToInt32(Math.Ceiling(scores.Count * 0.73));
  1062. rhl = rhlCount > 0 ? scores[rhlCount - 1] : 0;
  1063. }*/
  1064. /*int rhwCount = Convert.ToInt32(Math.Floor(scores.Count * 0.27));
  1065. double rhw = rhwCount > 0 ? scores[rhwCount-1] : 0;
  1066. //var rhww = srowallorder.Take(Convert.ToInt32(Math.Floor(scores.Count * 0.27)));
  1067. //确定低分组 最高分数
  1068. //scores.Sort((s1, s2) => { return s1.CompareTo(s2); });
  1069. int rhlCount = Convert.ToInt32(Math.Ceiling(scores.Count * 0.73));
  1070. double rhl = rhlCount > 0 ? scores[rhlCount-1] : 0;*/
  1071. //var rhll = srowallorder.Skip(Convert.ToInt32(Math.Ceiling(scores.Count * 0.73)));
  1072. //存放高分组学生ID
  1073. List<string> phId = new();
  1074. List<string> plId = new();
  1075. List<List<List<string>>> opth = new();
  1076. List<List<List<string>>> optl = new();
  1077. List<double> akp = await knowledgeCount(info, subject, _dingDing, no, classResults, rhwCount, rhw, rhlCount, rhl, _azureCosmos);
  1078. List<double> afp = await fieldCount(info, subject, _dingDing, no, classResults, rhwCount, rhw, rhlCount, rhl, _azureCosmos);
  1079. int PHCount = 0;
  1080. int PLCount = 0;
  1081. foreach (ExamClassResult classResult in classResults)
  1082. {
  1083. if (classResult.subjectId.Equals(subject.id))
  1084. {
  1085. foreach (string id in classResult.studentIds)
  1086. {
  1087. int index = classResult.studentIds.IndexOf(id);
  1088. if (classResult.studentScores.Count > 0)
  1089. {
  1090. if (phs.Contains(id))
  1091. {
  1092. if (classResult.ans.Count > 0)
  1093. {
  1094. opth.Add(classResult.ans[index]);
  1095. PHCount++;
  1096. continue;
  1097. }
  1098. }
  1099. if (pls.Contains(id))
  1100. {
  1101. if (classResult.ans.Count > 0)
  1102. {
  1103. optl.Add(classResult.ans[index]);
  1104. PLCount++;
  1105. continue;
  1106. }
  1107. }
  1108. }
  1109. }
  1110. }
  1111. }
  1112. er.phc = getMore(info, no, opth);
  1113. er.plc = getMore(info, no, optl);
  1114. er.afp = afp;
  1115. er.akp = akp;
  1116. }
  1117. catch (Exception ex)
  1118. {
  1119. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测作答记录结算异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1120. }
  1121. }
  1122. public static async Task<List<RGroupList>> Activity(CoreAPIHttpService _coreAPIHttpService, ExamInfo info, List<string> classes, CosmosClient client, DingDing _dingDing, List<string> sub, List<ExamClassResult> results)
  1123. {
  1124. List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
  1125. if (info.groupLists.Count > 0)
  1126. {
  1127. var group = info.groupLists;
  1128. foreach (var gp in group)
  1129. {
  1130. foreach (KeyValuePair<string, List<string>> pp in gp)
  1131. {
  1132. ps.Add((pp.Key, pp.Value));
  1133. }
  1134. }
  1135. }
  1136. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, classes, info.school, ps);
  1137. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  1138. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  1139. List<StuActivity> stuActivities = new List<StuActivity>();
  1140. List<StuActivity> tmdActivities = new List<StuActivity>();
  1141. var papers = info.papers.GroupBy(c => c.subjectId).Select(x => new
  1142. {
  1143. subject = x.Key,
  1144. blob = x.ToList().Select(z => z.blob).ToList()
  1145. });
  1146. bool flag = info.papers.Exists(c => c.subjectId != null);
  1147. if (addTmdidsCls.IsNotEmpty())
  1148. {
  1149. addTmdidsCls.ForEach(x =>
  1150. {
  1151. HashSet<string> classIds = new HashSet<string>();
  1152. classLists.ForEach(z =>
  1153. {
  1154. z.members.ForEach(y =>
  1155. {
  1156. if (y.id.Equals(x.id) && y.type == 1)
  1157. {
  1158. classIds.Add(z.id);
  1159. }
  1160. });
  1161. });
  1162. bool iss = false;
  1163. //标记学生作答状态
  1164. int ts = 0;
  1165. if (results.Count > 0)
  1166. {
  1167. foreach (ExamClassResult exam in results)
  1168. {
  1169. int index = exam.studentIds.IndexOf(x.id);
  1170. if (index != -1)
  1171. {
  1172. if (exam.studentAnswers[index].Count > 0)
  1173. {
  1174. bool flag = exam.studentScores[index].Exists(x => x == -1);
  1175. if (!flag)
  1176. {
  1177. ts = 1;
  1178. iss = true;
  1179. break;
  1180. }
  1181. else
  1182. {
  1183. ts = 0;
  1184. }
  1185. }
  1186. else
  1187. {
  1188. ts = -1;
  1189. }
  1190. }
  1191. }
  1192. }
  1193. else
  1194. {
  1195. ts = -1;
  1196. }
  1197. tmdActivities.Add(new StuActivity
  1198. {
  1199. pk = "Activity",
  1200. id = info.id,
  1201. code = $"Activity-{x.id}",
  1202. type = "Exam",
  1203. name = info.name,
  1204. source = info.source,
  1205. startTime = info.startTime,
  1206. endTime = info.endTime,
  1207. scode = info.code,
  1208. scope = info.scope,
  1209. school = info.school,
  1210. creatorId = info.creatorId,
  1211. subjects = sub,
  1212. blob = null,
  1213. paper = flag ? papers.Select(c => new
  1214. {
  1215. c.subject,
  1216. blob = c.blob[new Random().Next(c.blob.Count)]
  1217. }) : "",
  1218. owner = info.owner,
  1219. createTime = info.createTime,
  1220. taskStatus = ts,
  1221. qamode = info.qamode,
  1222. ext = new Dictionary<string, JsonElement>() { { "type", info.examType.ToJsonString().ToObject<JsonElement>() },
  1223. { "subjects", info.subjects.ToJsonString().ToObject<JsonElement>() } },
  1224. sStatus = iss ? 1 : 0,
  1225. classIds = classIds.ToList()
  1226. }); ;
  1227. });
  1228. }
  1229. if (addStudentsCls.IsNotEmpty())
  1230. {
  1231. addStudentsCls.ForEach(x =>
  1232. {
  1233. HashSet<string> classIds = new HashSet<string>();
  1234. classLists.ForEach(z =>
  1235. {
  1236. z.members.ForEach(y =>
  1237. {
  1238. if (y.id.Equals(x.id) && y.code.Equals(info.school) && y.type == 2)
  1239. {
  1240. classIds.Add(z.id);
  1241. }
  1242. });
  1243. });
  1244. bool iss = false;
  1245. //标记学生作答状态
  1246. int ts = 0;
  1247. if (results.Count > 0)
  1248. {
  1249. foreach (ExamClassResult exam in results)
  1250. {
  1251. int index = exam.studentIds.IndexOf(x.id);
  1252. if (index != -1)
  1253. {
  1254. if (exam.studentAnswers[index].Count > 0)
  1255. {
  1256. bool flag = exam.studentScores[index].Exists(x => x == -1);
  1257. if (!flag)
  1258. {
  1259. ts = 1;
  1260. iss = true;
  1261. break;
  1262. }
  1263. else
  1264. {
  1265. ts = 0;
  1266. }
  1267. }
  1268. else
  1269. {
  1270. ts = -1;
  1271. }
  1272. }
  1273. }
  1274. }
  1275. else
  1276. {
  1277. ts = -1;
  1278. }
  1279. stuActivities.Add(new StuActivity
  1280. {
  1281. pk = "Activity",
  1282. id = info.id,
  1283. code = $"Activity-{x.code.Replace("Base-", "")}-{x.id}",
  1284. type = "Exam",
  1285. name = info.name,
  1286. source = info.source,
  1287. startTime = info.startTime,
  1288. endTime = info.endTime,
  1289. scode = info.code,
  1290. scope = info.scope,
  1291. school = info.school,
  1292. creatorId = info.creatorId,
  1293. subjects = sub,
  1294. blob = null,
  1295. paper = flag ? papers.Select(c => new
  1296. {
  1297. c.subject,
  1298. blob = c.blob[new Random().Next(c.blob.Count)]
  1299. }) : "",
  1300. owner = info.owner,
  1301. classIds = classIds.ToList(),
  1302. createTime = info.createTime,
  1303. qamode = info.qamode,
  1304. ext = new Dictionary<string, JsonElement>() { { "type", info.examType.ToJsonString().ToObject<JsonElement>() },
  1305. { "subjects", info.subjects.ToJsonString().ToObject<JsonElement>() } },
  1306. taskStatus = ts,
  1307. sStatus = iss ? 1 : 0,
  1308. });
  1309. });
  1310. }
  1311. await IESActivityService.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities, null);
  1312. return classLists;
  1313. }
  1314. public static async Task<List<double>> knowledgeCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, List<ExamClassResult> classResults,
  1315. double rhwCount, double rhw, double rhlCount, double rhl, AzureCosmosFactory _azureCosmos)
  1316. {
  1317. List<double> akp = new();
  1318. try
  1319. {
  1320. int phcount = 0;
  1321. int plcount = 0;
  1322. //存放并去重知识点
  1323. HashSet<string> kname = new HashSet<string>();
  1324. if (info.papers[no].knowledge.Count > 0)
  1325. {
  1326. info.papers[no].knowledge.ForEach(kno =>
  1327. {
  1328. kno.ForEach(k =>
  1329. {
  1330. kname.Add(k);
  1331. });
  1332. });
  1333. List<string> knowledgeName = new List<string>();
  1334. foreach (string cla in kname)
  1335. {
  1336. knowledgeName.Add(cla);
  1337. }
  1338. for (int k = 0; k < knowledgeName.Count; k++)
  1339. {
  1340. if (null == knowledgeName[k])
  1341. {
  1342. knowledgeName.Remove(knowledgeName[k]);
  1343. }
  1344. }
  1345. foreach (ExamClassResult classResult in classResults)
  1346. {
  1347. if (classResult.subjectId.Equals(subject.id))
  1348. {
  1349. //List<int> phc = new List<int>();
  1350. List<int> ph = new List<int>();
  1351. List<int> pl = new List<int>();
  1352. List<int> pc = new List<int>();
  1353. List<double> persent = new List<double>();
  1354. int lostStu = classResult.status.Where(c => c == 1).ToList().Count;
  1355. for (int i = 0; i < knowledgeName.Count; i++)
  1356. {
  1357. //初始化单个知识点得分
  1358. double score = 0;
  1359. int n = 0;
  1360. int phCount = 0;
  1361. int plCount = 0;
  1362. int pCount = 0;
  1363. double classScore = 0;
  1364. foreach (List<string> str in info.papers[no].knowledge)
  1365. {
  1366. if (str.Contains(knowledgeName[i]))
  1367. {
  1368. var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
  1369. classScore += info.papers[no].point.Count > 0 ? (info.papers[no].point[n] * itemPersent) : 0;
  1370. foreach (string id in classResult.studentIds)
  1371. {
  1372. int index = classResult.studentIds.IndexOf(id);
  1373. if (classResult.studentScores.Count > 0)
  1374. {
  1375. if (classResult.studentScores[index].Count > 0)
  1376. {
  1377. double realScore = classResult.studentScores[index][n] == -1 ? 0 : classResult.studentScores[index][n] * itemPersent;
  1378. score += realScore;
  1379. //score += classResult.studentScores[index][n] == -1 ? 0 : classResult.studentScores[index][n] * itemPersent;
  1380. if (classResult.studentScores[index].Sum() >= rhw && phcount < rhwCount)
  1381. {
  1382. if (classResult.studentScores[index][n] <= 0)
  1383. {
  1384. phCount++;
  1385. }
  1386. phcount++;
  1387. continue;
  1388. }
  1389. if (classResult.studentScores[index].Sum() <= rhl && plcount < (info.stuCount - rhlCount))
  1390. {
  1391. if (classResult.studentScores[index][n] <= 0)
  1392. {
  1393. plCount++;
  1394. }
  1395. plcount++;
  1396. continue;
  1397. }
  1398. if (classResult.studentScores[index][n] <= 0)
  1399. {
  1400. pCount++;
  1401. }
  1402. }
  1403. }
  1404. }
  1405. }
  1406. n++;
  1407. }
  1408. pc.Add(pCount);
  1409. ph.Add(phCount);
  1410. pl.Add(plCount);
  1411. double per = classResult.studentIds.Count - lostStu > 0 ? Math.Round(score / (classResult.studentIds.Count - lostStu), 2) : 0;
  1412. persent.Add(classScore > 0 ? Math.Round(per * 1.0 / classScore, 2) : 0);
  1413. }
  1414. classResult.phc = ph;
  1415. classResult.plc = pl;
  1416. classResult.pc = pc;
  1417. classResult.krate = persent;
  1418. }
  1419. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new Azure.Cosmos.PartitionKey($"{classResult.code}"));
  1420. }
  1421. foreach (string k in knowledgeName)
  1422. {
  1423. double score = 0;
  1424. double allScore = 0;
  1425. int count = 0;
  1426. int m = 0;
  1427. foreach (List<string> str in info.papers[no].knowledge)
  1428. {
  1429. if (str.Contains(k))
  1430. {
  1431. var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
  1432. allScore += info.papers[no].point.Count > 0 ? info.papers[no].point[m] * itemPersent : 0;
  1433. }
  1434. m++;
  1435. }
  1436. foreach (ExamClassResult result in classResults)
  1437. {
  1438. if (result.subjectId.Equals(subject.id))
  1439. {
  1440. int n = 0;
  1441. foreach (List<string> str in info.papers[no].knowledge)
  1442. {
  1443. if (str.Contains(k))
  1444. {
  1445. var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
  1446. if (result.studentScores.Count > 0)
  1447. {
  1448. foreach (List<double> sc in result.studentScores)
  1449. {
  1450. double tsc = sc[n] == -1 ? 0 : sc[n];
  1451. score += (tsc * itemPersent);
  1452. }
  1453. }
  1454. }
  1455. n++;
  1456. }
  1457. count += result.studentIds.Count;
  1458. }
  1459. }
  1460. double per = count - info.lostStu.Count > 0 ? Math.Round(score / (count - info.lostStu.Count), 2) : 0;
  1461. akp.Add(allScore > 0 ? Math.Round(per / allScore, 2) : 0);
  1462. }
  1463. }
  1464. return akp;
  1465. }
  1466. catch (Exception ex)
  1467. {
  1468. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测知识点结算异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1469. return null;
  1470. }
  1471. }
  1472. public static async Task<List<double>> fieldCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, List<ExamClassResult> classResults,
  1473. double rhwCount, double rhw, double rhlCount, double rhl, AzureCosmosFactory _azureCosmos)
  1474. {
  1475. List<double> afp = new();
  1476. try
  1477. {
  1478. int phcount = 0;
  1479. int plcount = 0;
  1480. //存放并去重知识点
  1481. List<int> knowledgeName = new List<int>() { 1, 2, 3, 4, 5, 6 };
  1482. /* knowledgeName.Add(1);
  1483. knowledgeName.Add(2);
  1484. knowledgeName.Add(3);
  1485. knowledgeName.Add(4);
  1486. knowledgeName.Add(5);
  1487. knowledgeName.Add(6);*/
  1488. foreach (ExamClassResult classResult in classResults)
  1489. {
  1490. if (classResult.subjectId.Equals(subject.id))
  1491. {
  1492. //List<int> phc = new List<int>();
  1493. List<int> ph = new List<int>();
  1494. List<int> pl = new List<int>();
  1495. List<int> pc = new List<int>();
  1496. List<double> persent = new List<double>();
  1497. int lostStu = classResult.status.Where(c => c == 1).ToList().Count;
  1498. for (int i = 0; i < knowledgeName.Count; i++)
  1499. {
  1500. //初始化单个知识点得分
  1501. double score = 0;
  1502. int n = 0;
  1503. int phCount = 0;
  1504. int plCount = 0;
  1505. int pCount = 0;
  1506. double classScore = 0;
  1507. if (info.papers[no].field.Count > 0)
  1508. {
  1509. foreach (int str in info.papers[no].field)
  1510. {
  1511. if (str == knowledgeName[i])
  1512. {
  1513. var itemPersent = 1;
  1514. classScore += info.papers[no].point.Count > 0 ? info.papers[no].point[n] * itemPersent : 0;
  1515. foreach (string id in classResult.studentIds)
  1516. {
  1517. int index = classResult.studentIds.IndexOf(id);
  1518. if (classResult.studentScores.Count > 0)
  1519. {
  1520. if (classResult.studentScores[index].Count > 0)
  1521. {
  1522. score += classResult.studentScores[index][n] == -1 ? 0 : classResult.studentScores[index][n];
  1523. if (classResult.studentScores[index].Sum() >= rhw && phcount < rhwCount)
  1524. {
  1525. if (classResult.studentScores[index][n] <= 0)
  1526. {
  1527. phCount++;
  1528. }
  1529. phcount++;
  1530. continue;
  1531. }
  1532. if (classResult.studentScores[index].Sum() <= rhl && plcount < (info.stuCount - rhlCount))
  1533. {
  1534. if (classResult.studentScores[index][n] <= 0)
  1535. {
  1536. plCount++;
  1537. }
  1538. plcount++;
  1539. continue;
  1540. }
  1541. if (classResult.studentScores[index][n] <= 0)
  1542. {
  1543. pCount++;
  1544. }
  1545. }
  1546. }
  1547. }
  1548. }
  1549. n++;
  1550. }
  1551. pc.Add(pCount);
  1552. ph.Add(phCount);
  1553. pl.Add(plCount);
  1554. double per = classResult.studentIds.Count - lostStu > 0 ? Math.Round(score / (classResult.studentIds.Count - lostStu), 2) : 0;
  1555. persent.Add(classScore > 0 ? Math.Round(per / classScore, 2) : 0);
  1556. }
  1557. }
  1558. classResult.fphc = ph;
  1559. classResult.fplc = pl;
  1560. classResult.fpc = pc;
  1561. classResult.frate = persent;
  1562. }
  1563. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new Azure.Cosmos.PartitionKey($"{classResult.code}"));
  1564. }
  1565. for (int i = 0; i < knowledgeName.Count; i++)
  1566. {
  1567. double score = 0;
  1568. double allScore = 0;
  1569. int count = 0;
  1570. int m = 0;
  1571. foreach (int str in info.papers[no].field)
  1572. {
  1573. if (str == knowledgeName[i])
  1574. {
  1575. var itemPersent = 1;
  1576. allScore += info.papers[no].point.Count > 0 ? info.papers[no].point[m] * itemPersent : 0;
  1577. }
  1578. m++;
  1579. }
  1580. foreach (ExamClassResult result in classResults)
  1581. {
  1582. if (result.subjectId.Equals(subject.id))
  1583. {
  1584. int n = 0;
  1585. foreach (int str in info.papers[no].field)
  1586. {
  1587. var itemPersent = 1;
  1588. if (str == knowledgeName[i])
  1589. {
  1590. if (result.studentScores.Count > 0)
  1591. {
  1592. foreach (List<double> sc in result.studentScores)
  1593. {
  1594. double tsc = sc[n] == -1 ? 0 : sc[n];
  1595. score += tsc * itemPersent;
  1596. }
  1597. }
  1598. }
  1599. n++;
  1600. }
  1601. count += result.studentIds.Count;
  1602. }
  1603. }
  1604. double per = count - info.lostStu.Count > 0 ? Math.Round(score / (count - info.lostStu.Count), 2) : 0;
  1605. afp.Add(allScore > 0 ? Math.Round(per / allScore, 2) : 0);
  1606. }
  1607. return afp;
  1608. }
  1609. catch (Exception ex)
  1610. {
  1611. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测认知层次结算异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1612. return null;
  1613. }
  1614. }
  1615. //处理选题计数
  1616. public static List<Dictionary<string, int>> getMore(ExamInfo info, int no, List<List<List<string>>> list)
  1617. {
  1618. List<Dictionary<string, int>> recorde = new List<Dictionary<string, int>>();
  1619. try
  1620. {
  1621. for (int i = 0; i < info.papers[no].answers.Count; i++)
  1622. {
  1623. if (info.papers[no].answers[i].Count <= 0)
  1624. {
  1625. recorde.Add(new Dictionary<string, int>());
  1626. continue;
  1627. }
  1628. Dictionary<string, int> optCount = new Dictionary<string, int>();
  1629. foreach (List<List<string>> stu in list)
  1630. {
  1631. if (stu.Count == info.papers[no].answers.Count)
  1632. {
  1633. var item = stu[i];
  1634. foreach (string opt in item)
  1635. {
  1636. if (optCount.ContainsKey(opt))
  1637. {
  1638. optCount[opt] = optCount[opt] + 1;
  1639. }
  1640. else
  1641. {
  1642. optCount[opt] = 1;
  1643. }
  1644. }
  1645. }
  1646. }
  1647. recorde.Add(optCount);
  1648. }
  1649. return recorde;
  1650. }
  1651. catch (Exception)
  1652. {
  1653. return recorde;
  1654. }
  1655. }
  1656. public static async Task createClassResultAsync(ExamInfo info, List<ExamClassResult> examClassResults, ExamSubject subject, int no, AzureCosmosFactory _azureCosmos, DingDing _dingDing, AzureStorageFactory _azureStorage, IHttpClientFactory _httpClient, IConfiguration _configuration)
  1657. {
  1658. //保证试卷信息与科目信息同步
  1659. ExamResult result = new ExamResult();
  1660. //人数总和
  1661. int Count = 0;
  1662. int m = 0;
  1663. double score = 0;
  1664. //标准差
  1665. //double powSum = 0;
  1666. double allScore = info.papers[no].point.Sum();
  1667. List<ClassRange> classRanges = new List<ClassRange>();
  1668. List<string> lostStu = new List<string>();
  1669. List<double> csRate = new List<double>();
  1670. List<List<List<string>>> opt = new List<List<List<string>>>();
  1671. //List<Task<ItemResponse<ExamClassResult>>> tasks = new();
  1672. foreach (ExamClassResult classResult in examClassResults)
  1673. {
  1674. double classSrate = 0;
  1675. if (classResult.subjectId.Equals(subject.id))
  1676. {
  1677. foreach (List<List<string>> op in classResult.ans)
  1678. {
  1679. opt.Add(op);
  1680. }
  1681. //记录缺考学生索引位置
  1682. int index_stu = 0;
  1683. foreach (var ans in classResult.studentAnswers)
  1684. {
  1685. if (ans.Count == 0)
  1686. {
  1687. if (!lostStu.Contains(classResult.studentIds[index_stu]))
  1688. {
  1689. lostStu.Add(classResult.studentIds[index_stu]);
  1690. }
  1691. }
  1692. else
  1693. {
  1694. if (classResult.status[index_stu] == 1)
  1695. {
  1696. if (!lostStu.Contains(classResult.studentIds[index_stu]))
  1697. {
  1698. lostStu.Add(classResult.studentIds[index_stu]);
  1699. }
  1700. }
  1701. }
  1702. index_stu++;
  1703. }
  1704. int index = 0;
  1705. foreach (List<double> scores in classResult.studentScores)
  1706. {
  1707. List<double> newScores = new List<double>();
  1708. //int count = 0;
  1709. if (scores.Count > 0)
  1710. {
  1711. foreach (double sc in scores)
  1712. {
  1713. newScores.Add(sc > -1 ? sc : 0);
  1714. }
  1715. }
  1716. else
  1717. {
  1718. newScores.Add(0);
  1719. }
  1720. classSrate += newScores.Sum();
  1721. score += newScores.Sum();
  1722. result.studentScores.Add(newScores);
  1723. index++;
  1724. }
  1725. //处理班级信息
  1726. ClassRange range = new ClassRange();
  1727. range.id = classResult.info.id;
  1728. range.name = classResult.info.name;
  1729. range.gradeId = classResult.gradeId;
  1730. List<int> ran = new List<int>();
  1731. int stuCount = classResult.studentIds.Count;
  1732. //todo 与实际的缺考人数比较
  1733. int lostStus = classResult.status.Where(c => c == 1).ToList().Count;
  1734. Count += stuCount;
  1735. if (m == 0)
  1736. {
  1737. ran.Add(0);
  1738. ran.Add(stuCount - 1);
  1739. }
  1740. else
  1741. {
  1742. ran.Add(Count - stuCount);
  1743. ran.Add(Count - 1);
  1744. }
  1745. m++;
  1746. range.range = ran;
  1747. classRanges.Add(range);
  1748. //处理学生ID
  1749. foreach (string id in classResult.studentIds)
  1750. {
  1751. result.studentIds.Add(id);
  1752. }
  1753. if (allScore > 0)
  1754. {
  1755. csRate.Add(classResult.studentIds.Count - lostStus > 0 ? Math.Round(classSrate * 1.0 / (classResult.studentIds.Count - lostStus), 2) : 0 / allScore);
  1756. }
  1757. else
  1758. {
  1759. csRate.Add(0);
  1760. }
  1761. //powSum += Math.Pow(classSrate - result.average, 2);
  1762. //处理选项计数内容
  1763. }
  1764. //tasks.Add(_azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new PartitionKey($"{classResult.code}")));
  1765. }
  1766. //await tasks.TaskPage(10);
  1767. /*foreach (string id in result.lostStus) {
  1768. if (!examClassResults[0].studentIds.Contains(id)) {
  1769. int index = result.lostStus.IndexOf(id);
  1770. result.lostStus.RemoveAt(index);
  1771. }
  1772. }*/
  1773. //处理人员变更时被移除的人员
  1774. result.lostStus = lostStu;
  1775. List<string> stuIds = examClassResults.SelectMany(x => x.studentIds).ToList();
  1776. if (result.lostStus.Count > 0)
  1777. {
  1778. for (int i = 0; i < result.lostStus.Count; i++)
  1779. {
  1780. if (!stuIds.Contains(result.lostStus[i]))
  1781. {
  1782. result.lostStus.RemoveAt(i);
  1783. }
  1784. }
  1785. }
  1786. result.record = getMore(info, no, opt);
  1787. result.average = result.studentIds.Count - result.lostStus.Count > 0 ? Math.Round(score * 1.0 / (result.studentIds.Count - result.lostStus.Count), 2) : 0;
  1788. double powSum = 0;
  1789. //int sco = 0;
  1790. result.studentIds.ForEach(x =>
  1791. {
  1792. double sc = result.studentScores[result.studentIds.IndexOf(x)].Sum();
  1793. if (!result.lostStus.Contains(x))
  1794. {
  1795. powSum += Math.Pow(sc - result.average, 2);
  1796. }
  1797. });
  1798. result.standard = Math.Round((result.studentIds.Count - result.lostStus.Count) > 0 ? Math.Pow(powSum / (result.studentIds.Count - result.lostStus.Count), 0.5) : 0, 2);
  1799. result.csRate = csRate;
  1800. result.sRate = allScore > 0 ? Math.Round(result.average / allScore * 100, 2) : 0;
  1801. result.classes = classRanges;
  1802. result.code = "ExamResult-" + info.id;
  1803. result.school = info.school;
  1804. result.id = subject.id;
  1805. result.examId = info.id;
  1806. result.subjectId = subject.id;
  1807. result.year = info.year;
  1808. result.paper = info.papers[no];
  1809. //result.point = info.papers[j].point;
  1810. result.scope = info.scope;
  1811. result.name = info.name;
  1812. result.time = info.startTime;
  1813. if (info.qamode != 2) {
  1814. await examRecordCount(info, subject, _dingDing, no, result, examClassResults, _azureCosmos);
  1815. }
  1816. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").UpsertItemAsync(result, new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}"));
  1817. List<ErrorItems> errorItems = new();
  1818. string code = string.Empty;
  1819. string pk = string.Empty;
  1820. string table = "School";
  1821. if (info.scope.Equals("school"))
  1822. {
  1823. code = $"ErrorItems-{info.school}";
  1824. pk = $"Item-{info.school}";
  1825. }
  1826. else
  1827. {
  1828. code = "ErrorItems";
  1829. pk = $"Item-{info.creatorId}";
  1830. table = "Teacher";
  1831. }
  1832. 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}'"))})";
  1833. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Student").GetItemQueryIterator<ErrorItems>(queryText: sqlqueryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{code}") }))
  1834. {
  1835. errorItems.Add(item);
  1836. }
  1837. try {
  1838. /* bool isError = examClassResults.SelectMany(c => c.status).ToList().Exists(z => z == 1);
  1839. if () {
  1840. }*/
  1841. if (errorItems.Count == 0 && info.qamode != 2)
  1842. {
  1843. // 新增逻辑 收集错题内容
  1844. BlobDownloadResult index_json;
  1845. if (info.scope.Equals("school"))
  1846. {
  1847. index_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{info.papers[no].blob}/index.json").DownloadContentAsync();
  1848. }
  1849. else
  1850. {
  1851. index_json = await _azureStorage.GetBlobContainerClient($"{info.creatorId}").GetBlobClient($"{info.papers[no].blob}/index.json").DownloadContentAsync();
  1852. }
  1853. //BlobDownloadResult index_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{info.papers[no].blob}/index.json").DownloadContentAsync();
  1854. JsonElement RecordingJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(index_json.Content.ToString()))).RootElement;
  1855. RecordingJson.TryGetProperty("slides", out JsonElement slides);
  1856. var sdes = slides.ToObject<List<Slides>>();
  1857. List<string> attachments = new List<string>();
  1858. if (info.qamode == 1)
  1859. {
  1860. attachments = RecordingJson.GetProperty("attachments").ToObject<List<string>>();
  1861. if (attachments.Count == 0)
  1862. {
  1863. return;
  1864. }
  1865. }
  1866. List<string> urls = new();
  1867. foreach (var ne in sdes)
  1868. {
  1869. if (!ne.type.Equals("compose"))
  1870. {
  1871. urls.Add(ne.url);
  1872. }
  1873. }
  1874. // 获取整体的题目ID集合
  1875. List<string> ids = new();
  1876. List<(string id, string pid, int level, string type, List<string> knows)> itemInfos = new();
  1877. foreach (string url in urls)
  1878. {
  1879. string id = url.Replace(".json", "");
  1880. BlobDownloadResult index_item_json;
  1881. if (info.scope.Equals("school"))
  1882. {
  1883. index_item_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{info.papers[no].blob}/{url}").DownloadContentAsync();
  1884. }
  1885. else
  1886. {
  1887. index_item_json = await _azureStorage.GetBlobContainerClient($"{info.creatorId}").GetBlobClient($"{info.papers[no].blob}/{url}").DownloadContentAsync();
  1888. }
  1889. JsonElement itemJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(index_item_json.Content.ToString()))).RootElement;
  1890. itemJson.TryGetProperty("exercise", out JsonElement exercise);
  1891. itemJson.TryGetProperty("pid", out JsonElement pid);
  1892. var item_json = exercise.ToObject<Exercise>();
  1893. //JObject keys = JObject.Parse(index_item_json.Content.ToString());
  1894. string type = item_json.type;
  1895. int level = item_json.level;
  1896. var knowledge = item_json.knowledges;
  1897. //string pid = keys.Value<string>("pid");
  1898. itemInfos.Add((id, pid.ToString(), level, type, knowledge));
  1899. }
  1900. /* double[] point = StringHelper.ListTodouble(result.paper.point);
  1901. double[,] res = StringHelper.ListToDouble(result.studentScores);
  1902. var cdm = new ClouDASMatrix(res, point);*/
  1903. //需要努力的题目
  1904. //var ss = cdm.StriveTopic;
  1905. int n = 0;
  1906. List<Task<ItemResponse<ErrorItems>>> task_error = new();
  1907. List<ErrorItems> errors = new();
  1908. foreach (var sIds in result.studentIds)
  1909. {
  1910. ErrorItems error = new()
  1911. {
  1912. ttl = -1,
  1913. code = code,
  1914. id = Guid.NewGuid().ToString(),
  1915. stuId = sIds,
  1916. school = info.school,
  1917. activityId = info.id,
  1918. subjectId = result.subjectId,
  1919. time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1920. };
  1921. int index_stu = result.studentIds.IndexOf(sIds);
  1922. //顺序学生错题的索引
  1923. var itemScore = result.studentScores[index_stu];
  1924. List<int> index = new();
  1925. int index_item = 0;
  1926. foreach (var sc in itemScore)
  1927. {
  1928. if (sc == 0)
  1929. {
  1930. index.Add(index_item + 1);
  1931. }
  1932. index_item++;
  1933. }
  1934. if (index.Count == 0)
  1935. {
  1936. continue;
  1937. }
  1938. //int[] item_index = ss[n];
  1939. foreach (var item in index)
  1940. {
  1941. Items items = new()
  1942. {
  1943. id = urls[item - 1].Replace(".json", ""),
  1944. blob = info.papers[no].blob
  1945. };
  1946. items.level = itemInfos.Where(c => c.id.Equals(items.id)).FirstOrDefault().level;
  1947. items.type = itemInfos.Where(c => c.id.Equals(items.id)).FirstOrDefault().type;
  1948. items.pId = itemInfos.Where(c => c.id.Equals(items.id)).FirstOrDefault().pid;
  1949. items.knowledge = itemInfos.Where(c => c.id.Equals(items.id)).FirstOrDefault().knows;
  1950. items.qamode = info.qamode;
  1951. error.its.Add(items);
  1952. }
  1953. errors.Add(error);
  1954. n++;
  1955. task_error.Add(_azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(error, new PartitionKey($"{error.code}")));
  1956. }
  1957. //string connect = _configuration.GetValue<string>("HaBookAuth:Crtmabank") + "https://malearnfunction.chinacloudsites.cn/api/crtmabank";
  1958. string location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
  1959. string urlAction = string.Empty;
  1960. string accessKey = string.Empty;
  1961. if (location.Contains("China"))
  1962. {
  1963. if (location.Equals("China")) //大陸正式站
  1964. {
  1965. urlAction = "https://malearn.teammodel.cn";
  1966. accessKey = "2BcXFR_hvzG1pZjqIkaM7Dx74Hcu6m0PwwOacFpDpq44AzFuHJBRXA==";
  1967. }
  1968. else if (location.Equals("China-Dep") || location.Equals("China-Test")) //大陸測試站
  1969. {
  1970. urlAction = "https://malearn-rc.teammodel.cn";
  1971. accessKey = "lghWhJduNiAlo-e8isqEoROjdR7DAC-50XNtanIwHKYlAzFu1aog_A==";
  1972. }
  1973. }
  1974. else if (location.Contains("Global"))
  1975. {
  1976. if (location.Equals("Global")) //國際正式站
  1977. {
  1978. urlAction = "https://malearn.teammodel.net";
  1979. accessKey = "I-2lTcdggJkZWSBwOXQIm4oHx-huwX3d0wLe-9pgojThAzFuq_KNFg==";
  1980. }
  1981. else if (location.Equals("Global-Test")) //國際測試站
  1982. {
  1983. urlAction = "https://malearn-rc.teammodel.net";
  1984. accessKey = "_l4Cb_tHIRBw_iv3ZuwVqjkMwjg4_HtDaxhAmZ8OwJraAzFu_DAY8A==";
  1985. }
  1986. }
  1987. string connect = $"{urlAction}/api/crtmabank";
  1988. var htc = _httpClient.CreateClient();
  1989. if (htc.DefaultRequestHeaders.Contains("x-functions-key"))
  1990. {
  1991. htc.DefaultRequestHeaders.Remove("x-functions-key");
  1992. }
  1993. htc.DefaultRequestHeaders.Add("x-functions-key", accessKey);
  1994. ///智慧題庫school欄位修正
  1995. foreach (ErrorItems error in errors)
  1996. {
  1997. error.school = (info.scope.Equals("school")) ? info.school : string.Empty;
  1998. }
  1999. string paramJson = JsonConvert.SerializeObject(errors);
  2000. var content = new StringContent(paramJson, Encoding.UTF8, "application/json");
  2001. var response = await htc.PostAsync(connect, content);
  2002. if ((int)response.StatusCode == 200)
  2003. {
  2004. await task_error.TaskPage(10);
  2005. }
  2006. }
  2007. }
  2008. catch (Exception e)
  2009. {
  2010. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测错题异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  2011. }
  2012. }
  2013. public class Settlement
  2014. {
  2015. public double rate { get; set; }
  2016. public double score { get; set; }
  2017. public List<string> stus { get; set; } = new List<string>();
  2018. public int total { get; set; }
  2019. public double qrate { get; set; }
  2020. }
  2021. #region ===學習記錄用類別===
  2022. private class PaperIndex
  2023. {
  2024. public PaperIndex()
  2025. {
  2026. slides = new List<Slide>();
  2027. }
  2028. public List<Slide> slides { get; set; }
  2029. }
  2030. private class Slide
  2031. {
  2032. /// <summary>
  2033. /// blob 路徑
  2034. /// </summary>
  2035. public string url { get; set; }
  2036. /// <summary>
  2037. /// 題型
  2038. /// </summary>
  2039. public string type { get; set; }
  2040. /// <summary>
  2041. /// scoring
  2042. /// </summary>
  2043. public Scoring scoring { get; set; }
  2044. }
  2045. private class Exercise
  2046. {
  2047. /// <summary>
  2048. /// 题目类型
  2049. /// </summary>
  2050. public string type { get; set; }
  2051. /// <summary>
  2052. /// 难度
  2053. /// </summary>
  2054. public int level { get; set; }
  2055. /// <summary>
  2056. /// 知识点
  2057. /// </summary>
  2058. public List<string> knowledges { get; set; }
  2059. }
  2060. private class Scoring
  2061. {
  2062. /// <summary>
  2063. /// knowledge
  2064. /// </summary>
  2065. public List<string> knowledge { get; set; }
  2066. /// <summary>
  2067. /// 答案
  2068. /// </summary>
  2069. public List<string> ans { get; set; }
  2070. }
  2071. private class StudentAnswers
  2072. {
  2073. /// <summary>
  2074. /// 學生作答 blob 路徑
  2075. /// </summary>
  2076. public List<List<string>> studentAnswers { get; set; }
  2077. /// <summary>
  2078. /// 學生ID
  2079. /// </summary>
  2080. public List<string> studentIds { get; set; } = new();
  2081. }
  2082. private class QuestionData
  2083. {
  2084. public QuestionData()
  2085. {
  2086. item = new List<QuestionItem>();
  2087. }
  2088. public QuestionExercise exercise { get; set; }
  2089. public List<QuestionItem> item { get; set; }
  2090. }
  2091. private class QuestionItem
  2092. {
  2093. public QuestionItem()
  2094. {
  2095. option = new List<OptionItem>();
  2096. }
  2097. public string question { get; set; }
  2098. public List<OptionItem> option { get; set; }
  2099. }
  2100. private class OptionItem
  2101. {
  2102. public string code { get; set; }
  2103. public string value { get; set; }
  2104. }
  2105. private class QuestionExercise
  2106. {
  2107. public string type { get; set; }
  2108. public List<string> knowledge { get; set; }
  2109. public List<string> answer { get; set; }
  2110. }
  2111. #endregion
  2112. }
  2113. }