SheetConfigController.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. using Microsoft.Azure.Cosmos;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.AspNetCore.Mvc;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IdentityModel.Tokens.Jwt;
  7. using System.Linq;
  8. using System.Text.Json;
  9. using System.Threading.Tasks;
  10. using TEAMModelOS.SDK.Models;
  11. using TEAMModelOS.SDK.DI;
  12. using TEAMModelOS.SDK.Extension;
  13. using TEAMModelOS.Models;
  14. using Microsoft.Extensions.Options;
  15. using TEAMModelOS.SDK.Models.Cosmos.Common;
  16. using Azure;
  17. using Microsoft.AspNetCore.Authorization;
  18. using TEAMModelOS.SDK.Services;
  19. using TEAMModelOS.Filter;
  20. namespace TEAMModelOS.Controllers.Common
  21. {
  22. [ProducesResponseType(StatusCodes.Status200OK)]
  23. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  24. [Route("sheet-config")]
  25. [ApiController]
  26. public class SheetConfigController : ControllerBase
  27. {
  28. private readonly AzureRedisFactory _azureRedis;
  29. private readonly AzureCosmosFactory _azureCosmos;
  30. private readonly SnowflakeId _snowflakeId;
  31. private readonly AzureServiceBusFactory _serviceBus;
  32. private readonly DingDing _dingDing;
  33. private readonly Option _option;
  34. private readonly AzureStorageFactory _azureStorage;
  35. public SheetConfigController(AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing, IOptionsSnapshot<Option> option,
  36. AzureRedisFactory azureRedis, AzureStorageFactory azureStorage)
  37. {
  38. _azureCosmos = azureCosmos;
  39. _serviceBus = serviceBus;
  40. _snowflakeId = snowflakeId;
  41. _dingDing = dingDing;
  42. _option = option?.Value;
  43. _azureRedis = azureRedis;
  44. _azureStorage = azureStorage;
  45. }
  46. /// <summary>
  47. ///查询答题卡
  48. /// </summary>
  49. /// <param name="request"></param>
  50. /// <returns></returns>
  51. [ProducesDefaultResponseType]
  52. [HttpPost("find")]
  53. [AuthToken(Roles = "teacher,admin,student")]
  54. #if !DEBUG
  55. [Authorize(Roles = "IES")]
  56. #endif
  57. public async Task<IActionResult> Find(JsonElement request) {
  58. try
  59. {
  60. var client = _azureCosmos.GetCosmosClient();
  61. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  62. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  63. if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  64. if ($"{scope}" .Equals("school"))
  65. {
  66. SheetConfig config = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SheetConfig>($"{id}", new PartitionKey($"SheetConfig-{code}"));
  67. return Ok(new { config = config, status = 200 });
  68. }
  69. else
  70. {
  71. SheetConfig config = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<SheetConfig>($"{id}", new PartitionKey($"SheetConfig-{code}"));
  72. return Ok(new { config = config,status=200 });
  73. }
  74. }
  75. catch (CosmosException e)
  76. {
  77. return Ok(new { status = e.StatusCode });
  78. }
  79. catch (Exception ex) {
  80. await _dingDing.SendBotMsg($"OS,{_option.Location},common/SheetConfig/upsert()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  81. return BadRequest(ex.StackTrace);
  82. }
  83. }
  84. /**
  85. @条件1 当examId有值,则paperId 和 owner必定有值,sheet代表一个评测下的某一个试卷的答题卡数据,且答题卡的scope对应为评测的scope,且school和creatorId 与评测保持一致,且sheet.id从前端传递来的无效,
  86. 因为id需要根据当前评测examId的试卷绑定的答题卡覆写或者新建
  87. 如果检测到examId下对应的试卷绑定答题卡sheet为空则新生成一个答题卡id,并自动绑定。
  88. @条件2 当examId没有值,且paperId有值,sheet代表一个试卷库的某一个试卷的答题卡数据,且答题卡的scope对应为试卷库paperId的scope,且school和creatorId 与评测保持一致,且sheet.id从前端传递来的无效,
  89. 因为id需要根据试卷绑定的答题卡覆写或者新建
  90. 如果检测到paperId的试卷绑定的答题卡sheett为空则新生成一个答题卡id,并自动绑定。如果检测aperId的试卷已经绑定答题卡,则只需要更新实时的答题卡数据。
  91. @条件3 当examId和paperId都没有值,sheet代表与评测,试卷库无关的答题卡数据,且答题卡的scope ,school和creatorId 根据当前创建者需要保存数据的规则有关。
  92. 且sheet.id,如果有值则是更新答题卡内容数据。
  93. 如果sheet.id,没有值则是新建保存答题卡数据。
  94. @条件4 其他情况的参数传递不予以考虑,直接返回400参数错误。
  95. **/
  96. /// <summary>
  97. /// 新增 或 修改答题卡
  98. /// </summary>
  99. /// <param name="request"></param>
  100. /// <returns></returns>
  101. [ProducesDefaultResponseType]
  102. [HttpPost("upsert")]
  103. [AuthToken(Roles = "teacher,admin")]
  104. #if !DEBUG
  105. [Authorize(Roles = "IES")]
  106. #endif
  107. public async Task<IActionResult> Upsert(JsonElement request)
  108. {
  109. try
  110. {
  111. if (!request.TryGetProperty("sheet", out JsonElement _sheet)) { return BadRequest(); }
  112. request.TryGetProperty("examId", out JsonElement _examId);
  113. request.TryGetProperty("paperId", out JsonElement _paperId);
  114. request.TryGetProperty("owner", out JsonElement _owner);
  115. var client = _azureCosmos.GetCosmosClient();
  116. SheetConfig sheet = _sheet.ToObject<SheetConfig>();
  117. if (sheet == null) {
  118. return BadRequest("sheet params is null!");
  119. }
  120. if (!sheet.code.StartsWith("SheetConfig-")) {
  121. if (sheet.scope.Equals("school") && !string.IsNullOrWhiteSpace(sheet.school))
  122. {
  123. sheet.code = $"SheetConfig-{sheet.school}";
  124. }
  125. else {
  126. sheet.code = $"SheetConfig-{sheet.creatorId}";
  127. }
  128. }
  129. sheet.pk = $"SheetConfig";
  130. sheet.ttl = -1;
  131. string tbname = sheet.scope.Equals("school", StringComparison.OrdinalIgnoreCase)? "School": "Teacher";
  132. // @条件1 代表需要更新评测的某一个试卷的答题卡
  133. if (!_paperId.ValueKind.Equals(JsonValueKind.Null) && !_examId.ValueKind.Equals(JsonValueKind.Null) && !string.IsNullOrEmpty($"{ _examId}") && !string.IsNullOrEmpty($"{ _paperId}"))
  134. {
  135. sheet.from = "exam";
  136. string code = "";
  137. if (!string.IsNullOrEmpty($"{_owner}") && $"{_owner}".Equals("school", StringComparison.OrdinalIgnoreCase)) {
  138. code = $"Exam-{sheet.school}";
  139. }
  140. else {
  141. code = $"Exam-{sheet.creatorId}";
  142. }
  143. try
  144. {
  145. ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>($"{_examId}", new PartitionKey($"{code}"));
  146. sheet.scope = exam.scope;
  147. var ps = exam.papers.Where(p => p.id == $"{_paperId}").FirstOrDefault();
  148. if (ps != null)
  149. {
  150. if (string.IsNullOrEmpty(ps.sheet) || !Guid.TryParse(ps.sheet, out Guid guid))
  151. {
  152. sheet.id = Guid.NewGuid().ToString();
  153. ps.sheet = sheet.id;
  154. }
  155. else
  156. {
  157. sheet.id = ps.sheet;
  158. }
  159. if (string.IsNullOrEmpty(sheet.no))
  160. {
  161. sheet.no = await SheetService.genSheetNo(client, _dingDing, _option, sheet.code, tbname, sheet.from);
  162. }
  163. ps.sheetNo = sheet.no;
  164. ps.mode = sheet.mode;
  165. exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ExamInfo>(exam, $"{_examId}", new PartitionKey($"{code}"));
  166. }
  167. else
  168. {
  169. return BadRequest($"paperId:{_paperId} is not exist!");
  170. }
  171. }
  172. catch (CosmosException ex) when (ex.StatusCode ==System.Net.HttpStatusCode.NotFound) {
  173. return Ok(new { status = ex.StatusCode });
  174. }
  175. catch (Exception ex)
  176. {
  177. return BadRequest($"{ex.Message}\n{ex.StackTrace},examId:{_examId} is not exist!");
  178. }
  179. }
  180. // @条件2 代表需要更新或保存试卷库的某一个试卷的答题卡
  181. else if ((string.IsNullOrEmpty($"{ _examId}") || !_examId.ValueKind.Equals(JsonValueKind.Null))
  182. && !_paperId.ValueKind.Equals(JsonValueKind.Null) && !string.IsNullOrEmpty($"{ _paperId}"))
  183. {
  184. sheet.from = "paper";
  185. string code = sheet.scope.Equals("school", StringComparison.OrdinalIgnoreCase) ? $"Paper-{sheet.school}": $"Paper-{sheet.creatorId}";
  186. try
  187. {
  188. Paper paper = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<Paper>($"{_paperId}", new PartitionKey($"{code}"));
  189. if (string.IsNullOrEmpty(paper.sheet)||!Guid.TryParse(paper.sheet,out Guid guid))
  190. {
  191. sheet.id = Guid.NewGuid().ToString();
  192. paper.sheet = sheet.id;
  193. }
  194. else
  195. {
  196. sheet.id = paper.sheet;
  197. }
  198. if (string.IsNullOrEmpty(sheet.no)) {
  199. sheet.no = await SheetService.genSheetNo(client, _dingDing, _option, sheet.code, tbname, sheet.from);
  200. paper.sheetNo = sheet.no;
  201. paper.mode = sheet.mode;
  202. }
  203. paper.sheetNo = sheet.no;
  204. paper.mode = sheet.mode;
  205. paper = await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<Paper>(paper, $"{_paperId}", new PartitionKey($"{code}"));
  206. }
  207. catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
  208. {
  209. return Ok(new { status = ex.StatusCode });
  210. }
  211. catch (Exception ex)
  212. {
  213. return BadRequest($"{ex.Message}\n{ex.StackTrace},paperId:{_paperId} is not exist!");
  214. }
  215. }
  216. //@条件3 代表需要直接产生一个答题卡
  217. else if (string.IsNullOrEmpty($"{ _examId}") && string.IsNullOrEmpty($"{ _paperId}"))
  218. {
  219. sheet.from = "sheet";
  220. if (string.IsNullOrEmpty(sheet.id)) {
  221. sheet.id = Guid.NewGuid().ToString();
  222. }
  223. if (string.IsNullOrEmpty(sheet.no)) {
  224. sheet.no = await SheetService.genSheetNo(client, _dingDing, _option, sheet.code, tbname, sheet.from);
  225. }
  226. }
  227. else {
  228. //@条件4
  229. return BadRequest("params is error!");
  230. }
  231. if (string.IsNullOrEmpty(sheet.no))
  232. {
  233. sheet.no = await SheetService.genSheetNo(client, _dingDing, _option, sheet.code, tbname,sheet.from);
  234. }
  235. sheet = await client.GetContainer(Constant.TEAMModelOS, tbname).UpsertItemAsync(sheet, new PartitionKey($"{sheet.code}"));
  236. return Ok(new { config = sheet, status=200 });
  237. }
  238. catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
  239. {
  240. return Ok(new { status = ex.StatusCode });
  241. }
  242. catch (Exception e)
  243. {
  244. await _dingDing.SendBotMsg($"OS,{_option.Location},common/SheetConfig/upsert()\n{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
  245. return BadRequest(e.Message);
  246. }
  247. }
  248. /// <summary>
  249. ///删除答题卡
  250. /// </summary>
  251. /// <param name="request"></param>
  252. /// <returns></returns>
  253. [ProducesDefaultResponseType]
  254. [HttpPost("delete")]
  255. [AuthToken(Roles = "teacher,admin")]
  256. #if !DEBUG
  257. [Authorize(Roles = "IES")]
  258. #endif
  259. public async Task<IActionResult> Delete(JsonElement request)
  260. {
  261. try
  262. {
  263. var client = _azureCosmos.GetCosmosClient();
  264. if (!request.TryGetProperty("ids", out JsonElement ids)) return BadRequest();
  265. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  266. if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  267. List<string> idslist = ids.ToObject<List<string>>();
  268. if ($"{scope}" .Equals("school"))
  269. {
  270. await client.GetContainer(Constant.TEAMModelOS, "School").DeleteItemsStreamAsync(idslist, $"SheetConfig-{code}");
  271. }
  272. else
  273. {
  274. await client.GetContainer(Constant.TEAMModelOS, "Teacher").DeleteItemsStreamAsync(idslist, $"SheetConfig-{code}");
  275. }
  276. return Ok(new { status = 404 });
  277. }
  278. catch (CosmosException ex) {
  279. return Ok(new { status = ex.StatusCode });
  280. }
  281. catch (Exception e)
  282. {
  283. await _dingDing.SendBotMsg($"OS,{_option.Location},common/SheetConfig/delete()\n{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
  284. return BadRequest(e.StackTrace);
  285. }
  286. }
  287. }
  288. }