TriggerExam.cs 61 KB

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