TriggerExam.cs 96 KB

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