TriggerExam.cs 120 KB

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