TriggerCorrect.cs 28 KB

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