TriggerExam.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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.Helper.Common.CollectionHelper;
  13. using TEAMModelOS.SDK.Models;
  14. using TEAMModelOS.SDK.Models.Cosmos;
  15. using TEAMModelOS.SDK.Models.Cosmos.Common;
  16. namespace TEAMModelFunction
  17. {
  18. public class TriggerExam
  19. {
  20. public static async void Trigger(AzureCosmosFactory _azureCosmos, AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
  21. CosmosClient client, Document input ,string code,long stime,long etime, string school)
  22. {
  23. ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(input.Id, new Azure.Cosmos.PartitionKey($"{code}"));
  24. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  25. List<ExamSubject> examSubjects = new List<ExamSubject>();
  26. if (info.scope.Equals("teacher", StringComparison.OrdinalIgnoreCase) || info.scope.Equals("private", StringComparison.OrdinalIgnoreCase))
  27. {
  28. await foreach (var item in client.GetContainer("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}") }))
  29. {
  30. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  31. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  32. {
  33. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  34. {
  35. examClassResults.Add(obj.ToObject<ExamClassResult>());
  36. }
  37. }
  38. }
  39. }
  40. else {
  41. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: $"select value(c) from c where c.examId = '{info.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamClassResult-{school}") }))
  42. {
  43. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  44. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  45. {
  46. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  47. {
  48. examClassResults.Add(obj.ToObject<ExamClassResult>());
  49. }
  50. }
  51. }
  52. }
  53. List<ChangeRecord> records = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", info.progress } });
  54. //处理科目信息
  55. List<string> sub = new List<string>();
  56. foreach (ExamSubject subject in info.subjects)
  57. {
  58. sub.Add(subject.id);
  59. }
  60. //ChangeRecord record = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ChangeRecord>(input.Id, new Azure.Cosmos.PartitionKey($"{info.progress}"));
  61. switch (info.progress)
  62. {
  63. case "pending":
  64. var message = new ServiceBusMessage(new { id = input.Id, progress = "going", code = code }.ToJsonString());
  65. message.ApplicationProperties.Add("name", "Exam");
  66. if (records.Count > 0)
  67. {
  68. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", records[0].sequenceNumber);
  69. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", message, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  70. records[0].sequenceNumber = start;
  71. await _azureStorage.SaveOrUpdate<ChangeRecord>(records[0]);
  72. //await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(record, record.id, new Azure.Cosmos.PartitionKey($"{record.code}"));
  73. }
  74. else
  75. {
  76. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", message, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  77. ChangeRecord changeRecord = new ChangeRecord
  78. {
  79. RowKey = input.Id,
  80. PartitionKey = "pending",
  81. sequenceNumber = start,
  82. msgId = message.MessageId
  83. };
  84. await _azureStorage.Save<ChangeRecord>(changeRecord);
  85. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  86. }
  87. break;
  88. case "going":
  89. ActivityData data;
  90. if (info.scope == "school")
  91. {
  92. data = new ActivityData
  93. {
  94. id = info.id,
  95. code = $"Activity-{info.school}",
  96. type = "exam",
  97. name = info.name,
  98. startTime = info.startTime,
  99. endTime = info.endTime,
  100. scode = info.code,
  101. scope = info.scope,
  102. classes = info.classes.IsNotEmpty() ? info.classes : new List<string> { "" },
  103. tmdids = new List<string> { "" },
  104. progress = "going",
  105. subjects = sub
  106. };
  107. await client.GetContainer("TEAMModelOS", "School").UpsertItemAsync<ActivityData>(data, new Azure.Cosmos.PartitionKey(data.code));
  108. }
  109. else if (info.scope == "private")
  110. {
  111. data = new ActivityData
  112. {
  113. id = info.id,
  114. code = $"Activity-Common",
  115. type = "exam",
  116. name = info.name,
  117. startTime = info.startTime,
  118. endTime = info.endTime,
  119. scode = info.code,
  120. scope = info.scope,
  121. progress = "going",
  122. classes = info.classes.IsNotEmpty() ? info.classes : new List<string> { "" },
  123. tmdids = new List<string> { "" },
  124. subjects = sub
  125. };
  126. await client.GetContainer("TEAMModelOS", "Teacher").UpsertItemAsync<ActivityData>(data, new Azure.Cosmos.PartitionKey(data.code));
  127. }
  128. (List<string> tmdids, List<Students> students) = await TriggerStuActivity.GetStuList(client, info.classes, info.school);
  129. List<StuActivity> stuActivities = new List<StuActivity>();
  130. List<StuActivity> tmdActivities = new List<StuActivity>();
  131. if (tmdids.IsNotEmpty())
  132. {
  133. tmdids.ForEach(x => {
  134. tmdActivities.Add(new StuActivity
  135. {
  136. pk = "Activity",
  137. id = info.id,
  138. code = $"Activity-{x}",
  139. type = "survey",
  140. name = info.name,
  141. startTime = info.startTime,
  142. endTime = info.endTime,
  143. scode = info.code,
  144. scope = info.scope,
  145. school = info.school,
  146. creatorId = info.creatorId,
  147. subjects = new List<string> { "" }
  148. });
  149. });
  150. }
  151. if (students.IsNotEmpty())
  152. {
  153. students.ForEach(x => {
  154. stuActivities.Add(new StuActivity
  155. {
  156. pk = "Activity",
  157. id = info.id,
  158. code = $"Activity-{info.school}-{x}",
  159. type = "survey",
  160. name = info.name,
  161. startTime = info.startTime,
  162. endTime = info.endTime,
  163. scode = info.code,
  164. scope = info.scope,
  165. school = info.school,
  166. creatorId = info.creatorId,
  167. subjects = new List<string> { "" }
  168. });
  169. });
  170. }
  171. await TriggerStuActivity.SaveStuActivity(client, stuActivities, tmdActivities);
  172. if (examClassResults.Count == 0)
  173. {
  174. foreach (string cla in info.classes)
  175. {
  176. int m = 0;
  177. foreach (ExamSubject subject in info.subjects)
  178. {
  179. string classCode = "";
  180. if (string.IsNullOrEmpty(info.school) || !info.scope.Equals("school",StringComparison.OrdinalIgnoreCase))
  181. {
  182. classCode = "ExamClassResult-" + info.creatorId;
  183. }
  184. else {
  185. classCode = "ExamClassResult-" + info.school;
  186. }
  187. ExamClassResult result = new ExamClassResult
  188. {
  189. code = classCode,
  190. examId = info.id,
  191. id = Guid.NewGuid().ToString(),
  192. subjectId = subject.id,
  193. year = info.year,
  194. scope = info.scope
  195. };
  196. result.info.id = cla;
  197. List<string> ans = new List<string>();
  198. List<double> ansPoint = new List<double>();
  199. List<string> ids = new List<string>();
  200. foreach (double p in info.papers[m].point)
  201. {
  202. //ans.Add(new List<string>());
  203. ansPoint.Add(-1);
  204. }
  205. var sresponse = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"Class-{info.school}"));
  206. if (sresponse.Status == 200)
  207. {
  208. using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
  209. Class classroom = json.ToObject<Class>();
  210. //result.info.id = classroom.id;
  211. result.info.name = classroom.name;
  212. result.gradeId = classroom.gradeId;
  213. //处理班级人数
  214. await foreach (var item in client.GetContainer("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}") }))
  215. {
  216. using var json_stu = await JsonDocument.ParseAsync(item.ContentStream);
  217. if (json_stu.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  218. {
  219. var accounts = json_stu.RootElement.GetProperty("Documents").EnumerateArray();
  220. while (accounts.MoveNext())
  221. {
  222. JsonElement account = accounts.Current;
  223. ids.Add(account.GetProperty("id").GetString());
  224. }
  225. }
  226. }
  227. }
  228. if (info.scope.Equals("private", StringComparison.OrdinalIgnoreCase))
  229. {
  230. var stuResponse = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"StuList"));
  231. if (stuResponse.Status == 200) {
  232. using var json = await JsonDocument.ParseAsync(stuResponse.ContentStream);
  233. StuList stuList = json.ToObject<StuList>();
  234. //result.info.id = stuList.id;
  235. result.info.name = stuList.name;
  236. //处理发布对象为自选名单(个人)
  237. foreach (Students stus in stuList.students)
  238. {
  239. ids.Add(stus.id);
  240. }
  241. if (stuList.tmids.Count > 0)
  242. {
  243. foreach (string tid in stuList.tmids)
  244. {
  245. ids.Add(tid);
  246. }
  247. }
  248. }
  249. }
  250. else {
  251. var stuResponse = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"StuList-{info.school}"));
  252. if (stuResponse.Status == 200)
  253. {
  254. using var json = await JsonDocument.ParseAsync(stuResponse.ContentStream);
  255. StuList stuList = json.ToObject<StuList>();
  256. //result.info.id = stuList.id;
  257. result.info.name = stuList.name;
  258. //处理发布对象为自选名单(校本)
  259. foreach (Students stus in stuList.students)
  260. {
  261. ids.Add(stus.id);
  262. }
  263. }
  264. }
  265. foreach (string stu in ids)
  266. {
  267. result.studentIds.Add(stu);
  268. result.studentAnswers.Add(ans);
  269. result.studentScores.Add(ansPoint);
  270. result.sum.Add(0);
  271. }
  272. //result.progress = info.progress;
  273. result.school = info.school;
  274. m++;
  275. await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(result, new Azure.Cosmos.PartitionKey($"{result.code}"));
  276. }
  277. }
  278. // 发送信息通知
  279. var messageEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = code }.ToJsonString());
  280. messageEnd.ApplicationProperties.Add("name", "Exam");
  281. if (records.Count > 0)
  282. {
  283. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  284. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", records[0].sequenceNumber);
  285. records[0].sequenceNumber = end;
  286. await _azureStorage.SaveOrUpdate<ChangeRecord>(records[0]);
  287. //await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(record, record.id, new Azure.Cosmos.PartitionKey($"{record.code}"));
  288. }
  289. else
  290. {
  291. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  292. ChangeRecord changeRecord = new ChangeRecord
  293. {
  294. RowKey = input.Id,
  295. PartitionKey = "going",
  296. sequenceNumber = end,
  297. msgId = messageEnd.MessageId
  298. };
  299. await _azureStorage.Save<ChangeRecord>(changeRecord);
  300. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  301. }
  302. }
  303. else
  304. {
  305. //处理单科结算时科目与试卷信息匹配的问题
  306. int gno = 0;
  307. foreach (ExamSubject subject in info.subjects)
  308. {
  309. if (subject.classCount == info.classes.Count)
  310. {
  311. await createClassResultAsync(info, examClassResults, subject, gno,_azureCosmos);
  312. }
  313. gno++;
  314. }
  315. }
  316. break;
  317. case "finish":
  318. int fno = 0;
  319. foreach (ExamSubject subject in info.subjects)
  320. {
  321. await createClassResultAsync(info, examClassResults, subject, fno, _azureCosmos);
  322. fno++;
  323. }
  324. //计算单次考试简易统计信息
  325. List<ExamResult> examResults = new List<ExamResult>();
  326. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamResult>(
  327. queryText: $"select value(c) from c where c.examId = '{info.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}") }))
  328. {
  329. examResults.Add(item);
  330. }
  331. //记录某次考试所有学生得分总分
  332. double score = 0;
  333. double allScore = 0;
  334. int stuCount = 0;
  335. List<string> losStu = new List<string>();
  336. //先与第一个值取并集
  337. if (examResults.Count >0 ) {
  338. losStu.Union(examResults[0].lostStus);
  339. foreach (ExamResult examResult in examResults)
  340. {
  341. if (info.id == examResult.examId)
  342. {
  343. foreach (List<double> sc in examResult.studentScores)
  344. {
  345. score += sc.Sum();
  346. }
  347. stuCount = examResult.studentIds.Count;
  348. }
  349. //取交集
  350. losStu = losStu.Intersect(examResult.lostStus).ToList();
  351. }
  352. }
  353. double ascore = stuCount > 0 ? Math.Round(score * 1.0 / stuCount, 2) : 0;
  354. foreach (PaperSimple simple in info.papers)
  355. {
  356. allScore += simple.point.Sum();
  357. }
  358. info.sRate = allScore > 0 ? Math.Round(ascore / allScore * 100,2) : 0;
  359. info.lostStu = losStu;
  360. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync<ExamInfo>(info, info.id, new Azure.Cosmos.PartitionKey(info.code));
  361. //ActivityData data;
  362. if (info.scope == "school")
  363. {
  364. data = new ActivityData
  365. {
  366. id = info.id,
  367. code = $"Activity-{info.school}",
  368. type = "exam",
  369. name = info.name,
  370. startTime = info.startTime,
  371. endTime = info.endTime,
  372. scode = info.code,
  373. scope = info.scope,
  374. progress = "finish",
  375. classes = info.classes.IsNotEmpty() ? info.classes : new List<string> { "" },
  376. tmdids = new List<string> { "" },
  377. subjects = sub
  378. };
  379. await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<ActivityData>(data, info.id, new Azure.Cosmos.PartitionKey(data.code));
  380. }
  381. else if (info.scope == "private")
  382. {
  383. data = new ActivityData
  384. {
  385. id = info.id,
  386. code = $"Activity-Common",
  387. type = "exam",
  388. name = info.name,
  389. startTime = info.startTime,
  390. endTime = info.endTime,
  391. scode = info.code,
  392. scope = info.scope,
  393. progress = "finish",
  394. classes = info.classes.IsNotEmpty() ? info.classes : new List<string> { "" },
  395. tmdids = new List<string> { "" },
  396. subjects = sub
  397. };
  398. await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<ActivityData>(data, info.id, new Azure.Cosmos.PartitionKey(data.code));
  399. }
  400. break;
  401. }
  402. }
  403. public static async Task createClassResultAsync(ExamInfo info, List<ExamClassResult> examClassResults, ExamSubject subject, int no, AzureCosmosFactory _azureCosmos)
  404. {
  405. //保证试卷信息与科目信息同步
  406. ExamResult result = new ExamResult();
  407. //人数总和
  408. int Count = 0;
  409. int m = 0;
  410. double score = 0;
  411. double allScore = info.papers[no].point.Sum();
  412. List<ClassRange> classRanges = new List<ClassRange>();
  413. List<string> lostStu = new List<string>();
  414. List<double> csRate = new List<double>();
  415. foreach (ExamClassResult classResult in examClassResults)
  416. {
  417. double classSrate = 0;
  418. if (classResult.subjectId.Equals(subject.id))
  419. {
  420. //记录缺考学生索引位置
  421. int index = 0;
  422. foreach (List<double> scores in classResult.studentScores)
  423. {
  424. List<double> newScores = new List<double>();
  425. int count = 0;
  426. foreach (double sc in scores) {
  427. newScores.Add(sc > -1 ? sc : 0);
  428. if(sc == -1) {
  429. count++;
  430. }
  431. }
  432. if (count == scores.Count) {
  433. lostStu.Add(classResult.studentIds[index]);
  434. //mcount++;
  435. }
  436. classSrate += newScores.Sum();
  437. score += newScores.Sum();
  438. result.studentScores.Add(newScores);
  439. index++;
  440. }
  441. //处理班级信息
  442. ClassRange range = new ClassRange();
  443. range.id = classResult.info.id;
  444. range.name = classResult.info.name;
  445. range.gradeId = classResult.gradeId;
  446. List<int> ran = new List<int>();
  447. int stuCount = classResult.studentIds.Count;
  448. Count += stuCount;
  449. if (m == 0)
  450. {
  451. ran.Add(0);
  452. ran.Add(stuCount - 1);
  453. }
  454. else
  455. {
  456. ran.Add(Count - stuCount);
  457. ran.Add(Count - 1);
  458. }
  459. m++;
  460. range.range = ran;
  461. classRanges.Add(range);
  462. //处理学生ID
  463. foreach (string id in classResult.studentIds)
  464. {
  465. result.studentIds.Add(id);
  466. }
  467. csRate.Add(result.studentIds.Count > 0 ? Math.Round(classSrate * 1.0 / classResult.studentIds.Count, 2) : 0 / allScore);
  468. }
  469. }
  470. result.csRate = csRate;
  471. result.lostStus = lostStu;
  472. result.sRate =result.studentIds.Count> 0 ? Math.Round(score *1.0 / result.studentIds.Count ,2 ): 0 / allScore;
  473. result.classes = classRanges;
  474. result.code = "ExamResult-" + info.id;
  475. result.school = info.school;
  476. result.id = subject.id;
  477. result.examId = info.id;
  478. result.subjectId = subject.id;
  479. result.year = info.year;
  480. result.paper = info.papers[no];
  481. //result.point = info.papers[j].point;
  482. result.scope = info.scope;
  483. result.name = info.name;
  484. result.time = info.startTime;
  485. await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Common").UpsertItemAsync(result, new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}"));
  486. }
  487. }
  488. }