TriggerExam.cs 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  1. using Azure.Cosmos;
  2. using Azure.Messaging.ServiceBus;
  3. using Microsoft.Azure.Documents;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Text.Json;
  9. using System.Threading.Tasks;
  10. using TEAMModelOS.SDK.DI;
  11. using TEAMModelOS.SDK.Extension;
  12. using TEAMModelOS.SDK;
  13. using TEAMModelOS.SDK.Models;
  14. using TEAMModelOS.SDK.Models.Service;
  15. using HTEXLib.COMM.Helpers;
  16. using System.Net.Http;
  17. namespace TEAMModelOS.FunctionV4
  18. {
  19. public class TriggerExam
  20. {
  21. public static async Task Trigger(CoreAPIHttpService _coreAPIHttpService, AzureCosmosFactory _azureCosmos, AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
  22. CosmosClient client, JsonElement input, TriggerData data)
  23. {
  24. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  25. List<ExamSubject> examSubjects = new List<ExamSubject>();
  26. try
  27. {
  28. if ((data.status != null && data.status.Value == 404))
  29. {
  30. await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync( data.id, new PartitionKey( data.code));
  31. ActivityList activity = input.ToObject<ActivityList>();
  32. await ActivityService.DeleteActivity(_coreAPIHttpService, client, _dingDing, activity);
  33. return;
  34. }
  35. ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(data.id, new Azure.Cosmos.PartitionKey($"{data.code}"));
  36. if (info != null)
  37. {
  38. if (info.scope.Equals("teacher", StringComparison.OrdinalIgnoreCase) || info.scope.Equals("private", StringComparison.OrdinalIgnoreCase))
  39. {
  40. 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}") }))
  41. {
  42. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  43. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  44. {
  45. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  46. {
  47. examClassResults.Add(obj.ToObject<ExamClassResult>());
  48. }
  49. }
  50. }
  51. }
  52. else
  53. {
  54. 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}") }))
  55. {
  56. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  57. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  58. {
  59. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  60. {
  61. examClassResults.Add(obj.ToObject<ExamClassResult>());
  62. }
  63. }
  64. }
  65. }
  66. string PartitionKey = string.Format("{0}{1}{2}", info.code, "-", info.progress);
  67. List<ChangeRecord> records = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", data.id }, { "PartitionKey", PartitionKey } });
  68. //处理科目信息
  69. List<string> sub = new List<string>();
  70. foreach (ExamSubject subject in info.subjects)
  71. {
  72. sub.Add(subject.id);
  73. }
  74. //整合名单
  75. List<string> classes = ExamService.getClasses(info.classes, info.stuLists);
  76. //ChangeRecord record = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ChangeRecord>(input.Id, new Azure.Cosmos.PartitionKey($"{info.progress}"));
  77. switch (info.progress)
  78. {
  79. case "pending":
  80. var message = new ServiceBusMessage(new { id = data.id, progress = "going", code = data.code }.ToJsonString());
  81. message.ApplicationProperties.Add("name", "Exam");
  82. if (records.Count > 0)
  83. {
  84. await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), records[0].sequenceNumber);
  85. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(data.startTime));
  86. records[0].sequenceNumber = start;
  87. await _azureStorage.SaveOrUpdate<ChangeRecord>(records[0]);
  88. //await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(record, record.id, new Azure.Cosmos.PartitionKey($"{record.code}"));
  89. }
  90. else
  91. {
  92. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(data.startTime));
  93. //string pk = String.Format("{0}{1}{2}", info.code, "-", "pending");
  94. ChangeRecord changeRecord = new ChangeRecord
  95. {
  96. RowKey = data.id,
  97. PartitionKey = PartitionKey,
  98. sequenceNumber = start,
  99. msgId = message.MessageId
  100. };
  101. await _azureStorage.Save<ChangeRecord>(changeRecord);
  102. //await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  103. }
  104. break;
  105. case "going":
  106. try
  107. {
  108. //向学生或醍摩豆账号发起通知
  109. #region
  110. //Notice notice = new Notice()
  111. //{
  112. // msgId = info.id,
  113. // creation = info.startTime,
  114. // expire = info.endTime,
  115. // creatorId = info.creatorId,
  116. // stuids = studentss,
  117. // tmdids = tmdids,
  118. // type = "notice",//评测参加通知
  119. // priority = "normal",
  120. // school = info.school,
  121. // scope = info.scope,
  122. // //data = new { }.ToJsonString()
  123. // body = new Body { sid = info.id, scode = info.code, spk = info.pk, biztype = "exam-join" }
  124. //};
  125. //var messageBlob = new ServiceBusMessage(notice.ToJsonString());
  126. //messageBlob.ApplicationProperties.Add("name", "Notice");
  127. //await _serviceBus.GetServiceBusClient().SendMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageBlob);
  128. #endregion
  129. //List<string> classes = new List<string>();
  130. if (examClassResults.Count == 0)
  131. {
  132. //处理活动中间件
  133. List<RGroupList> members = await Activity(_coreAPIHttpService,info, classes, client, _dingDing, sub, examClassResults);
  134. foreach (string cla in classes)
  135. {
  136. int m = 0;
  137. foreach (ExamSubject subject in info.subjects)
  138. {
  139. string classCode = String.Empty;
  140. string cname = string.Empty;
  141. if (string.IsNullOrEmpty(info.school) || !info.scope.Equals("school", StringComparison.OrdinalIgnoreCase))
  142. {
  143. classCode = "ExamClassResult-" + info.creatorId;
  144. }
  145. else
  146. {
  147. classCode = "ExamClassResult-" + info.school;
  148. }
  149. cname = members.Where(m => m.id.Equals(cla)).FirstOrDefault()?.name;
  150. ExamClassResult result = new ExamClassResult
  151. {
  152. code = classCode,
  153. examId = info.id,
  154. id = Guid.NewGuid().ToString(),
  155. subjectId = subject.id,
  156. year = info.year,
  157. scope = info.scope
  158. };
  159. result.info.id = cla;
  160. result.info.name = cname;
  161. List<string> ans = new List<string>();
  162. List<List<string>> anses = new List<List<string>>();
  163. List<List<Details>> marks = new List<List<Details>>();
  164. List<double> ansPoint = new List<double>();
  165. List<(string sId,string scode)> ids = new List<(string sId, string scode)>();
  166. foreach (double p in info.papers[m].point)
  167. {
  168. //Details details = new Details();
  169. //ans.Add(new List<string>());
  170. anses.Add(new List<string>());
  171. marks.Add(new List<Details>());
  172. ansPoint.Add(-1);
  173. }
  174. var sresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"Class-{info.school}"));
  175. if (sresponse.Status == 200)
  176. {
  177. using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
  178. Class classroom = json.ToObject<Class>();
  179. School sc = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(info.school, new Azure.Cosmos.PartitionKey("Base"));
  180. foreach (Period period in sc.period)
  181. {
  182. if (period.id.Equals(classroom.periodId))
  183. {
  184. foreach (Semester semester in period.semesters)
  185. {
  186. if (semester.start == 1)
  187. {
  188. int year = DateTimeOffset.UtcNow.Year;
  189. int month = DateTimeOffset.UtcNow.Month;
  190. int day = DateTimeOffset.UtcNow.Day;
  191. int time = 0;
  192. if (month == semester.month)
  193. {
  194. time = day >= semester.day ? 0 : 1;
  195. }
  196. else
  197. {
  198. time = month > semester.month ? 0 : 1;
  199. }
  200. int eyear = year - time;
  201. result.gradeId = (eyear - classroom.year).ToString();
  202. }
  203. }
  204. }
  205. }
  206. //result.info.id = classroom.id;
  207. //result.info.name = classroom.name;
  208. //result.gradeId = classroom.year.ToString();
  209. //处理班级人数
  210. /* 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}") }))
  211. {
  212. using var json_stu = await JsonDocument.ParseAsync(item.ContentStream);
  213. if (json_stu.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  214. {
  215. var accounts = json_stu.RootElement.GetProperty("Documents").EnumerateArray();
  216. while (accounts.MoveNext())
  217. {
  218. JsonElement account = accounts.Current;
  219. ids.Add(account.GetProperty("id").GetString());
  220. }
  221. }
  222. }*/
  223. }
  224. /*if (info.scope.Equals("private", StringComparison.OrdinalIgnoreCase))
  225. {
  226. var stuResponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"GroupList"));
  227. if (stuResponse.Status == 200)
  228. {
  229. using var json = await JsonDocument.ParseAsync(stuResponse.ContentStream);
  230. GroupList stuList = json.ToObject<GroupList>();
  231. //result.info.id = stuList.id;
  232. result.info.name = stuList.name;
  233. //处理发布对象为自选名单(个人)
  234. foreach (Member stus in stuList.members)
  235. {
  236. if (!ids.Contains(stus.id))
  237. {
  238. ids.Add(stus.id);
  239. }
  240. }
  241. }
  242. }
  243. else
  244. {
  245. var stuResponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"GroupList-{info.school}"));
  246. if (stuResponse.Status == 200)
  247. {
  248. using var json = await JsonDocument.ParseAsync(stuResponse.ContentStream);
  249. GroupList stuList = json.ToObject<GroupList>();
  250. //result.info.id = stuList.id;
  251. result.info.name = stuList.name;
  252. //处理发布对象为自选名单(校本)
  253. foreach (Member stus in stuList.members)
  254. {
  255. if (!ids.Contains(stus.id))
  256. {
  257. ids.Add(stus.id);
  258. }
  259. }
  260. }
  261. }*/
  262. foreach (RGroupList list in members) {
  263. foreach (RMember member in list.members) {
  264. ids.Add((member.id,member.code));
  265. }
  266. }
  267. //ids = members.Where(c => c.id.Equals(cla)).SelectMany(m => m.members).Select(g => g.id).ToList();
  268. foreach (var stu in ids)
  269. {
  270. result.mark.Add(marks);
  271. result.studentIds.Add(stu.sId);
  272. result.scIds.Add(stu.scode);
  273. result.studentAnswers.Add(ans);
  274. result.studentScores.Add(ansPoint);
  275. result.ans.Add(anses);
  276. result.sum.Add(0);
  277. result.status.Add(0);
  278. }
  279. //result.progress = info.progress;
  280. result.school = info.school;
  281. m++;
  282. await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(result, new Azure.Cosmos.PartitionKey($"{result.code}"));
  283. }
  284. }
  285. }
  286. else
  287. {
  288. //处理单科结算时科目与试卷信息匹配的问题
  289. int gno = 0;
  290. foreach (ExamSubject subject in info.subjects)
  291. {
  292. if (subject.classCount == classes.Count)
  293. {
  294. await createClassResultAsync(info, examClassResults, subject, gno, _azureCosmos, _dingDing, _azureStorage);
  295. }
  296. gno++;
  297. }
  298. if (gno == info.subjects.Count) {
  299. var isScore = examClassResults.SelectMany(e => e.studentScores).ToList().Exists(c => c.Contains(-1));
  300. int newStatus = 0;
  301. if (!isScore)
  302. {
  303. newStatus = 1;
  304. }
  305. Settlement settlement = await getMore(client, info, examClassResults);
  306. long nowTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  307. //判断评分状态是否发生变化,便于实时的更新评测基本信息
  308. if ((info.updateTime != nowTime && info.average != settlement.score) || info.sStatus != newStatus)
  309. {
  310. info.sRate = settlement.rate;
  311. info.sStatus = newStatus;
  312. info.updateTime = nowTime;
  313. info.average = settlement.score;
  314. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ExamInfo>(info, info.id, new PartitionKey(info.code));
  315. }
  316. }
  317. }
  318. }
  319. catch (Exception e)
  320. {
  321. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测going状态异常{e.Message}\n{e.StackTrace}", GroupNames.成都开发測試群組);
  322. }
  323. finally
  324. {
  325. // 发送信息通知
  326. var messageEnd = new ServiceBusMessage(new { id = data.id, progress = "finish", code = data.code }.ToJsonString());
  327. messageEnd.ApplicationProperties.Add("name", "Exam");
  328. if (records.Count > 0)
  329. {
  330. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(data.endTime));
  331. await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), records[0].sequenceNumber);
  332. records[0].sequenceNumber = end;
  333. await _azureStorage.SaveOrUpdate<ChangeRecord>(records[0]);
  334. //await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(record, record.id, new Azure.Cosmos.PartitionKey($"{record.code}"));
  335. }
  336. else
  337. {
  338. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(data.endTime));
  339. //string pk = String.Format("{0}{1}{2}", info.code, "-", "going");
  340. ChangeRecord changeRecord = new ChangeRecord
  341. {
  342. RowKey = data.id,
  343. PartitionKey = PartitionKey,
  344. sequenceNumber = end,
  345. msgId = messageEnd.MessageId
  346. };
  347. await _azureStorage.Save<ChangeRecord>(changeRecord);
  348. //await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  349. }
  350. }
  351. break;
  352. case "finish":
  353. int fno = 0;
  354. try
  355. {
  356. //用来判定是否完成评分
  357. //bool isScore = true;
  358. var isScore = examClassResults.SelectMany(e => e.studentScores).ToList().Exists(c => c.Contains(-1));
  359. int newStatus = 0;
  360. if (!isScore)
  361. {
  362. newStatus = 1;
  363. }
  364. //处理活动中间件
  365. List<StuActivity> stus = new List<StuActivity>();
  366. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<StuActivity>(
  367. queryText: $"select c.id from c where c.id = '{info.id}'" ))
  368. {
  369. stus.Add(item);
  370. }
  371. if (info.source.Equals("1") && stus.Count == 0) {
  372. await Activity(_coreAPIHttpService,info, classes,client, _dingDing, sub, examClassResults);
  373. }
  374. foreach (ExamSubject subject in info.subjects)
  375. {
  376. await createClassResultAsync(info, examClassResults, subject, fno, _azureCosmos, _dingDing, _azureStorage);
  377. fno++;
  378. }
  379. Settlement settlement = await getMore(client, info, examClassResults);
  380. //info.lostStu = losStu;
  381. /*//补充历史数据的容器名称
  382. if (string.IsNullOrEmpty(info.cn)) {
  383. if (info.scope.Equals("school"))
  384. {
  385. info.cn = info.school;
  386. }
  387. else {
  388. info.cn = info.creatorId;
  389. }
  390. }*/
  391. //判断均分是否发生变化,便于实时的更新评测基本信息
  392. if (info.sRate != settlement.rate || info.average != settlement.score || info.sStatus != newStatus)
  393. {
  394. info.sRate = settlement.rate;
  395. info.average = settlement.score;
  396. info.sStatus = newStatus;
  397. info.lostStu = settlement.stus;
  398. info.stuCount = settlement.total;
  399. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ExamInfo>(info, info.id, new Azure.Cosmos.PartitionKey(info.code));
  400. }
  401. }
  402. catch (Exception e)
  403. {
  404. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测finish状态异常{e.Message}\n{e.StackTrace}", GroupNames.成都开发測試群組);
  405. }
  406. break;
  407. }
  408. }
  409. }
  410. catch (CosmosException e)
  411. {
  412. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDB异常{e.Message}\n{e.Status}", GroupNames.成都开发測試群組);
  413. } catch (Exception e) {
  414. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-评测结算异常{e.Message}\n{e.StackTrace}", GroupNames.成都开发測試群組);
  415. }
  416. }
  417. public static async Task<Settlement> getMore(CosmosClient client,ExamInfo info,List<ExamClassResult> examClassResults) {
  418. //计算单次考试简易统计信息
  419. Settlement settlement = new Settlement();
  420. List<ExamResult> examResults = new List<ExamResult>();
  421. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamResult>(
  422. queryText: $"select value(c) from c where c.examId = '{info.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}") }))
  423. {
  424. examResults.Add(item);
  425. }
  426. List<Task<ItemResponse<ExamClassResult>>> tasks = new List<Task<ItemResponse<ExamClassResult>>>();
  427. //结算单科单班的标准差和平均分
  428. foreach (ExamClassResult classResult in examClassResults)
  429. {
  430. //标记单科单班总得分
  431. double subScore = 0;
  432. //标准差
  433. double sPowSum = 0;
  434. List<double> newSumScore = new List<double>();
  435. var scount = classResult.studentIds.Count;
  436. foreach (List<double> sc in classResult.studentScores)
  437. {
  438. List<double> newSc = new List<double>();
  439. foreach (double ssc in sc)
  440. {
  441. if (ssc == -1)
  442. {
  443. newSc.Add(0);
  444. }
  445. else
  446. {
  447. newSc.Add(ssc);
  448. }
  449. }
  450. double nc = newSc.Sum();
  451. newSumScore.Add(nc);
  452. subScore += nc;
  453. }
  454. double rateScore = scount > 0 ? Math.Round(subScore * 1.0 / scount, 2) : 0;
  455. foreach (double scs in newSumScore)
  456. {
  457. sPowSum += Math.Pow(scs - rateScore, 2);
  458. }
  459. classResult.standard = Math.Round(scount > 0 ? Math.Pow(sPowSum / scount, 0.5) : 0, 2);
  460. classResult.average = scount > 0 ? Math.Round(subScore / scount, 2) : 0;
  461. classResult.progress = true;
  462. tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new Azure.Cosmos.PartitionKey($"{classResult.code}")));
  463. }
  464. await Task.WhenAll(tasks);
  465. //记录某次考试所有学生得分总分
  466. double score = 0;
  467. double allScore = 0;
  468. int stuCount = 0;
  469. //标准差
  470. double powSum = 0;
  471. List<string> losStu = new List<string>();
  472. //当前完成考试得人数
  473. int total = examResults[0].studentIds.Count;
  474. //先与第一个值取并集
  475. if (examResults.Count > 0)
  476. {
  477. losStu = losStu.Union(examResults[0].lostStus).ToList();
  478. foreach (ExamResult examResult in examResults)
  479. {
  480. if (info.id == examResult.examId)
  481. {
  482. foreach (List<double> sc in examResult.studentScores)
  483. {
  484. score += sc.Sum();
  485. }
  486. stuCount = examResult.studentIds.Count;
  487. }
  488. //powSum += Math.Pow(score - examResult.studentIds.Count > 0 ? Math.Round(score * 1.0 / examResult.studentIds.Count, 2) : 0, 2);
  489. //取交集
  490. losStu = losStu.Intersect(examResult.lostStus).ToList();
  491. }
  492. }
  493. double NewsRateScore = stuCount > 0 ? Math.Round(score * 1.0 / stuCount, 2) : 0;
  494. foreach (PaperSimple simple in info.papers)
  495. {
  496. allScore += simple.point.Sum();
  497. }
  498. //计算全科标准差
  499. foreach (string id in examResults[0].studentIds)
  500. {
  501. double sc = 0;
  502. foreach (ExamResult result in examResults)
  503. {
  504. sc += result.studentScores[result.studentIds.IndexOf(id)].Sum();
  505. }
  506. powSum += Math.Pow(sc - NewsRateScore, 2);
  507. }
  508. info.standard = Math.Round(total > 0 ? Math.Pow(powSum / total, 0.5) : 0, 2);
  509. double NewsRate = allScore > 0 ? Math.Round(NewsRateScore / allScore * 100, 2) : 0;
  510. settlement.rate = NewsRate;
  511. settlement.score = NewsRateScore;
  512. settlement.stus = losStu;
  513. settlement.total = total;
  514. return settlement;
  515. }
  516. //处理全部学生选题计数
  517. public static async Task examRecordCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, ExamResult result, List<ExamClassResult> classResults, AzureCosmosFactory _azureCosmos)
  518. {
  519. try
  520. {
  521. List<double> scores = new List<double>();
  522. foreach (List<double> sc in result.studentScores)
  523. {
  524. scores.Add(sc.Sum());
  525. }
  526. //确定高分组 最低分数
  527. scores.Sort((s1, s2) => { return s2.CompareTo(s1); });
  528. double rhwCount = Math.Floor(scores.Count * 0.27);
  529. double rhw = rhwCount > 0 ? scores[int.Parse(rhwCount.ToString("0"))] : 0;
  530. //确定低分组 最高分数
  531. //scores.Sort((s1, s2) => { return s1.CompareTo(s2); });
  532. double rhlCount = Math.Ceiling(scores.Count * 0.73);
  533. double rhl = rhlCount > 0 ? scores[int.Parse(rhlCount.ToString("0")) - 1] : 0;
  534. //存放高分组学生ID
  535. List<string> phId = new List<string>();
  536. List<string> plId = new List<string>();
  537. List<List<List<string>>> opth = new List<List<List<string>>>();
  538. List<List<List<string>>> optl = new List<List<List<string>>>();
  539. await knowledgeCount(info, subject, _dingDing, no, classResults, rhwCount, rhw, rhlCount, rhl, _azureCosmos);
  540. await fieldCount(info, subject, _dingDing, no, classResults, rhwCount, rhw, rhlCount, rhl, _azureCosmos);
  541. int PHCount = 0;
  542. int PLCount = 0;
  543. foreach (ExamClassResult classResult in classResults)
  544. {
  545. if (classResult.subjectId.Equals(subject.id))
  546. {
  547. foreach (string id in classResult.studentIds)
  548. {
  549. int index = classResult.studentIds.IndexOf(id);
  550. if (classResult.studentScores.Count > 0)
  551. {
  552. if (classResult.studentScores[index].Sum() >= rhw && PHCount < rhwCount)
  553. {
  554. if (classResult.ans.Count > 0)
  555. {
  556. opth.Add(classResult.ans[index]);
  557. PHCount++;
  558. continue;
  559. }
  560. }
  561. if (classResult.studentScores[index].Sum() <= rhl && PLCount < (scores.Count - rhlCount))
  562. {
  563. if (classResult.ans.Count > 0)
  564. {
  565. optl.Add(classResult.ans[index]);
  566. PLCount++;
  567. continue;
  568. }
  569. }
  570. }
  571. }
  572. }
  573. }
  574. result.phc = getMore(info, no, opth);
  575. result.plc = getMore(info, no, optl);
  576. }
  577. catch (Exception ex)
  578. {
  579. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测作答记录结算异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  580. }
  581. }
  582. public static async Task<List<RGroupList>> Activity(CoreAPIHttpService _coreAPIHttpService, ExamInfo info, List<string> classes,CosmosClient client, DingDing _dingDing, List<string> sub,List<ExamClassResult> results) {
  583. List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
  584. if (info.groupLists.Count > 0)
  585. {
  586. var group = info.groupLists;
  587. foreach (var gp in group)
  588. {
  589. foreach (KeyValuePair<string, List<string>> pp in gp)
  590. {
  591. ps.Add((pp.Key, pp.Value));
  592. }
  593. }
  594. }
  595. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService,client, _dingDing, classes, info.school, ps);
  596. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  597. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  598. List<StuActivity> stuActivities = new List<StuActivity>();
  599. List<StuActivity> tmdActivities = new List<StuActivity>();
  600. if (addTmdidsCls.IsNotEmpty())
  601. {
  602. addTmdidsCls.ForEach(x =>
  603. {
  604. HashSet<string> classIds = new HashSet<string>();
  605. classLists.ForEach(z => {
  606. z.members.ForEach(y => {
  607. if (y.id.Equals(x.id) && y.type == 1)
  608. {
  609. classIds.Add(z.id);
  610. }
  611. });
  612. });
  613. bool flag = false;
  614. if (results.Count > 0)
  615. {
  616. foreach (ExamClassResult exam in results)
  617. {
  618. int index = exam.studentIds.IndexOf(x.id);
  619. if (index != -1)
  620. {
  621. flag = exam.studentScores[index].Exists(x => x == -1);
  622. if (!flag) {
  623. break;
  624. }
  625. }
  626. }
  627. }
  628. tmdActivities.Add(new StuActivity
  629. {
  630. pk = "Activity",
  631. id = info.id,
  632. code = $"Activity-{x.id}",
  633. type = "Exam",
  634. name = info.name,
  635. source = info.source,
  636. startTime = info.startTime,
  637. endTime = info.endTime,
  638. scode = info.code,
  639. scope = info.scope,
  640. school = info.school,
  641. creatorId = info.creatorId,
  642. subjects = sub,
  643. blob = null,
  644. owner = info.owner,
  645. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  646. taskStatus = -1,
  647. ext = new Dictionary<string, JsonElement>() { { "type",info.type.ToJsonString().ToObject<JsonElement>() },{ "subjects", info.subjects.ToJsonString().ToObject<JsonElement>() }},
  648. sStatus = flag ? 0 : 1,
  649. classIds = classIds.ToList()
  650. }); ;
  651. });
  652. }
  653. if (addStudentsCls.IsNotEmpty())
  654. {
  655. addStudentsCls.ForEach(x =>
  656. {
  657. HashSet<string> classIds = new HashSet<string>();
  658. classLists.ForEach(z => {
  659. z.members.ForEach(y => {
  660. if (y.id.Equals(x.id) && y.code.Equals(info.school) && y.type == 2)
  661. {
  662. classIds.Add(z.id);
  663. }
  664. });
  665. });
  666. bool flag = false;
  667. if (results.Count > 0) {
  668. foreach (ExamClassResult exam in results)
  669. {
  670. int index = exam.studentIds.IndexOf(x.id);
  671. if (index != -1)
  672. {
  673. flag = exam.studentScores[index].Exists(x => x == -1);
  674. if (!flag)
  675. {
  676. break;
  677. }
  678. }
  679. }
  680. }
  681. stuActivities.Add(new StuActivity
  682. {
  683. pk = "Activity",
  684. id = info.id,
  685. code = $"Activity-{x.code.Replace("Base-", "")}-{x.id}",
  686. type = "Exam",
  687. name = info.name,
  688. source = info.source,
  689. startTime = info.startTime,
  690. endTime = info.endTime,
  691. scode = info.code,
  692. scope = info.scope,
  693. school = info.school,
  694. creatorId = info.creatorId,
  695. subjects = sub,
  696. blob = null,
  697. owner = info.owner,
  698. classIds = classIds.ToList(),
  699. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  700. ext = new Dictionary<string, JsonElement>() { { "type", info.type.ToJsonString().ToObject<JsonElement>() },
  701. { "subjects", info.subjects.ToJsonString().ToObject<JsonElement>() } },
  702. taskStatus = -1,
  703. sStatus = flag ? 0 : 1,
  704. });
  705. });
  706. }
  707. await ActivityService.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities, null);
  708. return classLists;
  709. }
  710. public static async Task knowledgeCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, List<ExamClassResult> classResults,
  711. double rhwCount, double rhw, double rhlCount, double rhl, AzureCosmosFactory _azureCosmos)
  712. {
  713. try
  714. {
  715. int phcount = 0;
  716. int plcount = 0;
  717. //存放并去重知识点
  718. HashSet<string> kname = new HashSet<string>();
  719. if (info.papers[no].knowledge.Count > 0)
  720. {
  721. info.papers[no].knowledge.ForEach(kno =>
  722. {
  723. kno.ForEach(k =>
  724. {
  725. kname.Add(k);
  726. });
  727. });
  728. List<string> knowledgeName = new List<string>();
  729. foreach (string cla in kname)
  730. {
  731. knowledgeName.Add(cla);
  732. }
  733. for (int k = 0; k < knowledgeName.Count; k++)
  734. {
  735. if (null == knowledgeName[k])
  736. {
  737. knowledgeName.Remove(knowledgeName[k]);
  738. }
  739. }
  740. foreach (ExamClassResult classResult in classResults)
  741. {
  742. if (classResult.subjectId.Equals(subject.id))
  743. {
  744. //List<int> phc = new List<int>();
  745. List<int> ph = new List<int>();
  746. List<int> pl = new List<int>();
  747. List<int> pc = new List<int>();
  748. List<double> persent = new List<double>();
  749. for (int i = 0; i < knowledgeName.Count; i++)
  750. {
  751. //初始化单个知识点得分
  752. double score = 0;
  753. double allScore = 0;
  754. int n = 0;
  755. int phCount = 0;
  756. int plCount = 0;
  757. int pCount = 0;
  758. foreach (List<string> str in info.papers[no].knowledge)
  759. {
  760. if (str.Contains(knowledgeName[i]))
  761. {
  762. var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
  763. allScore += info.papers[no].point.Count > 0 ? info.papers[no].point[n] * itemPersent : 0;
  764. foreach (string id in classResult.studentIds)
  765. {
  766. int index = classResult.studentIds.IndexOf(id);
  767. if (classResult.studentScores.Count > 0)
  768. {
  769. if (classResult.studentScores[index].Count > 0)
  770. {
  771. score += classResult.studentScores[index][n] == -1 ? 0 : classResult.studentScores[index][n];
  772. if (classResult.studentScores[index].Sum() >= rhw && phcount < rhwCount)
  773. {
  774. if (classResult.studentScores[index][n] <= 0)
  775. {
  776. phCount++;
  777. }
  778. phcount++;
  779. continue;
  780. }
  781. if (classResult.studentScores[index].Sum() <= rhl && plcount < (info.stuCount - rhlCount))
  782. {
  783. if (classResult.studentScores[index][n] <= 0)
  784. {
  785. plCount++;
  786. }
  787. plcount++;
  788. continue;
  789. }
  790. if (classResult.studentScores[index][n] <= 0)
  791. {
  792. pCount++;
  793. }
  794. }
  795. }
  796. }
  797. }
  798. n++;
  799. }
  800. pc.Add(pCount);
  801. ph.Add(phCount);
  802. pl.Add(plCount);
  803. double per = classResult.studentIds.Count > 0 ? Math.Round(score / classResult.studentIds.Count, 2) : 0;
  804. persent.Add(allScore > 0 ? per / allScore : 0);
  805. }
  806. classResult.phc = ph;
  807. classResult.plc = pl;
  808. classResult.pc = pc;
  809. classResult.krate = persent;
  810. }
  811. //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new Azure.Cosmos.PartitionKey($"{classResult.code}"));
  812. }
  813. }
  814. }
  815. catch (Exception ex)
  816. {
  817. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测知识点结算异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  818. }
  819. }
  820. public static async Task fieldCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, List<ExamClassResult> classResults,
  821. double rhwCount, double rhw, double rhlCount, double rhl, AzureCosmosFactory _azureCosmos)
  822. {
  823. try
  824. {
  825. int phcount = 0;
  826. int plcount = 0;
  827. //存放并去重知识点
  828. List<int> knowledgeName = new List<int>() { 1,2,3,4,5,6};
  829. /* knowledgeName.Add(1);
  830. knowledgeName.Add(2);
  831. knowledgeName.Add(3);
  832. knowledgeName.Add(4);
  833. knowledgeName.Add(5);
  834. knowledgeName.Add(6);*/
  835. foreach (ExamClassResult classResult in classResults)
  836. {
  837. if (classResult.subjectId.Equals(subject.id))
  838. {
  839. //List<int> phc = new List<int>();
  840. List<int> ph = new List<int>();
  841. List<int> pl = new List<int>();
  842. List<int> pc = new List<int>();
  843. List<double> persent = new List<double>();
  844. for (int i = 0; i < knowledgeName.Count; i++)
  845. {
  846. //初始化单个知识点得分
  847. double score = 0;
  848. double allScore = 0;
  849. int n = 0;
  850. int phCount = 0;
  851. int plCount = 0;
  852. int pCount = 0;
  853. if (info.papers[no].field.Count > 0)
  854. {
  855. foreach (int str in info.papers[no].field)
  856. {
  857. if (str == knowledgeName[i])
  858. {
  859. var itemPersent = 1;
  860. allScore += info.papers[no].point.Count > 0 ? info.papers[no].point[n] * itemPersent : 0;
  861. foreach (string id in classResult.studentIds)
  862. {
  863. int index = classResult.studentIds.IndexOf(id);
  864. if (classResult.studentScores.Count > 0)
  865. {
  866. if (classResult.studentScores[index].Count > 0)
  867. {
  868. score += classResult.studentScores[index][n] == -1 ? 0 : classResult.studentScores[index][n];
  869. if (classResult.studentScores[index].Sum() >= rhw && phcount < rhwCount)
  870. {
  871. if (classResult.studentScores[index][n] <= 0)
  872. {
  873. phCount++;
  874. }
  875. phcount++;
  876. continue;
  877. }
  878. if (classResult.studentScores[index].Sum() <= rhl && plcount < (info.stuCount - rhlCount))
  879. {
  880. if (classResult.studentScores[index][n] <= 0)
  881. {
  882. plCount++;
  883. }
  884. plcount++;
  885. continue;
  886. }
  887. if (classResult.studentScores[index][n] <= 0)
  888. {
  889. pCount++;
  890. }
  891. }
  892. }
  893. }
  894. }
  895. n++;
  896. }
  897. pc.Add(pCount);
  898. ph.Add(phCount);
  899. pl.Add(plCount);
  900. double per = classResult.studentIds.Count > 0 ? Math.Round(score / classResult.studentIds.Count, 2) : 0;
  901. persent.Add(allScore > 0 ? per / allScore : 0);
  902. }
  903. }
  904. classResult.fphc = ph;
  905. classResult.fplc = pl;
  906. classResult.fpc = pc;
  907. classResult.frate = persent;
  908. }
  909. //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new Azure.Cosmos.PartitionKey($"{classResult.code}"));
  910. }
  911. }
  912. catch (Exception ex)
  913. {
  914. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测认知层次结算异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  915. }
  916. }
  917. //处理选题计数
  918. public static List<Dictionary<string, int>> getMore(ExamInfo info, int no, List<List<List<string>>> list)
  919. {
  920. List<Dictionary<string, int>> recorde = new List<Dictionary<string, int>>();
  921. try
  922. {
  923. for (int i = 0; i < info.papers[no].answers.Count; i++)
  924. {
  925. if (info.papers[no].answers[i].Count <= 0)
  926. {
  927. recorde.Add(new Dictionary<string, int>());
  928. continue;
  929. }
  930. Dictionary<string, int> optCount = new Dictionary<string, int>();
  931. foreach (List<List<string>> stu in list)
  932. {
  933. if (stu.Count == info.papers[no].answers.Count)
  934. {
  935. var item = stu[i];
  936. foreach (string opt in item)
  937. {
  938. if (optCount.ContainsKey(opt))
  939. {
  940. optCount[opt] = optCount[opt] + 1;
  941. }
  942. else
  943. {
  944. optCount[opt] = 1;
  945. }
  946. }
  947. }
  948. }
  949. recorde.Add(optCount);
  950. }
  951. return recorde;
  952. }
  953. catch (Exception)
  954. {
  955. return recorde;
  956. }
  957. }
  958. public static async Task createClassResultAsync(ExamInfo info, List<ExamClassResult> examClassResults, ExamSubject subject, int no, AzureCosmosFactory _azureCosmos, DingDing _dingDing, AzureStorageFactory _azureStorage)
  959. {
  960. //保证试卷信息与科目信息同步
  961. ExamResult result = new ExamResult();
  962. //人数总和
  963. int Count = 0;
  964. int m = 0;
  965. double score = 0;
  966. //标准差
  967. double powSum = 0;
  968. double allScore = info.papers[no].point.Sum();
  969. List<ClassRange> classRanges = new List<ClassRange>();
  970. List<string> lostStu = new List<string>();
  971. List<double> csRate = new List<double>();
  972. List<List<List<string>>> opt = new List<List<List<string>>>();
  973. foreach (ExamClassResult classResult in examClassResults)
  974. {
  975. double classSrate = 0;
  976. if (classResult.subjectId.Equals(subject.id))
  977. {
  978. foreach (List<List<string>> op in classResult.ans)
  979. {
  980. opt.Add(op);
  981. }
  982. //记录缺考学生索引位置
  983. int index = 0;
  984. foreach (List<double> scores in classResult.studentScores)
  985. {
  986. List<double> newScores = new List<double>();
  987. int count = 0;
  988. foreach (double sc in scores)
  989. {
  990. newScores.Add(sc > -1 ? sc : 0);
  991. if (sc == -1)
  992. {
  993. count++;
  994. }
  995. }
  996. if (count == scores.Count)
  997. {
  998. if (!lostStu.Contains(classResult.studentIds[index])) {
  999. lostStu.Add(classResult.studentIds[index]);
  1000. }
  1001. //mcount++;
  1002. }
  1003. classSrate += newScores.Sum();
  1004. score += newScores.Sum();
  1005. result.studentScores.Add(newScores);
  1006. index++;
  1007. }
  1008. //处理班级信息
  1009. ClassRange range = new ClassRange();
  1010. range.id = classResult.info.id;
  1011. range.name = classResult.info.name;
  1012. range.gradeId = classResult.gradeId;
  1013. List<int> ran = new List<int>();
  1014. int stuCount = classResult.studentIds.Count;
  1015. Count += stuCount;
  1016. if (m == 0)
  1017. {
  1018. ran.Add(0);
  1019. ran.Add(stuCount - 1);
  1020. }
  1021. else
  1022. {
  1023. ran.Add(Count - stuCount);
  1024. ran.Add(Count - 1);
  1025. }
  1026. m++;
  1027. range.range = ran;
  1028. classRanges.Add(range);
  1029. //处理学生ID
  1030. foreach (string id in classResult.studentIds)
  1031. {
  1032. result.studentIds.Add(id);
  1033. }
  1034. if (allScore > 0)
  1035. {
  1036. csRate.Add(classResult.studentIds.Count > 0 ? Math.Round(classSrate * 1.0 / classResult.studentIds.Count, 2) : 0 / allScore);
  1037. }
  1038. else
  1039. {
  1040. csRate.Add(0);
  1041. }
  1042. //powSum += Math.Pow(classSrate - result.average, 2);
  1043. //处理选项计数内容
  1044. }
  1045. }
  1046. await examRecordCount(info, subject, _dingDing, no, result, examClassResults, _azureCosmos);
  1047. result.record = getMore(info, no, opt);
  1048. result.average = result.studentIds.Count > 0 ? Math.Round(score * 1.0 / result.studentIds.Count, 2) : 0;
  1049. double stand = 0;
  1050. int sco = 0;
  1051. foreach (ExamClassResult classResult in examClassResults)
  1052. {
  1053. //double classSrate = 0;
  1054. if (classResult.subjectId.Equals(subject.id))
  1055. {
  1056. stand += classResult.standard;
  1057. sco++;
  1058. }
  1059. }
  1060. result.standard = sco > 0 ? Math.Round(stand / sco, 2) : 0;
  1061. result.csRate = csRate;
  1062. result.lostStus = lostStu;
  1063. result.sRate = allScore > 0 ? Math.Round(result.average / allScore * 100, 2) : 0;
  1064. result.classes = classRanges;
  1065. result.code = "ExamResult-" + info.id;
  1066. result.school = info.school;
  1067. result.id = subject.id;
  1068. result.examId = info.id;
  1069. result.subjectId = subject.id;
  1070. result.year = info.year;
  1071. result.paper = info.papers[no];
  1072. //result.point = info.papers[j].point;
  1073. result.scope = info.scope;
  1074. result.name = info.name;
  1075. result.time = info.startTime;
  1076. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").UpsertItemAsync(result, new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}"));
  1077. }
  1078. public class Settlement
  1079. {
  1080. public double rate { get; set; }
  1081. public double score { get; set; }
  1082. public List<string> stus { get; set; } = new List<string>();
  1083. public int total { get; set; }
  1084. }
  1085. }
  1086. }