TriggerExam.cs 127 KB

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