123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390 |
- using Azure.Cosmos;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using System;
- using System.Collections.Generic;
- using System.IdentityModel.Tokens.Jwt;
- using System.Linq;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelOS.Models.Dto;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.DI.AzureCosmos.Inner;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Helper.Common.StringHelper;
- using TEAMModelOS.Models;
- using Microsoft.Extensions.Options;
- using TEAMModelOS.SDK.Models.Cosmos;
- using Microsoft.AspNetCore.Authorization;
- using TEAMModelOS.Filter;
- using StackExchange.Redis;
- using TEAMModelOS.SDK.Models.Cosmos.Common.Inner;
- using TEAMModelOS.SDK.Models.Service;
- using Microsoft.Extensions.Configuration;
- using HTEXLib.COMM.Helpers;
- using TEAMModelOS.SDK.DI.CoreAPI;
- using TEAMModelOS.SDK.Models.Dtos;
- using Microsoft.Extensions.Hosting;
- using Microsoft.AspNetCore.Hosting;
- using DocumentFormat.OpenXml.Office2010.Excel;
- namespace TEAMModelOS.Controllers
- {
- [ProducesResponseType(StatusCodes.Status200OK)]
- [ProducesResponseType(StatusCodes.Status400BadRequest)]
-
- [Route("school/correct")]
- [ApiController]
- public class CorrectController : ControllerBase
- {
- private readonly AzureRedisFactory _azureRedis;
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly SnowflakeId _snowflakeId;
- private readonly AzureServiceBusFactory _serviceBus;
- private readonly DingDing _dingDing;
- private readonly Option _option;
- private readonly AzureStorageFactory _azureStorage;
- private readonly IConfiguration _configuration;
- private readonly NotificationService _notificationService;
- private readonly CoreAPIHttpService _coreAPIHttpService;
- private readonly IWebHostEnvironment _environment;
- public CorrectController(IWebHostEnvironment environment,CoreAPIHttpService coreAPIHttpService,AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing, IOptionsSnapshot<Option> option, IConfiguration configuration, NotificationService notificationService,
- AzureRedisFactory azureRedis, AzureStorageFactory azureStorage)
- {
- _environment = environment;
- _azureCosmos = azureCosmos;
- _serviceBus = serviceBus;
- _snowflakeId = snowflakeId;
- _dingDing = dingDing;
- _option = option?.Value;
- _azureRedis = azureRedis;
- _azureStorage = azureStorage;
- _configuration = configuration;
- _notificationService = notificationService;
- _coreAPIHttpService = coreAPIHttpService;
- }
- ///<summary>
- ///查询教师的阅卷任务列表
- /// </summary>
- /// <data>
- /// ! "code":"tmdid"
- /// </data>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("find-task")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> FindTask(JsonElement request)
- {
- List<CorrectTask> tasks = new List<CorrectTask>();
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- //活动分区
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var (_, _, _, school) = HttpContext.GetAuthTokenInfo();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<CorrectTask>(queryText: $"select value(c) from c where c.scode = 'Correct-{school}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"CorrectTask-{code}") }))
- {
- tasks.Add(item);
- }
- return Ok(new { tasks = tasks });
- }
- catch (CosmosException ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},common/Correct/find-task()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return Ok(new { tasks = tasks });
- }
- }
- /*
- {
- "id":"uuid",//新增为null或者空
- "code":"hbcn",
- "owner":"school",
- "name":"xxx评测-阅卷",
- "creatorId":"1558635535",
- "progress":"pending 待发布|going 已发布|finish 已结束",
- "scope":"school",
- "startTime":158556666658,//评测结束的时间
- "createTime":158556666658,//当前时间
- "endTime":158556666658,//指定一个结束时间
- "examType":"评测活动的类型",
- "scode":"评测的源数据code值",
- "mode":"阅卷模式,1 按题目,0 按人/学生",
- "corSubs":[//科目的设置
- {
- "id":"科目id",
- "corTmdids":[//设置的醍摩豆账号
- {
- "tmdid":"1558635535,评卷教师的id",
- "corCount":100
- },
-
- ]
- }
- ]
- }
- */
- /// <summary>
- /// 新增 或 修改阅卷设置
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("upsert")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> Upsert(Correct request)
- {
- try
- {
- //新增阅卷活动设置
- var client = _azureCosmos.GetCosmosClient();
- request.pk = $"Correct";
- request.code = $"Correct-{request.code}";
- request.ttl = -1;
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- request.createTime = now;
- var (userid, name, _, school) = HttpContext.GetAuthTokenInfo();
- //取得学校基本信息
- var schresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(school.ToString(), new PartitionKey("Base"));
- string schname = string.Empty;
- if (schresponse.Status == 200)
- {
- using var schjson = await JsonDocument.ParseAsync(schresponse.ContentStream);
- schjson.RootElement.TryGetProperty("name", out JsonElement jsonschname);
- schname = jsonschname.ToString();
- }
- //如果设置的时间是小于当前时间则立即发布
- if (request.startTime <= 0)
- {
- request.startTime = now;
- }
- if (string.IsNullOrEmpty(request.id))
- {
- request.id = Guid.NewGuid().ToString();
- if (request.startTime > now)
- {
- request.progress = "pending";
- }
- else
- {
- request.progress = "going";
- }
- request.subs.Select(r => r.markers).ToList();
- request = await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(request, new PartitionKey($"{request.code}"));
- }
- else
- {
- var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(request.id, new PartitionKey($"{request.code}"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- var info = json.ToObject<Correct>();
- if (info.progress.Equals("going"))
- {
- return Ok(new { v = "活动正在进行中" });
- }
- if (request.startTime > now)
- {
- request.progress = "pending";
- }
- else
- {
- request.progress = "going";
- }
- request.progress = info.progress;
- request = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(request, info.id, new PartitionKey($"{info.code}"));
- }
- else
- {
- if (request.startTime > now)
- {
- request.progress = "pending";
- }
- else
- {
- request.progress = "going";
- }
- request = await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(request, new PartitionKey($"{request.code}"));
- }
- }
- string bizcode = "scoring-mark";
- List<string> ids = new List<string>();
- foreach (CorSub sub in request.subs)
- {
- foreach (CorTmd tmd in sub.markers)
- {
- ids.Add(tmd.id);
- }
- }
- Notification notification = new Notification
- {
- hubName = "hita",
- type = "msg",
- from = $"ies5:{_option.Location}:private",
- to = ids,
- label = $"{bizcode}_school",
- body = new { location = _option.Location,
- biz = bizcode,
- tmdid = userid,
- tmdname = name.ToString(),
- schoolcode = school,
- schoolname = $"{schname}",
- examname = request.name,
- status = 1,
- time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
- }.ToJsonString(),
- expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
- };
- var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
- var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
- var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
- var location = _option.Location;
- await _notificationService.SendNotification(clientID, clientSecret, location, url, notification);
- string sql = $"select c.id, c.name ,c.lang as code from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))})";
- List<IdNameCode> idNameCodes = new List<IdNameCode>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIterator<IdNameCode>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- idNameCodes.Add(item);
- }
- _coreAPIHttpService.PushNotify(idNameCodes, $"{bizcode}_school", Constant.NotifyType_IES5_Task,
- new Dictionary<string, object> { { "tmdname", name }, { "schooName", schname }, { "schoolId", $"{school}" }, { "tmdid", userid } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
- return Ok(new { vote = request });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},common/Correct/upsert()\n{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest(e.StackTrace);
- }
- }
- ///<summary>
- ///
- /// </summary>
- /// <data>
- /// ! "id":"3c075347-75ef-4bcb-ae03-68678d02d5ef", //评测id
- /// ! "code":"hbcn"//
- /// </data>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("find-id")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> FindById(JsonElement request)
- {
- try
- {
- //活动id
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- //活动分区
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- Correct correct = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Correct>(id.GetString(), new PartitionKey($"Correct-{code}"));
- return Ok(new { correct });
- }
- catch (CosmosException ex)
- {
- Correct correct = null;
- return Ok(new { correct, status = ex.Status });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},common/Correct/find-id()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- Correct correct = null;
- return Ok(new { correct });
- }
- }
- [ProducesDefaultResponseType]
- [HttpPost("delete-task")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> delete(JsonElement request)
- {
- try
- {
- //活动id
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- //活动分区
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- List<SDK.Models.Cosmos.Common.Scoring> attr = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<SDK.Models.Cosmos.Common.Scoring>(
- queryText: $"select value(c) from c where c.examId = '{id}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
- {
- attr.Add(item);
- }
- await client.GetContainer(Constant.TEAMModelOS, "Teacher").DeleteItemsAsync<SDK.Models.Cosmos.Common.Scoring>(attr.Select(a => a.id).ToList(), $"Scoring-{code}");
- //var cresponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Scoring-{code}"));
- //删除阅卷配置
- var cresponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Correct-{code}"));
- if (cresponse.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(cresponse.ContentStream);
- Correct correct = json.ToObject<Correct>();
- if (correct.subs.IsNotEmpty())
- {
- foreach (var sub in correct.subs)
- {
- //List<string> correctIds = new List<string>();
- if (sub.markers.IsNotEmpty())
- {
- foreach (var marker in sub.markers)
- {
- await ExamService.deleteAsync(client, id.GetString(), marker.id);
- }
- }
- if (sub.err.Count > 0)
- {
- foreach (var tId in sub.err)
- {
- await ExamService.deleteAsync(client, id.GetString(), tId);
- }
- }
- if (sub.arb.Count > 0)
- {
- foreach (var tId in sub.arb)
- {
- await ExamService.deleteAsync(client, id.GetString(), tId);
- }
- }
- }
- }
- await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(id.GetString(), new PartitionKey($"Correct-{code}"));
- return Ok(new { id });
- }
- else
- {
- return Ok(new { code = 404 });
- }
- }
- catch (CosmosException ex)
- {
- Correct correct = null;
- return Ok(new { correct, status = ex.Status });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},common/Correct/find-id()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- Correct correct = null;
- return Ok(new { correct });
- }
- }
- }
- }
|