TriggerExam.cs 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  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))
  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. int total = examResults[0].studentIds.Count;
  421. //先与第一个值取并集
  422. if (examResults.Count > 0)
  423. {
  424. losStu = losStu.Union(examResults[0].lostStus).ToList();
  425. foreach (ExamResult examResult in examResults)
  426. {
  427. if (info.id == examResult.examId)
  428. {
  429. foreach (List<double> sc in examResult.studentScores)
  430. {
  431. score += sc.Sum();
  432. }
  433. stuCount = examResult.studentIds.Count;
  434. }
  435. //powSum += Math.Pow(score - examResult.studentIds.Count > 0 ? Math.Round(score * 1.0 / examResult.studentIds.Count, 2) : 0, 2);
  436. //取交集
  437. losStu = losStu.Intersect(examResult.lostStus).ToList();
  438. }
  439. }
  440. double NewsRateScore = stuCount > 0 ? Math.Round(score * 1.0 / stuCount, 2) : 0;
  441. foreach (PaperSimple simple in info.papers)
  442. {
  443. allScore += simple.point.Sum();
  444. }
  445. //计算全科标准差
  446. foreach (string id in examResults[0].studentIds)
  447. {
  448. double sc = 0;
  449. foreach (ExamResult result in examResults)
  450. {
  451. sc += result.studentScores[result.studentIds.IndexOf(id)].Sum();
  452. }
  453. powSum += Math.Pow(sc - NewsRateScore, 2);
  454. }
  455. info.standard = Math.Round(total > 0 ? Math.Pow(powSum / total, 0.5) : 0, 2);
  456. double NewsRate = allScore > 0 ? Math.Round(NewsRateScore / allScore * 100, 2) : 0;
  457. //info.lostStu = losStu;
  458. /*//补充历史数据的容器名称
  459. if (string.IsNullOrEmpty(info.cn)) {
  460. if (info.scope.Equals("school"))
  461. {
  462. info.cn = info.school;
  463. }
  464. else {
  465. info.cn = info.creatorId;
  466. }
  467. }*/
  468. //判断均分是否发生变化,便于实时的更新评测基本信息
  469. if (info.sRate != NewsRate || info.average != NewsRateScore || info.sStatus != newStatus)
  470. {
  471. info.sRate = NewsRate;
  472. info.average = NewsRateScore;
  473. info.sStatus = newStatus;
  474. info.lostStu = losStu;
  475. info.stuCount = total;
  476. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ExamInfo>(info, info.id, new Azure.Cosmos.PartitionKey(info.code));
  477. }
  478. }
  479. catch (Exception e)
  480. {
  481. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测finish状态异常{e.Message}\n{e.StackTrace}", GroupNames.成都开发測試群組);
  482. }
  483. break;
  484. }
  485. }
  486. }
  487. catch (CosmosException e)
  488. {
  489. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDB异常{e.Message}\n{e.Status}", GroupNames.成都开发測試群組);
  490. } catch (Exception e) {
  491. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-评测结算异常{e.Message}\n{e.StackTrace}", GroupNames.成都开发測試群組);
  492. }
  493. }
  494. //处理全部学生选题计数
  495. public static async Task examRecordCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, ExamResult result, List<ExamClassResult> classResults, AzureCosmosFactory _azureCosmos)
  496. {
  497. try
  498. {
  499. List<double> scores = new List<double>();
  500. foreach (List<double> sc in result.studentScores)
  501. {
  502. scores.Add(sc.Sum());
  503. }
  504. //确定高分组 最低分数
  505. scores.Sort((s1, s2) => { return s2.CompareTo(s1); });
  506. double rhwCount = Math.Floor(scores.Count * 0.27);
  507. double rhw = rhwCount > 0 ? scores[int.Parse(rhwCount.ToString("0"))] : 0;
  508. //确定低分组 最高分数
  509. //scores.Sort((s1, s2) => { return s1.CompareTo(s2); });
  510. double rhlCount = Math.Ceiling(scores.Count * 0.73);
  511. double rhl = rhlCount > 0 ? scores[int.Parse(rhlCount.ToString("0")) - 1] : 0;
  512. //存放高分组学生ID
  513. List<string> phId = new List<string>();
  514. List<string> plId = new List<string>();
  515. List<List<List<string>>> opth = new List<List<List<string>>>();
  516. List<List<List<string>>> optl = new List<List<List<string>>>();
  517. await knowledgeCount(info, subject, _dingDing, no, classResults, rhwCount, rhw, rhlCount, rhl, _azureCosmos);
  518. await fieldCount(info, subject, _dingDing, no, classResults, rhwCount, rhw, rhlCount, rhl, _azureCosmos);
  519. int PHCount = 0;
  520. int PLCount = 0;
  521. foreach (ExamClassResult classResult in classResults)
  522. {
  523. if (classResult.subjectId.Equals(subject.id))
  524. {
  525. foreach (string id in classResult.studentIds)
  526. {
  527. int index = classResult.studentIds.IndexOf(id);
  528. if (classResult.studentScores.Count > 0)
  529. {
  530. if (classResult.studentScores[index].Sum() >= rhw && PHCount < rhwCount)
  531. {
  532. if (classResult.ans.Count > 0)
  533. {
  534. opth.Add(classResult.ans[index]);
  535. PHCount++;
  536. continue;
  537. }
  538. }
  539. if (classResult.studentScores[index].Sum() <= rhl && PLCount < (scores.Count - rhlCount))
  540. {
  541. if (classResult.ans.Count > 0)
  542. {
  543. optl.Add(classResult.ans[index]);
  544. PLCount++;
  545. continue;
  546. }
  547. }
  548. }
  549. }
  550. }
  551. }
  552. result.phc = getMore(info, no, opth);
  553. result.plc = getMore(info, no, optl);
  554. }
  555. catch (Exception ex)
  556. {
  557. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测作答记录结算异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  558. }
  559. }
  560. public static async Task<List<RGroupList>> Activity(CoreAPIHttpService _coreAPIHttpService, ExamInfo info, List<string> classes,CosmosClient client, DingDing _dingDing, List<string> sub) {
  561. List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
  562. if (info.groupLists.Count > 0)
  563. {
  564. var group = info.groupLists;
  565. foreach (var gp in group)
  566. {
  567. foreach (KeyValuePair<string, List<string>> pp in gp)
  568. {
  569. ps.Add((pp.Key, pp.Value));
  570. }
  571. }
  572. }
  573. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService,client, _dingDing, classes, info.school, ps);
  574. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  575. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  576. List<StuActivity> stuActivities = new List<StuActivity>();
  577. List<StuActivity> tmdActivities = new List<StuActivity>();
  578. if (addTmdidsCls.IsNotEmpty())
  579. {
  580. addTmdidsCls.ForEach(x =>
  581. {
  582. HashSet<string> classIds = new HashSet<string>();
  583. classLists.ForEach(z => {
  584. z.members.ForEach(y => {
  585. if (y.id.Equals(x.id) && y.type == 1)
  586. {
  587. classIds.Add(z.id);
  588. }
  589. });
  590. });
  591. tmdActivities.Add(new StuActivity
  592. {
  593. pk = "Activity",
  594. id = info.id,
  595. code = $"Activity-{x.id}",
  596. type = "Exam",
  597. name = info.name,
  598. source = info.source,
  599. startTime = info.startTime,
  600. endTime = info.endTime,
  601. scode = info.code,
  602. scope = info.scope,
  603. school = info.school,
  604. creatorId = info.creatorId,
  605. subjects = sub,
  606. blob = null,
  607. owner = info.owner,
  608. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  609. taskStatus = -1,
  610. ext = new Dictionary<string, JsonElement>() { { "type",info.type.ToJsonString().ToObject<JsonElement>() },{ "subjects", info.subjects.ToJsonString().ToObject<JsonElement>() } },
  611. //sStatus = info.sStatus,
  612. classIds = classIds.ToList()
  613. }); ;
  614. });
  615. }
  616. if (addStudentsCls.IsNotEmpty())
  617. {
  618. addStudentsCls.ForEach(x =>
  619. {
  620. HashSet<string> classIds = new HashSet<string>();
  621. classLists.ForEach(z => {
  622. z.members.ForEach(y => {
  623. if (y.id.Equals(x.id) && y.code.Equals(info.school) && y.type == 2)
  624. {
  625. classIds.Add(z.id);
  626. }
  627. });
  628. });
  629. stuActivities.Add(new StuActivity
  630. {
  631. pk = "Activity",
  632. id = info.id,
  633. code = $"Activity-{x.code.Replace("Base-", "")}-{x.id}",
  634. type = "Exam",
  635. name = info.name,
  636. source = info.source,
  637. startTime = info.startTime,
  638. endTime = info.endTime,
  639. scode = info.code,
  640. scope = info.scope,
  641. school = info.school,
  642. creatorId = info.creatorId,
  643. subjects = sub,
  644. blob = null,
  645. owner = info.owner,
  646. classIds = classIds.ToList(),
  647. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  648. ext = new Dictionary<string, JsonElement>() { { "type", info.type.ToJsonString().ToObject<JsonElement>() }, { "subjects", info.subjects.ToJsonString().ToObject<JsonElement>() } },
  649. taskStatus = -1
  650. //sStatus = info.sStatus,
  651. });
  652. });
  653. }
  654. await ActivityService.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities, null);
  655. return classLists;
  656. }
  657. public static async Task knowledgeCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, List<ExamClassResult> classResults,
  658. double rhwCount, double rhw, double rhlCount, double rhl, AzureCosmosFactory _azureCosmos)
  659. {
  660. try
  661. {
  662. int phcount = 0;
  663. int plcount = 0;
  664. //存放并去重知识点
  665. HashSet<string> kname = new HashSet<string>();
  666. if (info.papers[no].knowledge.Count > 0)
  667. {
  668. info.papers[no].knowledge.ForEach(kno =>
  669. {
  670. kno.ForEach(k =>
  671. {
  672. kname.Add(k);
  673. });
  674. });
  675. List<string> knowledgeName = new List<string>();
  676. foreach (string cla in kname)
  677. {
  678. knowledgeName.Add(cla);
  679. }
  680. for (int k = 0; k < knowledgeName.Count; k++)
  681. {
  682. if (null == knowledgeName[k])
  683. {
  684. knowledgeName.Remove(knowledgeName[k]);
  685. }
  686. }
  687. foreach (ExamClassResult classResult in classResults)
  688. {
  689. if (classResult.subjectId.Equals(subject.id))
  690. {
  691. //List<int> phc = new List<int>();
  692. List<int> ph = new List<int>();
  693. List<int> pl = new List<int>();
  694. List<int> pc = new List<int>();
  695. List<double> persent = new List<double>();
  696. for (int i = 0; i < knowledgeName.Count; i++)
  697. {
  698. //初始化单个知识点得分
  699. double score = 0;
  700. double allScore = 0;
  701. int n = 0;
  702. int phCount = 0;
  703. int plCount = 0;
  704. int pCount = 0;
  705. foreach (List<string> str in info.papers[no].knowledge)
  706. {
  707. if (str.Contains(knowledgeName[i]))
  708. {
  709. var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
  710. allScore += info.papers[no].point.Count > 0 ? info.papers[no].point[n] * itemPersent : 0;
  711. foreach (string id in classResult.studentIds)
  712. {
  713. int index = classResult.studentIds.IndexOf(id);
  714. if (classResult.studentScores.Count > 0)
  715. {
  716. if (classResult.studentScores[index].Count > 0)
  717. {
  718. score += classResult.studentScores[index][n] == -1 ? 0 : classResult.studentScores[index][n];
  719. if (classResult.studentScores[index].Sum() >= rhw && phcount < rhwCount)
  720. {
  721. if (classResult.studentScores[index][n] <= 0)
  722. {
  723. phCount++;
  724. }
  725. phcount++;
  726. continue;
  727. }
  728. if (classResult.studentScores[index].Sum() <= rhl && plcount < (info.stuCount - rhlCount))
  729. {
  730. if (classResult.studentScores[index][n] <= 0)
  731. {
  732. plCount++;
  733. }
  734. plcount++;
  735. continue;
  736. }
  737. if (classResult.studentScores[index][n] <= 0)
  738. {
  739. pCount++;
  740. }
  741. }
  742. }
  743. }
  744. }
  745. n++;
  746. }
  747. pc.Add(pCount);
  748. ph.Add(phCount);
  749. pl.Add(plCount);
  750. double per = classResult.studentIds.Count > 0 ? Math.Round(score / classResult.studentIds.Count, 2) : 0;
  751. persent.Add(allScore > 0 ? per / allScore : 0);
  752. }
  753. classResult.phc = ph;
  754. classResult.plc = pl;
  755. classResult.pc = pc;
  756. classResult.krate = persent;
  757. }
  758. //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new Azure.Cosmos.PartitionKey($"{classResult.code}"));
  759. }
  760. }
  761. }
  762. catch (Exception ex)
  763. {
  764. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测知识点结算异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  765. }
  766. }
  767. public static async Task fieldCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, List<ExamClassResult> classResults,
  768. double rhwCount, double rhw, double rhlCount, double rhl, AzureCosmosFactory _azureCosmos)
  769. {
  770. try
  771. {
  772. int phcount = 0;
  773. int plcount = 0;
  774. //存放并去重知识点
  775. List<int> knowledgeName = new List<int>() { 1,2,3,4,5,6};
  776. /* knowledgeName.Add(1);
  777. knowledgeName.Add(2);
  778. knowledgeName.Add(3);
  779. knowledgeName.Add(4);
  780. knowledgeName.Add(5);
  781. knowledgeName.Add(6);*/
  782. foreach (ExamClassResult classResult in classResults)
  783. {
  784. if (classResult.subjectId.Equals(subject.id))
  785. {
  786. //List<int> phc = new List<int>();
  787. List<int> ph = new List<int>();
  788. List<int> pl = new List<int>();
  789. List<int> pc = new List<int>();
  790. List<double> persent = new List<double>();
  791. for (int i = 0; i < knowledgeName.Count; i++)
  792. {
  793. //初始化单个知识点得分
  794. double score = 0;
  795. double allScore = 0;
  796. int n = 0;
  797. int phCount = 0;
  798. int plCount = 0;
  799. int pCount = 0;
  800. if (info.papers[no].field.Count > 0)
  801. {
  802. foreach (int str in info.papers[no].field)
  803. {
  804. if (str == knowledgeName[i])
  805. {
  806. var itemPersent = 1;
  807. allScore += info.papers[no].point.Count > 0 ? info.papers[no].point[n] * itemPersent : 0;
  808. foreach (string id in classResult.studentIds)
  809. {
  810. int index = classResult.studentIds.IndexOf(id);
  811. if (classResult.studentScores.Count > 0)
  812. {
  813. if (classResult.studentScores[index].Count > 0)
  814. {
  815. score += classResult.studentScores[index][n] == -1 ? 0 : classResult.studentScores[index][n];
  816. if (classResult.studentScores[index].Sum() >= rhw && phcount < rhwCount)
  817. {
  818. if (classResult.studentScores[index][n] <= 0)
  819. {
  820. phCount++;
  821. }
  822. phcount++;
  823. continue;
  824. }
  825. if (classResult.studentScores[index].Sum() <= rhl && plcount < (info.stuCount - rhlCount))
  826. {
  827. if (classResult.studentScores[index][n] <= 0)
  828. {
  829. plCount++;
  830. }
  831. plcount++;
  832. continue;
  833. }
  834. if (classResult.studentScores[index][n] <= 0)
  835. {
  836. pCount++;
  837. }
  838. }
  839. }
  840. }
  841. }
  842. n++;
  843. }
  844. pc.Add(pCount);
  845. ph.Add(phCount);
  846. pl.Add(plCount);
  847. double per = classResult.studentIds.Count > 0 ? Math.Round(score / classResult.studentIds.Count, 2) : 0;
  848. persent.Add(allScore > 0 ? per / allScore : 0);
  849. }
  850. }
  851. classResult.fphc = ph;
  852. classResult.fplc = pl;
  853. classResult.fpc = pc;
  854. classResult.frate = persent;
  855. }
  856. //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new Azure.Cosmos.PartitionKey($"{classResult.code}"));
  857. }
  858. }
  859. catch (Exception ex)
  860. {
  861. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测认知层次结算异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  862. }
  863. }
  864. //处理选题计数
  865. public static List<Dictionary<string, int>> getMore(ExamInfo info, int no, List<List<List<string>>> list)
  866. {
  867. List<Dictionary<string, int>> recorde = new List<Dictionary<string, int>>();
  868. try
  869. {
  870. for (int i = 0; i < info.papers[no].answers.Count; i++)
  871. {
  872. if (info.papers[no].answers[i].Count <= 0)
  873. {
  874. recorde.Add(new Dictionary<string, int>());
  875. continue;
  876. }
  877. Dictionary<string, int> optCount = new Dictionary<string, int>();
  878. foreach (List<List<string>> stu in list)
  879. {
  880. if (stu.Count == info.papers[no].answers.Count)
  881. {
  882. var item = stu[i];
  883. foreach (string opt in item)
  884. {
  885. if (optCount.ContainsKey(opt))
  886. {
  887. optCount[opt] = optCount[opt] + 1;
  888. }
  889. else
  890. {
  891. optCount[opt] = 1;
  892. }
  893. }
  894. }
  895. }
  896. recorde.Add(optCount);
  897. }
  898. return recorde;
  899. }
  900. catch (Exception)
  901. {
  902. return recorde;
  903. }
  904. }
  905. public static async Task createClassResultAsync(ExamInfo info, List<ExamClassResult> examClassResults, ExamSubject subject, int no, AzureCosmosFactory _azureCosmos, DingDing _dingDing, AzureStorageFactory _azureStorage)
  906. {
  907. //保证试卷信息与科目信息同步
  908. ExamResult result = new ExamResult();
  909. //人数总和
  910. int Count = 0;
  911. int m = 0;
  912. double score = 0;
  913. //标准差
  914. double powSum = 0;
  915. double allScore = info.papers[no].point.Sum();
  916. List<ClassRange> classRanges = new List<ClassRange>();
  917. List<string> lostStu = new List<string>();
  918. List<double> csRate = new List<double>();
  919. List<List<List<string>>> opt = new List<List<List<string>>>();
  920. foreach (ExamClassResult classResult in examClassResults)
  921. {
  922. double classSrate = 0;
  923. if (classResult.subjectId.Equals(subject.id))
  924. {
  925. foreach (List<List<string>> op in classResult.ans)
  926. {
  927. opt.Add(op);
  928. }
  929. //记录缺考学生索引位置
  930. int index = 0;
  931. foreach (List<double> scores in classResult.studentScores)
  932. {
  933. List<double> newScores = new List<double>();
  934. int count = 0;
  935. foreach (double sc in scores)
  936. {
  937. newScores.Add(sc > -1 ? sc : 0);
  938. if (sc == -1)
  939. {
  940. count++;
  941. }
  942. }
  943. if (count == scores.Count)
  944. {
  945. if (!lostStu.Contains(classResult.studentIds[index])) {
  946. lostStu.Add(classResult.studentIds[index]);
  947. }
  948. //mcount++;
  949. }
  950. classSrate += newScores.Sum();
  951. score += newScores.Sum();
  952. result.studentScores.Add(newScores);
  953. index++;
  954. }
  955. //处理班级信息
  956. ClassRange range = new ClassRange();
  957. range.id = classResult.info.id;
  958. range.name = classResult.info.name;
  959. range.gradeId = classResult.gradeId;
  960. List<int> ran = new List<int>();
  961. int stuCount = classResult.studentIds.Count;
  962. Count += stuCount;
  963. if (m == 0)
  964. {
  965. ran.Add(0);
  966. ran.Add(stuCount - 1);
  967. }
  968. else
  969. {
  970. ran.Add(Count - stuCount);
  971. ran.Add(Count - 1);
  972. }
  973. m++;
  974. range.range = ran;
  975. classRanges.Add(range);
  976. //处理学生ID
  977. foreach (string id in classResult.studentIds)
  978. {
  979. result.studentIds.Add(id);
  980. }
  981. if (allScore > 0)
  982. {
  983. csRate.Add(classResult.studentIds.Count > 0 ? Math.Round(classSrate * 1.0 / classResult.studentIds.Count, 2) : 0 / allScore);
  984. }
  985. else
  986. {
  987. csRate.Add(0);
  988. }
  989. //powSum += Math.Pow(classSrate - result.average, 2);
  990. //处理选项计数内容
  991. }
  992. }
  993. await examRecordCount(info, subject, _dingDing, no, result, examClassResults, _azureCosmos);
  994. result.record = getMore(info, no, opt);
  995. result.average = result.studentIds.Count > 0 ? Math.Round(score * 1.0 / result.studentIds.Count, 2) : 0;
  996. double stand = 0;
  997. int sco = 0;
  998. foreach (ExamClassResult classResult in examClassResults)
  999. {
  1000. //double classSrate = 0;
  1001. if (classResult.subjectId.Equals(subject.id))
  1002. {
  1003. stand += classResult.standard;
  1004. sco++;
  1005. }
  1006. }
  1007. result.standard = sco > 0 ? Math.Round(stand / sco, 2) : 0;
  1008. result.csRate = csRate;
  1009. result.lostStus = lostStu;
  1010. result.sRate = allScore > 0 ? Math.Round(result.average / allScore * 100, 2) : 0;
  1011. result.classes = classRanges;
  1012. result.code = "ExamResult-" + info.id;
  1013. result.school = info.school;
  1014. result.id = subject.id;
  1015. result.examId = info.id;
  1016. result.subjectId = subject.id;
  1017. result.year = info.year;
  1018. result.paper = info.papers[no];
  1019. //result.point = info.papers[j].point;
  1020. result.scope = info.scope;
  1021. result.name = info.name;
  1022. result.time = info.startTime;
  1023. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").UpsertItemAsync(result, new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}"));
  1024. }
  1025. }
  1026. }