TriggerCorrect.cs 28 KB

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