TriggerExam.cs 120 KB

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