TriggerExam.cs 87 KB

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