TriggerExam.cs 126 KB

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