TriggerExam.cs 119 KB

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