TriggerExam.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. if (examClassResults.Count == 0)
  129. {
  130. foreach (string cla in info.classes)
  131. {
  132. int m = 0;
  133. foreach (ExamSubject subject in info.subjects)
  134. {
  135. string classCode = "";
  136. if (string.IsNullOrEmpty(info.school) || !info.scope.Equals("school",StringComparison.OrdinalIgnoreCase))
  137. {
  138. classCode = "ExamClassResult-" + info.creatorId;
  139. }
  140. else {
  141. classCode = "ExamClassResult-" + info.school;
  142. }
  143. ExamClassResult result = new ExamClassResult
  144. {
  145. code = classCode,
  146. examId = info.id,
  147. id = Guid.NewGuid().ToString(),
  148. subjectId = subject.id,
  149. year = info.year,
  150. scope = info.scope
  151. };
  152. result.info.id = cla;
  153. List<string> ans = new List<string>();
  154. List<double> ansPoint = new List<double>();
  155. List<string> ids = new List<string>();
  156. foreach (double p in info.papers[m].point)
  157. {
  158. //ans.Add(new List<string>());
  159. ansPoint.Add(-1);
  160. }
  161. var sresponse = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"Class-{info.school}"));
  162. if (sresponse.Status == 200)
  163. {
  164. using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
  165. Class classroom = json.ToObject<Class>();
  166. //result.info.id = classroom.id;
  167. result.info.name = classroom.name;
  168. result.gradeId = classroom.gradeId;
  169. //处理班级人数
  170. 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}") }))
  171. {
  172. using var json_stu = await JsonDocument.ParseAsync(item.ContentStream);
  173. if (json_stu.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  174. {
  175. var accounts = json_stu.RootElement.GetProperty("Documents").EnumerateArray();
  176. while (accounts.MoveNext())
  177. {
  178. JsonElement account = accounts.Current;
  179. ids.Add(account.GetProperty("id").GetString());
  180. }
  181. }
  182. }
  183. }
  184. if (info.scope.Equals("private", StringComparison.OrdinalIgnoreCase))
  185. {
  186. var stuResponse = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"StuList"));
  187. if (stuResponse.Status == 200) {
  188. using var json = await JsonDocument.ParseAsync(stuResponse.ContentStream);
  189. StuList stuList = json.ToObject<StuList>();
  190. //result.info.id = stuList.id;
  191. result.info.name = stuList.name;
  192. //处理发布对象为自选名单(个人)
  193. foreach (Students students in stuList.students)
  194. {
  195. ids.Add(students.id);
  196. }
  197. if (stuList.tmids.Count > 0)
  198. {
  199. foreach (string tid in stuList.tmids)
  200. {
  201. ids.Add(tid);
  202. }
  203. }
  204. }
  205. }
  206. else {
  207. var stuResponse = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"StuList-{info.school}"));
  208. if (stuResponse.Status == 200)
  209. {
  210. using var json = await JsonDocument.ParseAsync(stuResponse.ContentStream);
  211. StuList stuList = json.ToObject<StuList>();
  212. //result.info.id = stuList.id;
  213. result.info.name = stuList.name;
  214. //处理发布对象为自选名单(校本)
  215. foreach (Students students in stuList.students)
  216. {
  217. ids.Add(students.id);
  218. }
  219. }
  220. }
  221. foreach (string stu in ids)
  222. {
  223. result.studentIds.Add(stu);
  224. result.studentAnswers.Add(ans);
  225. result.studentScores.Add(ansPoint);
  226. result.sum.Add(0);
  227. }
  228. //result.progress = info.progress;
  229. result.school = info.school;
  230. m++;
  231. await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(result, new Azure.Cosmos.PartitionKey($"{result.code}"));
  232. }
  233. }
  234. // 发送信息通知
  235. var messageEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = code }.ToJsonString());
  236. messageEnd.ApplicationProperties.Add("name", "Exam");
  237. if (records.Count > 0)
  238. {
  239. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  240. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", records[0].sequenceNumber);
  241. records[0].sequenceNumber = end;
  242. await _azureStorage.SaveOrUpdate<ChangeRecord>(records[0]);
  243. //await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(record, record.id, new Azure.Cosmos.PartitionKey($"{record.code}"));
  244. }
  245. else
  246. {
  247. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  248. ChangeRecord changeRecord = new ChangeRecord
  249. {
  250. RowKey = input.Id,
  251. PartitionKey = "going",
  252. sequenceNumber = end,
  253. msgId = messageEnd.MessageId
  254. };
  255. await _azureStorage.Save<ChangeRecord>(changeRecord);
  256. //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  257. }
  258. }
  259. else
  260. {
  261. //处理单科结算时科目与试卷信息匹配的问题
  262. int gno = 0;
  263. foreach (ExamSubject subject in info.subjects)
  264. {
  265. if (subject.classCount == info.classes.Count)
  266. {
  267. await createClassResultAsync(info, examClassResults, subject, gno,_azureCosmos);
  268. }
  269. gno++;
  270. }
  271. }
  272. break;
  273. case "finish":
  274. int fno = 0;
  275. foreach (ExamSubject subject in info.subjects)
  276. {
  277. await createClassResultAsync(info, examClassResults, subject, fno, _azureCosmos);
  278. fno++;
  279. }
  280. //计算单次考试简易统计信息
  281. List<ExamResult> examResults = new List<ExamResult>();
  282. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamResult>(
  283. queryText: $"select value(c) from c where c.examId = '{info.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}") }))
  284. {
  285. examResults.Add(item);
  286. }
  287. //记录某次考试所有学生得分总分
  288. double score = 0;
  289. double allScore = 0;
  290. int stuCount = 0;
  291. List<string> losStu = new List<string>();
  292. //先与第一个值取并集
  293. if (examResults.Count >0 ) {
  294. losStu.Union(examResults[0].lostStus);
  295. foreach (ExamResult examResult in examResults)
  296. {
  297. if (info.id == examResult.examId)
  298. {
  299. foreach (List<double> sc in examResult.studentScores)
  300. {
  301. score += sc.Sum();
  302. }
  303. stuCount = examResult.studentIds.Count;
  304. }
  305. //取交集
  306. losStu = losStu.Intersect(examResult.lostStus).ToList();
  307. }
  308. }
  309. double ascore = stuCount > 0 ? Math.Round(score * 0.1 / stuCount, 2) : 0;
  310. foreach (PaperSimple simple in info.papers)
  311. {
  312. allScore += simple.point.Sum();
  313. }
  314. info.sRate = allScore > 0 ? ascore / allScore * 100 : 0;
  315. info.lostStu = losStu;
  316. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync<ExamInfo>(info, info.id, new Azure.Cosmos.PartitionKey(info.code));
  317. //ActivityData data;
  318. if (info.scope == "school")
  319. {
  320. data = new ActivityData
  321. {
  322. id = info.id,
  323. code = $"Activity-{info.school}",
  324. type = "exam",
  325. name = info.name,
  326. startTime = info.startTime,
  327. endTime = info.endTime,
  328. scode = info.code,
  329. scope = info.scope,
  330. progress = "finish",
  331. classes = info.classes.IsNotEmpty() ? info.classes : new List<string> { "" },
  332. tmdids = new List<string> { "" },
  333. subjects = sub
  334. };
  335. await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<ActivityData>(data, info.id, new Azure.Cosmos.PartitionKey(data.code));
  336. }
  337. else if (info.scope == "private")
  338. {
  339. data = new ActivityData
  340. {
  341. id = info.id,
  342. code = $"Activity-Common",
  343. type = "exam",
  344. name = info.name,
  345. startTime = info.startTime,
  346. endTime = info.endTime,
  347. scode = info.code,
  348. scope = info.scope,
  349. progress = "finish",
  350. classes = info.classes.IsNotEmpty() ? info.classes : new List<string> { "" },
  351. tmdids = new List<string> { "" },
  352. subjects = sub
  353. };
  354. await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<ActivityData>(data, info.id, new Azure.Cosmos.PartitionKey(data.code));
  355. }
  356. break;
  357. }
  358. }
  359. public static async Task createClassResultAsync(ExamInfo info, List<ExamClassResult> examClassResults, ExamSubject subject, int no, AzureCosmosFactory _azureCosmos)
  360. {
  361. //保证试卷信息与科目信息同步
  362. ExamResult result = new ExamResult();
  363. //人数总和
  364. int Count = 0;
  365. int m = 0;
  366. double score = 0;
  367. double allScore = info.papers[no].point.Sum();
  368. List<ClassRange> classRanges = new List<ClassRange>();
  369. List<string> lostStu = new List<string>();
  370. foreach (ExamClassResult classResult in examClassResults)
  371. {
  372. if (classResult.subjectId.Equals(subject.id))
  373. {
  374. //记录缺考学生索引位置
  375. int index = 0;
  376. foreach (List<double> scores in classResult.studentScores)
  377. {
  378. List<double> newScores = new List<double>();
  379. int count = 0;
  380. foreach (double sc in scores) {
  381. newScores.Add(sc > -1 ? sc : 0);
  382. if(sc == -1) {
  383. count++;
  384. }
  385. }
  386. if (count == scores.Count) {
  387. lostStu.Add(classResult.studentIds[index]);
  388. //mcount++;
  389. }
  390. score += newScores.Sum();
  391. result.studentScores.Add(newScores);
  392. index++;
  393. }
  394. //处理班级信息
  395. ClassRange range = new ClassRange();
  396. range.id = classResult.info.id;
  397. range.name = classResult.info.name;
  398. range.gradeId = classResult.gradeId;
  399. List<int> ran = new List<int>();
  400. int stuCount = classResult.studentIds.Count;
  401. Count += stuCount;
  402. if (m == 0)
  403. {
  404. ran.Add(0);
  405. ran.Add(stuCount - 1);
  406. }
  407. else
  408. {
  409. ran.Add(Count - stuCount);
  410. ran.Add(Count - 1);
  411. }
  412. m++;
  413. range.range = ran;
  414. classRanges.Add(range);
  415. //处理学生ID
  416. foreach (string id in classResult.studentIds)
  417. {
  418. result.studentIds.Add(id);
  419. }
  420. }
  421. }
  422. result.lostStus = lostStu;
  423. result.sRate =result.studentIds.Count> 0 ? Math.Round(score *1.0 / result.studentIds.Count ,2 ): 0 / allScore;
  424. result.classes = classRanges;
  425. result.code = "ExamResult-" + info.id;
  426. result.school = info.school;
  427. result.id = subject.id;
  428. result.examId = info.id;
  429. result.subjectId = subject.id;
  430. result.year = info.year;
  431. result.paper = info.papers[no];
  432. //result.point = info.papers[j].point;
  433. result.scope = info.scope;
  434. result.name = info.name;
  435. result.time = info.startTime;
  436. await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Common").UpsertItemAsync(result, new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}"));
  437. }
  438. }
  439. }