TriggerExam.cs 84 KB

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