TriggerExam.cs 80 KB

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