ActivityController.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. using Azure.Cosmos;
  2. using HTEXLib.Translator;
  3. using Microsoft.AspNetCore.Http;
  4. using Microsoft.AspNetCore.Mvc;
  5. using Microsoft.Extensions.Configuration;
  6. using Microsoft.Extensions.Options;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Text.Json;
  12. using System.Threading.Tasks;
  13. using TEAMModelOS.Filter;
  14. using TEAMModelOS.Models;
  15. using TEAMModelOS.Models.Dto;
  16. using TEAMModelOS.SDK;
  17. using TEAMModelOS.SDK.DI;
  18. using TEAMModelOS.SDK.Extension;
  19. using TEAMModelOS.SDK.Models;
  20. namespace TEAMModelAPI.Controllers
  21. {
  22. [ProducesResponseType(StatusCodes.Status200OK)]
  23. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  24. [ApiController]
  25. [Route("activity")]
  26. public class ActivityController:ControllerBase
  27. {
  28. public AzureCosmosFactory _azureCosmos;
  29. private readonly AzureStorageFactory _azureStorage;
  30. private readonly AzureRedisFactory _azureRedis;
  31. private readonly DingDing _dingDing;
  32. private readonly Option _option;
  33. private readonly IConfiguration _configuration;
  34. public DOXC2HTMLTranslator _DOXC2HTMLTranslator { get; set; }
  35. //public PPTX2HTEXTranslator _PPTX2HTEXTranslator { get; set; }
  36. public HTML2ITEMV3Translator _HTML2ITEMV3Translator { get; set; }
  37. public ActivityController(AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, DingDing dingDing, IOptionsSnapshot<Option> option, IConfiguration configuration)
  38. {
  39. _azureCosmos = azureCosmos;
  40. _azureStorage = azureStorage;
  41. _azureRedis = azureRedis;
  42. _dingDing = dingDing;
  43. _option = option?.Value;
  44. _configuration = configuration;
  45. }
  46. [ProducesDefaultResponseType]
  47. [HttpGet("import-exam")]
  48. [ApiToken(Auth = "91", Name = "汇入评测基础数据", Limit = false)]
  49. public async Task<IActionResult> importExam(JsonElement request)
  50. {
  51. //获取评测的ID
  52. if (!request.TryGetProperty("exam", out JsonElement exam)) return BadRequest();
  53. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  54. try
  55. {
  56. var client = _azureCosmos.GetCosmosClient();
  57. ExamInfo info = exam.ToObject<ExamInfo>();
  58. info.progress = "going";
  59. await client.GetContainer(Constant.TEAMModelOS, "Common").UpsertItemAsync(info, new PartitionKey($"Exam-{code}"));
  60. return Ok(new { info });
  61. }
  62. catch (Exception e)
  63. {
  64. await _dingDing.SendBotMsg($"OS,{_option.Location},analysis/import-exam()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
  65. return BadRequest();
  66. }
  67. }
  68. [ProducesDefaultResponseType]
  69. [HttpGet("upsert-record")]
  70. [ApiToken(Auth = "90", Name = "批量汇入作答数据", Limit = false)]
  71. public async Task<IActionResult> upsertRecord(JsonElement request)
  72. {
  73. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  74. if (!request.TryGetProperty("students", out JsonElement students)) return BadRequest();
  75. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  76. //根据不同评测的类型返回对应的编码
  77. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  78. try
  79. {
  80. var client = _azureCosmos.GetCosmosClient();
  81. //List<string> ids = students.ToObject<List<string>>();
  82. List<students> stus = students.ToObject<List<students>>();
  83. ExamInfo info = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.GetString(), new PartitionKey($"Exam-{code}"));
  84. string classCode = info.scope.Equals("school") ? info.school : info.creatorId;
  85. List<ExamClassResult> examClassResults = new();
  86. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
  87. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  88. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{classCode}") }))
  89. {
  90. examClassResults.Add(item);
  91. }
  92. int n = 0;
  93. foreach (ExamSubject subject in info.subjects)
  94. {
  95. if (!subject.id.Equals(subjectId.GetString()))
  96. {
  97. n++;
  98. }
  99. else
  100. {
  101. break;
  102. }
  103. }
  104. //获取试卷信息
  105. PaperSimple standerAnswers = new PaperSimple();
  106. List<List<string>> standard = new List<List<string>>();
  107. List<double> points = new List<double>();
  108. standerAnswers = info.papers[n];
  109. standard = standerAnswers.answers;
  110. points = standerAnswers.point;
  111. int rule = standerAnswers.multipleRule;
  112. List<string> value = new List<string>();
  113. await foreach (var s in stuTask(stus, examClassResults, standard, points, rule, info, subjectId.GetString(), client))
  114. {
  115. if (s.code == 1)
  116. {
  117. value.Add(s.value);
  118. }
  119. }
  120. if (value.Count > 0)
  121. {
  122. return Ok(new { code = 1, msg = "学生ID异常", value = value });
  123. }
  124. else
  125. {
  126. return Ok(new { code = 0 });
  127. }
  128. }
  129. catch (Exception e)
  130. {
  131. await _dingDing.SendBotMsg($"OS,{_option.Location},activity/upsert-record()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
  132. return BadRequest();
  133. }
  134. }
  135. private async IAsyncEnumerable<(int code, string value)> stuTask(List<students> stus, List<ExamClassResult> examClassResults, List<List<string>> standard,
  136. List<double> points, int rule, ExamInfo info, string subjectId, CosmosClient client)
  137. {
  138. foreach (var s in stus)
  139. {
  140. string value = "";
  141. int code = 0;
  142. List<List<string>> ans = s.answer;
  143. bool isExist = examClassResults.Exists(e => e.studentIds.Contains(s.id));
  144. if (!isExist)
  145. {
  146. value = s.id;
  147. code = 1;
  148. }
  149. else
  150. {
  151. foreach (ExamClassResult result in examClassResults)
  152. {
  153. if (!result.studentIds.Contains(s.id))
  154. {
  155. continue;
  156. }
  157. else
  158. {
  159. int newIndex = result.studentIds.IndexOf(s.id);
  160. StringBuilder builder = new StringBuilder();
  161. builder.Append(result.examId).Append('/');
  162. builder.Append(result.subjectId).Append('/');
  163. builder.Append(s.id).Append('/');
  164. builder.Append("ans.json");
  165. result.studentAnswers[newIndex].Clear();
  166. result.studentAnswers[newIndex].Add(builder.ToString());
  167. for (int i = 0; i < ans.Count; i++)
  168. {
  169. if (ans[i] == null)
  170. {
  171. continue;
  172. //ans[i] = new List<string>();
  173. }
  174. var ac = ans[i].Count;
  175. var sc = standard[i].Count;
  176. //记录次数
  177. int n = 0;
  178. //算分处理
  179. if (sc > 0)
  180. {
  181. result.ans[newIndex][i] = ans[i];
  182. if (ac == sc && sc == 1)
  183. {
  184. foreach (string right in ans[i])
  185. {
  186. if (standard[i].Contains(right))
  187. {
  188. result.studentScores[newIndex][i] = points[i];
  189. }
  190. else
  191. {
  192. result.studentScores[newIndex][i] = 0;
  193. }
  194. }
  195. }
  196. else
  197. {
  198. if (rule > 0)
  199. {
  200. int falseCount = 0;
  201. if (ac > 0)
  202. {
  203. foreach (string obj in ans[i])
  204. {
  205. if (!standard[i].Contains(obj))
  206. {
  207. falseCount++;
  208. }
  209. }
  210. switch (rule)
  211. {
  212. case 1:
  213. if (ac == sc)
  214. {
  215. if (falseCount == 0)
  216. {
  217. result.studentScores[newIndex][i] = points[i];
  218. }
  219. else
  220. {
  221. result.studentScores[newIndex][i] = 0;
  222. }
  223. }
  224. else
  225. {
  226. result.studentScores[newIndex][i] = 0;
  227. }
  228. break;
  229. case 2:
  230. if (falseCount > 0)
  231. {
  232. result.studentScores[newIndex][i] = 0;
  233. }
  234. else
  235. {
  236. if (ac == sc)
  237. {
  238. result.studentScores[newIndex][i] = points[i];
  239. }
  240. else
  241. {
  242. result.studentScores[newIndex][i] = points[i] / 2;
  243. }
  244. }
  245. break;
  246. case 3:
  247. if (falseCount > 0)
  248. {
  249. result.studentScores[newIndex][i] = 0;
  250. }
  251. else
  252. {
  253. if (ac == sc)
  254. {
  255. result.studentScores[newIndex][i] = points[i];
  256. }
  257. else
  258. {
  259. result.studentScores[newIndex][i] = System.Math.Round((double)ac / sc * points[i], 1);
  260. }
  261. }
  262. break;
  263. case 4:
  264. if (ac == sc)
  265. {
  266. result.studentScores[newIndex][i] = points[i];
  267. }
  268. else
  269. {
  270. double persent = (double)(sc - 2 * falseCount) / sc;
  271. if (persent <= 0)
  272. {
  273. result.studentScores[newIndex][i] = 0;
  274. }
  275. else
  276. {
  277. result.studentScores[newIndex][i] = System.Math.Round(persent * points[i], 1);
  278. }
  279. }
  280. break;
  281. }
  282. }
  283. else
  284. {
  285. result.studentScores[newIndex][i] = 0;
  286. }
  287. }
  288. }
  289. }
  290. }
  291. bool flag = true;
  292. foreach (List<double> scores in result.studentScores)
  293. {
  294. foreach (double score in scores)
  295. {
  296. if (score == -1)
  297. {
  298. flag = false;
  299. break;
  300. }
  301. }
  302. }
  303. if (flag)
  304. {
  305. result.progress = true;
  306. info.subjects.ForEach(s =>
  307. {
  308. if (s.id.Equals(subjectId.ToString()))
  309. {
  310. s.classCount += 1;
  311. }
  312. });
  313. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(info, info.id.ToString(), new PartitionKey($"{info.code}"));
  314. }
  315. result.sum[newIndex] = result.studentScores[newIndex].Sum();
  316. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
  317. break;
  318. }
  319. }
  320. }
  321. yield return (code, value);
  322. }
  323. }
  324. [ProducesDefaultResponseType]
  325. [HttpGet("parse-word")]
  326. [ApiToken(Auth = "92", Name = "录入试卷数据", Limit = false)]
  327. public async Task<IActionResult> ParseWord([FromForm] FileDto fileDto)
  328. {
  329. if (!FileType.GetExtention(fileDto.file.FileName).ToLower().Equals("docx"))
  330. {
  331. return BadRequest(new Dictionary<string, object> { { "msg", "type is not docx!" }, { "code", 404} });
  332. }
  333. try
  334. {
  335. var client = _azureCosmos.GetCosmosClient();
  336. var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(fileDto.examId, new PartitionKey($"Exam-{fileDto.code}"));
  337. ExamInfo examInfo;
  338. if (response.Status == 200)
  339. {
  340. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  341. examInfo = json.ToObject<ExamInfo>();
  342. }
  343. else
  344. {
  345. return Ok(new { error = 404, msg = "请先导入评测信息" });
  346. }
  347. foreach (PaperSimple paper in examInfo.papers)
  348. {
  349. if (paper.id.Contains(fileDto.subjectId))
  350. {
  351. return Ok(new { error = 500, msg = "该试卷信息已存在" });
  352. }
  353. }
  354. PaperSimple simple = new();
  355. var doc = _DOXC2HTMLTranslator.Translate(fileDto.file.OpenReadStream());
  356. (List<HTEXLib.DOCX.Models.ItemInfo> tests, List<string> error) = _HTML2ITEMV3Translator.Translate(doc);
  357. List<Task<string>> tasks = new List<Task<string>>();
  358. PaperDto paperDto = new()
  359. {
  360. id = Guid.NewGuid().ToString(),
  361. name = fileDto.name,
  362. code = fileDto.code,
  363. scope = "school",
  364. multipleRule = fileDto.multipleRule,
  365. gradeIds = fileDto.gradeIds,
  366. subjectId = fileDto.subjectId,
  367. periodId = fileDto.periodId
  368. };
  369. foreach (HTEXLib.DOCX.Models.ItemInfo item in tests)
  370. {
  371. Slides slides = new();
  372. ItemDto dto = new();
  373. Scoring scoring = new();
  374. dto.id = Guid.NewGuid().ToString();
  375. dto.exercise.answer = item.answer;
  376. dto.exercise.explain = item.explain;
  377. dto.exercise.type = item.type;
  378. dto.exercise.opts = item.option.Count;
  379. dto.exercise.knowledge = item.knowledge;
  380. dto.exercise.field = item.field;
  381. dto.exercise.level = item.level;
  382. dto.exercise.subjectId = fileDto.subjectId;
  383. dto.exercise.periodId = fileDto.periodId;
  384. dto.exercise.gradeIds = fileDto.gradeIds;
  385. slides.url = dto.id + ".json";
  386. slides.type = dto.exercise.type;
  387. scoring.ans = dto.exercise.answer;
  388. scoring.score = dto.exercise.score;
  389. scoring.knowledge = dto.exercise.knowledge;
  390. scoring.field = dto.exercise.field;
  391. slides.scoring = scoring;
  392. //添加试卷信息
  393. paperDto.slides.Add(slides);
  394. if (!slides.type.Equals("compose"))
  395. {
  396. simple.point.Add(dto.exercise.score);
  397. simple.answers.Add(dto.exercise.answer);
  398. simple.knowledge.Add(dto.exercise.knowledge);
  399. simple.type.Add(dto.exercise.type);
  400. simple.field.Add((int)dto.exercise.field);
  401. }
  402. if (item.children.Count > 0)
  403. {
  404. foreach (HTEXLib.DOCX.Models.ItemInfo its in item.children)
  405. {
  406. Slides cslides = new();
  407. Scoring cscoring = new();
  408. ItemDto dtoChildren = new ItemDto();
  409. dtoChildren.id = Guid.NewGuid().ToString();
  410. dtoChildren.pid = dto.id;
  411. dtoChildren.exercise.answer = its.answer;
  412. dtoChildren.exercise.explain = its.explain;
  413. dtoChildren.exercise.type = its.type;
  414. dtoChildren.exercise.opts = its.option.Count;
  415. dtoChildren.exercise.knowledge = its.knowledge;
  416. dtoChildren.exercise.field = its.field;
  417. dtoChildren.exercise.level = its.level;
  418. dtoChildren.exercise.scope = "school";
  419. dtoChildren.exercise.score = its.score;
  420. dtoChildren.exercise.subjectId = fileDto.subjectId;
  421. dtoChildren.exercise.periodId = fileDto.periodId;
  422. dtoChildren.exercise.gradeIds = fileDto.gradeIds;
  423. dtoChildren.exercise.children.Add(dtoChildren.id);
  424. info info1 = new();
  425. info1.uid = dtoChildren.id;
  426. info1.question = its.question;
  427. info1.option = its.option;
  428. dtoChildren.item.Add(info1);
  429. dto.exercise.children.Add(dtoChildren.id);
  430. //处理子题的slides
  431. cslides.url = dtoChildren.id + ".json";
  432. cslides.type = dtoChildren.exercise.type;
  433. cscoring.ans = dtoChildren.exercise.answer;
  434. cscoring.score = dtoChildren.exercise.score;
  435. cscoring.knowledge = dtoChildren.exercise.knowledge;
  436. cscoring.field = dtoChildren.exercise.field;
  437. cslides.scoring = scoring;
  438. paperDto.slides.Add(cslides);
  439. //添加试卷信息
  440. simple.point.Add(dtoChildren.exercise.score);
  441. simple.answers.Add(dto.exercise.answer);
  442. simple.knowledge.Add(dto.exercise.knowledge);
  443. simple.type.Add(dto.exercise.type);
  444. simple.field.Add((int)dto.exercise.field);
  445. StringBuilder stringBuilder = new StringBuilder();
  446. stringBuilder.Append(fileDto.examId).Append("/");
  447. stringBuilder.Append("paper").Append("/");
  448. stringBuilder.Append(fileDto.subjectId).Append("/");
  449. stringBuilder.Append(dtoChildren.id + ".json");
  450. tasks.Add(_azureStorage.UploadFileByContainer(fileDto.code, dtoChildren.ToJsonString(), "exam", stringBuilder.ToString(), false));
  451. }
  452. }
  453. info @info = new();
  454. @info.uid = dto.id;
  455. @info.question = item.question;
  456. @info.option = item.option;
  457. dto.item.Add(@info);
  458. dto.exercise.scope = "school";
  459. dto.exercise.score = item.score;
  460. StringBuilder builder = new StringBuilder();
  461. builder.Append(fileDto.examId).Append('/');
  462. builder.Append("paper").Append('/');
  463. builder.Append(fileDto.subjectId).Append('/');
  464. builder.Append(dto.id + ".json");
  465. tasks.Add(_azureStorage.UploadFileByContainer(fileDto.code, dto.ToJsonString(), "exam", builder.ToString(), false));
  466. }
  467. StringBuilder paperBuilder = new StringBuilder();
  468. paperBuilder.Append(fileDto.examId).Append('/');
  469. paperBuilder.Append("paper").Append('/');
  470. paperBuilder.Append(fileDto.subjectId).Append('/');
  471. paperBuilder.Append("index.json");
  472. tasks.Add(_azureStorage.UploadFileByContainer(fileDto.code, paperDto.ToJsonString(), "exam", paperBuilder.ToString(), false));
  473. //开始给ExamInfo paper赋值
  474. simple.id = fileDto.subjectId;
  475. simple.code = "Paper-" + fileDto.code;
  476. simple.name = fileDto.name;
  477. simple.blob = paperBuilder.ToString().Replace("index.json", "");
  478. simple.scope = "school";
  479. simple.multipleRule = fileDto.multipleRule;
  480. examInfo.papers.Add(simple);
  481. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(examInfo, examInfo.id, new PartitionKey($"{examInfo.code}"));
  482. await Task.WhenAll(tasks);
  483. return Ok(new { code = 200 });
  484. }
  485. catch (Exception e)
  486. {
  487. await _dingDing.SendBotMsg($"OS,{_option.Location},analysis/word()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
  488. return BadRequest();
  489. }
  490. }
  491. private class students
  492. {
  493. public string id { get; set; }
  494. public List<List<string>> answer { get; set; }
  495. }
  496. public class FileDto
  497. {
  498. public string periodId { get; set; }
  499. public string code { get; set; }
  500. public string name { get; set; }
  501. public int multipleRule { get; set; }
  502. public string examId { get; set; }
  503. public string subjectId { get; set; }
  504. public List<string> gradeIds { get; set; }
  505. public IFormFile file { get; set; }
  506. }
  507. }
  508. }