TriggerExam.cs 77 KB

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