TriggerCorrect.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. using Azure.Cosmos;
  2. using Azure.Messaging.ServiceBus;
  3. using System.Text.Json;
  4. using TEAMModelOS.SDK.DI;
  5. using TEAMModelOS.SDK.Extension;
  6. using TEAMModelOS.SDK;
  7. using TEAMModelOS.SDK.Models;
  8. using TEAMModelOS.SDK.Models.Cosmos;
  9. using TEAMModelOS.SDK.Models.Cosmos.Common;
  10. using HTEXLib.COMM.Helpers;
  11. using TEAMModelOS.Function;
  12. namespace TEAMModelOS.CosmosDBTriggers
  13. {
  14. public static class TriggerCorrect
  15. {
  16. public static async Task Trigger(CoreAPIHttpService _coreAPIHttpService, AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
  17. CosmosClient client, JsonElement input, TriggerData tdata, AzureRedisFactory _azureRedis)
  18. {
  19. if ((tdata.status != null && tdata.status.Value == 404))
  20. {
  21. await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(tdata.id, new PartitionKey(tdata.code));
  22. ActivityList data = input.ToObject<ActivityList>();
  23. //await IESActivityService.DeleteActivity(_coreAPIHttpService, client, _dingDing, data);
  24. var table_cancel = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  25. List<ChangeRecord> records = await table_cancel.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tdata.id } });
  26. foreach (var record in records)
  27. {
  28. try
  29. {
  30. await table_cancel.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  31. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  32. }
  33. catch (Exception)
  34. {
  35. continue;
  36. }
  37. }
  38. return;
  39. }
  40. var adid = tdata.id;
  41. var adcode = "";
  42. string blobcntr = null;
  43. if (tdata.scope.Equals("school"))
  44. {
  45. adcode = $"Activity-{tdata.school}";
  46. blobcntr = tdata.school;
  47. }
  48. else
  49. {
  50. return;
  51. }
  52. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}阅卷配置【{tdata.name}-{tdata.id}-ttl={tdata.ttl}】正在执行", GroupNames.醍摩豆服務運維群組);
  53. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  54. try {
  55. Correct correct = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Correct>(tdata.id, new Azure.Cosmos.PartitionKey($"{tdata.code}"));
  56. if (correct != null)
  57. {
  58. string PartitionKey = string.Format("{0}{1}{2}", correct.code, "-", correct.progress);
  59. List<ChangeRecord> correctRecords = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tdata.id }, { "PartitionKey", PartitionKey } });
  60. switch (correct.progress)
  61. {
  62. case "pending":
  63. var messageCorrect = new ServiceBusMessage(new { id = tdata.id, progress = "going", code = tdata.code }.ToJsonString());
  64. messageCorrect.ApplicationProperties.Add("name", "Correct");
  65. if (correctRecords.Count > 0)
  66. {
  67. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageCorrect, DateTimeOffset.FromUnixTimeMilliseconds(tdata.startTime));
  68. try
  69. {
  70. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), correctRecords[0].sequenceNumber);
  71. }
  72. catch (Exception)
  73. {
  74. }
  75. correctRecords[0].sequenceNumber = start;
  76. await table.SaveOrUpdate<ChangeRecord>(correctRecords[0]);
  77. }
  78. else
  79. {
  80. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageCorrect, DateTimeOffset.FromUnixTimeMilliseconds(tdata.startTime));
  81. ChangeRecord changeRecord = new ChangeRecord
  82. {
  83. RowKey = tdata.id,
  84. PartitionKey = PartitionKey,
  85. sequenceNumber = start,
  86. msgId = messageCorrect.MessageId
  87. };
  88. await table.Save<ChangeRecord>(changeRecord);
  89. }
  90. break;
  91. case "going":
  92. //评测id
  93. string eid = correct.id;
  94. //评测的分区键
  95. string ecode = correct.scode;
  96. ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(tdata.id, new Azure.Cosmos.PartitionKey($"{ecode}"));
  97. if (correct.subs.IsNotEmpty())
  98. {
  99. foreach (var sub in correct.subs)
  100. {
  101. ///生成阅卷教师的阅卷任务列表
  102. if (sub.markers.IsNotEmpty())
  103. {
  104. foreach (var marker in sub.markers)
  105. {
  106. CorrectTask task = new CorrectTask
  107. {
  108. ttl = -1,
  109. pk = "CorrectTask",
  110. code = "CorrectTask-" + marker.id,
  111. id = Guid.NewGuid().ToString(),
  112. //评测id 或者阅卷配置id
  113. cid = correct.id,
  114. //科目
  115. subject = sub.id,
  116. //科目名称
  117. subjectName = sub.name,
  118. //评测code
  119. ecode = correct.scode,
  120. //阅卷配置code
  121. scode = correct.code,
  122. //任务名称
  123. name = correct.name,
  124. progress = "going",
  125. //开始时间
  126. startTime = correct.startTime,
  127. //结束时间
  128. endTime = correct.endTime,
  129. //批改数量
  130. count = marker.count,
  131. //按题阅卷时,题号
  132. qu = marker.qu,
  133. //模块数
  134. model = sub.model,
  135. type = 1,
  136. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  137. source = info.source
  138. };
  139. await client.GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync<CorrectTask>(task, new Azure.Cosmos.PartitionKey(task.code));
  140. }
  141. }
  142. //生成异常卷处理人员
  143. if (sub.err.IsNotEmpty())
  144. {
  145. foreach (var tId in sub.err)
  146. {
  147. CorrectTask task = new CorrectTask
  148. {
  149. ttl = -1,
  150. pk = "CorrectTask",
  151. code = "CorrectTask-" + tId,
  152. id = Guid.NewGuid().ToString(),
  153. //评测id 或者阅卷配置id
  154. cid = correct.id,
  155. //科目
  156. subject = sub.id,
  157. //科目名称
  158. subjectName = sub.name,
  159. //评测code
  160. ecode = correct.scode,
  161. //阅卷配置code
  162. scode = correct.code,
  163. progress = "going",
  164. //任务名称
  165. name = correct.name,
  166. //开始时间
  167. startTime = correct.startTime,
  168. //结束时间
  169. endTime = correct.endTime,
  170. //模块数
  171. model = sub.model,
  172. type = 2,
  173. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  174. };
  175. await client.GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync<CorrectTask>(task, new Azure.Cosmos.PartitionKey(task.code));
  176. }
  177. }
  178. //生成仲裁人员
  179. if (sub.arb.IsNotEmpty())
  180. {
  181. foreach (var tId in sub.arb)
  182. {
  183. CorrectTask task = new CorrectTask
  184. {
  185. ttl = -1,
  186. pk = "CorrectTask",
  187. code = "CorrectTask-" + tId,
  188. id = Guid.NewGuid().ToString(),
  189. //评测id 或者阅卷配置id
  190. cid = correct.id,
  191. //科目
  192. subject = sub.id,
  193. //科目名称
  194. subjectName = sub.name,
  195. progress = "going",
  196. //评测code
  197. ecode = correct.scode,
  198. //阅卷配置code
  199. scode = correct.code,
  200. //任务名称
  201. name = correct.name,
  202. //开始时间
  203. startTime = correct.startTime,
  204. //结束时间
  205. endTime = correct.endTime,
  206. //模块数
  207. model = sub.model,
  208. type = 3,
  209. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  210. };
  211. await client.GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync<CorrectTask>(task, new Azure.Cosmos.PartitionKey(task.code));
  212. }
  213. }
  214. //评测科目
  215. string subjectId = sub.id;
  216. //生成临时作答数据存放到redis
  217. //var redisClient = _azureRedis.GetRedisClient(8);
  218. //ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(eid, new Azure.Cosmos.PartitionKey(ecode));
  219. List<ExamClassResult> classResults = new List<ExamClassResult>();
  220. //获取原题配分
  221. int paperIndex = 0;
  222. foreach (ExamSubject subject in info.subjects)
  223. {
  224. if (subject.id.Equals(subjectId))
  225. {
  226. break;
  227. }
  228. else
  229. {
  230. paperIndex++;
  231. }
  232. }
  233. List<double> paperPoint = info.papers[paperIndex].point;
  234. List<List<string>> ans = info.papers[paperIndex].answers;
  235. if (info.scope.Equals("school"))
  236. {
  237. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
  238. queryText: $"select value(c) from c where c.examId = '{eid}' and c.subjectId = '{subjectId}'",
  239. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamClassResult-{info.school}") }))
  240. {
  241. classResults.Add(item);
  242. }
  243. }
  244. else
  245. {
  246. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
  247. queryText: $"select value(c) from c where c.examId = '{eid}' and c.subjectId = '{subjectId}'",
  248. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamClassResult-{info.creatorId}") }))
  249. {
  250. classResults.Add(item);
  251. }
  252. }
  253. List<Task<ItemResponse<SDK.Models.Cosmos.Common.Scoring>>> tasks = new List<Task<ItemResponse<SDK.Models.Cosmos.Common.Scoring>>>();
  254. //初始化老师阅卷记录
  255. //List<string> tmds = new List<string>();
  256. /* List<string> marks = new List<string>();
  257. for (int i = 0; i < correct.num; i++)
  258. {
  259. marks.Add("");
  260. }*/
  261. foreach (ExamClassResult examClass in classResults)
  262. {
  263. foreach (string stuId in examClass.studentIds)
  264. {
  265. int index = examClass.studentIds.IndexOf(stuId);
  266. if (index > -1)
  267. {
  268. List<double> scc = examClass.studentScores[index];
  269. List<Item> items = new List<Item>();
  270. List<Qs> qss = new List<Qs>();
  271. int itemIndex = 0;
  272. foreach (double psc in scc)
  273. {
  274. //初始化异常卷信息,初始化仲裁卷信息
  275. Qs qs = new Qs();
  276. List<Info> infos = new List<Info>();
  277. Item item = new Item
  278. {
  279. ssc = paperPoint[itemIndex],
  280. scores = infos
  281. };
  282. itemIndex++;
  283. items.Add(item);
  284. qss.Add(qs);
  285. }
  286. //处理学生未作答 生成阅卷数据时 客观题分数为-1的情况
  287. List<double> scores = new List<double>();
  288. int n = 0;
  289. foreach (List<string> answer in ans)
  290. {
  291. var scs = examClass.studentScores[index][n];
  292. if (answer.Count > 0)
  293. {
  294. if (scs == -1)
  295. {
  296. scores.Add(0);
  297. }
  298. else
  299. {
  300. scores.Add(scs);
  301. }
  302. }
  303. else
  304. {
  305. scores.Add(scs);
  306. }
  307. n++;
  308. }
  309. SDK.Models.Cosmos.Common.Scoring sc = new SDK.Models.Cosmos.Common.Scoring
  310. {
  311. id = Guid.NewGuid().ToString(),
  312. code = "Scoring-" + info.school,
  313. blob = examClass.studentAnswers[index].Count > 0 ? examClass.studentAnswers[index][0] : "",
  314. stuId = stuId,
  315. examId = eid,
  316. subjectId = subjectId,
  317. scores = scores,
  318. count = correct.num,
  319. //marks = marks,
  320. items = items,
  321. qs = qss,
  322. //endTime = correct.endTime,
  323. model = sub.model
  324. };
  325. tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<SDK.Models.Cosmos.Common.Scoring>(sc, new Azure.Cosmos.PartitionKey(sc.code)));
  326. }
  327. //tasks.Add(redisClient.HashSetAsync($"Exam:Scoring:{eid}-{subjectId}", stuId, new { tmdId = tmds, ans = examClass.studentAnswers[index].Count > 0 ? examClass.studentAnswers[index][0] : "", score = examClass.studentScores[index] }.ToJsonString()));
  328. }
  329. }
  330. await Task.WhenAll(tasks);
  331. }
  332. }
  333. var messageCorrectEnd = new ServiceBusMessage(new { id = tdata.id, progress = "finish", code = tdata.code }.ToJsonString());
  334. messageCorrectEnd.ApplicationProperties.Add("name", "Correct");
  335. if (correctRecords.Count > 0)
  336. {
  337. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageCorrectEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.endTime));
  338. try
  339. {
  340. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), correctRecords[0].sequenceNumber);
  341. }
  342. catch (Exception)
  343. {
  344. }
  345. correctRecords[0].sequenceNumber = end;
  346. await table.SaveOrUpdate<ChangeRecord>(correctRecords[0]);
  347. }
  348. else
  349. {
  350. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageCorrectEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.endTime));
  351. ChangeRecord changeRecord = new ChangeRecord
  352. {
  353. RowKey = tdata.id,
  354. PartitionKey = PartitionKey,
  355. sequenceNumber = end,
  356. msgId = messageCorrectEnd.MessageId
  357. };
  358. await table.Save<ChangeRecord>(changeRecord);
  359. }
  360. break;
  361. case "finish":
  362. foreach (var sub in correct.subs)
  363. {
  364. List<string> ids = new List<string>();
  365. ///阅卷教师的阅卷任务列表
  366. if (sub.markers.IsNotEmpty())
  367. {
  368. foreach (var marker in sub.markers)
  369. {
  370. ids.Add(marker.id);
  371. //await client.GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync<CorrectTask>(task, new Azure.Cosmos.PartitionKey(task.code),new ItemRequestOptions().PostTriggers);
  372. }
  373. }
  374. //异常卷处理人员
  375. if (sub.err.IsNotEmpty())
  376. {
  377. foreach (var tId in sub.err)
  378. {
  379. if (!ids.Contains(tId))
  380. {
  381. ids.Add(tId);
  382. }
  383. }
  384. }
  385. //仲裁人员
  386. if (sub.arb.IsNotEmpty())
  387. {
  388. foreach (var tId in sub.arb)
  389. {
  390. if (!ids.Contains(tId))
  391. {
  392. ids.Add(tId);
  393. }
  394. }
  395. }
  396. List<CorrectTask> corrects = new List<CorrectTask>();
  397. foreach (string id in ids)
  398. {
  399. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<CorrectTask>(
  400. queryText: $"select value(c) from c where c.cid = '{correct.id}'",
  401. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"CorrectTask-{id}") }))
  402. {
  403. corrects.Add(item);
  404. }
  405. }
  406. List<Task<ItemResponse<CorrectTask>>> tasks = new List<Task<ItemResponse<CorrectTask>>>();
  407. foreach (CorrectTask task in corrects)
  408. {
  409. task.progress = "finish";
  410. tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(task, task.id, new Azure.Cosmos.PartitionKey(task.code)));
  411. }
  412. await Task.WhenAll(tasks);
  413. }
  414. break;
  415. }
  416. }
  417. }
  418. catch (CosmosException e)
  419. {
  420. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.Status}", GroupNames.醍摩豆服務運維群組);
  421. }
  422. catch (Exception e)
  423. {
  424. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-阅卷异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  425. }
  426. }
  427. }
  428. }