TriggerExam.cs 58 KB

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