1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750 |
- using Azure.Cosmos;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Options;
- using System;
- using System.Collections.Generic;
- using System.Dynamic;
- using System.IdentityModel.Tokens.Jwt;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK;
- using TEAMModelOS.SDK.Context.Constant.Common;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.DI.AzureCosmos.Inner;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
- using TEAMModelOS.SDK.Helper.Common.StringHelper;
- using TEAMModelOS.SDK.Models.Cosmos.Common;
- using TEAMModelOS.SDK.Models.Table;
- using Azure.Messaging.ServiceBus;
- using Microsoft.Extensions.Configuration;
- namespace TEAMModelOS.Controllers
- {
- [ProducesResponseType(StatusCodes.Status200OK)]
- [ProducesResponseType(StatusCodes.Status400BadRequest)]
- //[Authorize(Roles = "IES5")
- [Route("common/exam")]
- [ApiController]
- public class ExamController : ControllerBase
- {
- 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 AzureRedisFactory _azureRedis;
- public IConfiguration _configuration { get; set; }
- public ExamController(AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing,
- IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, IConfiguration configuration)
- {
- _azureCosmos = azureCosmos;
- _serviceBus = serviceBus;
- _snowflakeId = snowflakeId;
- _dingDing = dingDing;
- _option = option?.Value;
- _azureStorage = azureStorage;
- _azureRedis = azureRedis;
- _configuration = configuration;
- }
- /// <summary>
- /// 保存考试信息
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Teacher")]
- [HttpPost("save")]
- public async Task<IActionResult> Save(ExamInfo request)
- {
- try
- {
- //新增
- //string code = request.code;
- var client = _azureCosmos.GetCosmosClient();
- ExamInfo exam;
- string code = request.code;
- request.ttl = -1;
- request.code = "Exam-" + request.code;
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- request.createTime = now;
- if (request.startTime <= 0)
- {
- request.startTime = now;
- }
- int stuCount = 0;
- for (int i = 0; i < request.classes.Count; i++)
- {
- List<string> ids = new List<string>();
- //处理班级人数(公共部分的校本名单)
- //List<Student> students = new List<Student>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Student").GetItemQueryStreamIterator(queryText: $"select c.id from c where c.classId = '{request.classes[i]}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{request.school}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- ids.Add(account.GetProperty("id").GetString());
- }
- }
- }
- if (request.scope.Equals("private"))
- {
- //处理发布对象为自选名单(个人)
- List<StuList> stuLists = new List<StuList>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<StuList>(queryText: $"select value(c) from c where c.id = '{request.classes[i]}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList") }))
- {
- stuLists.Add(item);
- }
- if (stuLists.Count > 0)
- {
- foreach (StuList stuList in stuLists)
- {
- foreach (Students students in stuList.students)
- {
- if (students.code.Contains(code))
- {
- if (!ids.Contains(students.id))
- {
- ids.Add(students.id);
- }
- }
- else
- {
- ids.Add(students.id);
- }
- }
- if (stuList.tmids.Count > 0)
- {
- foreach (string tid in stuList.tmids)
- {
- ids.Add(tid);
- }
- }
- }
- }
- }
- else
- {
- //request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"exam/{request.id}");
- //发布对象为自选名单(校本)
- List<StuList> stuLists = new List<StuList>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<StuList>(queryText: $"select value(c) from c where c.id = '{request.classes[i]}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList-{request.school}") }))
- {
- stuLists.Add(item);
- }
- if (stuLists.Count > 0)
- {
- foreach (StuList stuList in stuLists)
- {
- foreach (Students students in stuList.students)
- {
- if (students.code.Contains(code))
- {
- if (!ids.Contains(students.id))
- {
- ids.Add(students.id);
- }
- }
- else
- {
- ids.Add(students.id);
- }
- }
- }
- }
- }
- stuCount += ids.Count;
- }
- request.stuCount = stuCount;
- if (string.IsNullOrEmpty(request.id))
- {
- request.id = Guid.NewGuid().ToString();
- if (request.startTime > now)
- {
- request.progress = "pending";
- }
- else
- {
- request.progress = "going";
- }
- var messageBlob = new ServiceBusMessage();
- if (request.scope.Equals("school"))
- {
- request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"exam/{request.id}");
- messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "insert", root = $"exam/{request.id}", name = request.school }.ToJsonString());
- }
- else
- {
- request.size = await _azureStorage.GetBlobContainerClient(request.creatorId).GetBlobsSize($"exam/{request.id}");
- messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "insert", root = $"exam/{request.id}", name = request.creatorId }.ToJsonString());
- }
- messageBlob.ApplicationProperties.Add("name", "BlobRoot");
- var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
- await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
- int n = 0;
- foreach (PaperSimple simple in request.papers)
- {
- simple.blob = "/exam/" + request.id + "/paper/" + request.subjects[n].id;
- n++;
- }
- //request.papers
- /*long SequenceNumber = await _serviceBus.GetServiceBusClient().SendLeamMessage<ExamInfo>(Constants.TopicName, request.id, request.code, request.startTime);
- request.sequenceNumber = SequenceNumber;*/
- //await _azureStorage.GetBlobContainerClient("hbcn").GetBlobsCatalogSize($"exam/{request.id}");
- exam = await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(request, new PartitionKey($"{request.code}"));
- //await _serviceBus.GetServiceBusClient().SendLeamMessage<ExamInfo>(Constants.TopicName, request.id, request.code, request.startTime);
- //request.sequenceNumber = SequenceNumber;
- }
- else
- {
- ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(request.id, new PartitionKey($"{request.code}"));
- if (info.progress.Equals("going"))
- {
- return Ok(new { v = "活动正在进行中" });
- }
- var messageBlob = new ServiceBusMessage();
- if (request.scope.Equals("school"))
- {
- request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"exam/{request.id}");
- messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = $"exam/{request.id}", name = request.school }.ToJsonString());
- }
- else
- {
- request.size = await _azureStorage.GetBlobContainerClient(request.creatorId).GetBlobsSize($"exam/{request.id}");
- messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = $"exam/{request.id}", name = request.creatorId }.ToJsonString());
- }
- messageBlob.ApplicationProperties.Add("name", "BlobRoot");
- var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
- await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
- request.progress = info.progress;
- int n = 0;
- foreach (PaperSimple simple in request.papers)
- {
- simple.blob = "/exam/" + request.id + "/paper/" + request.subjects[n].id;
- n++;
- }
- /* await _serviceBus.GetServiceBusClient().cancelMessage(Constants.TopicName, info.sequenceNumber);
- long SequenceNumber = await _serviceBus.GetServiceBusClient().SendLeamMessage<ExamInfo>(Constants.TopicName, request.id, request.code, request.startTime);
- request.sequenceNumber = SequenceNumber;*/
- exam = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(request, request.id, new PartitionKey($"{request.code}"));
- //await _serviceBus.GetServiceBusClient().SendLeamMessage<ExamInfo>(Constants.TopicName, request.id, request.code, request.startTime);
- }
- //Survey homeWork = await _azureCosmos.SaveOrUpdate<Survey>(request.survey);
- //设定结束时间
- //string msgEndId = _snowflakeId.NextId() + "";
- //await _serviceBus.GetServiceBusClient().SendLeamMessage<ExamInfo>(Constants.TopicName, request.id, request.code, request.endTime);
- return Ok(new { exam });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/save()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //TODO blob 批量删除
- /// <summary>
- /// 删除
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Teacher")]
- [HttpPost("delete")]
- public async Task<IActionResult> Delete(JsonElement request)
- {
- /* ResponseBuilder builder = ResponseBuilder.custom();
- IdPk items = await _azureCosmos.DeleteAsync<ExamInfo>(request.id, request.pk);
- await _azureCosmos.DeleteAll<Paper>(new Dictionary<string, object>() { { "code", request.id } });
- return builder.Data(items).build();*/
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- //string school_code = code.ToString().Substring(typeof(ExamClassResult).Name.Length + 1);
- var response = await client.GetContainer("TEAMModelOS", "Common").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Exam-{code}"));
- //删除blob 相关资料
- await _azureStorage.GetBlobServiceClient().DelectBlobs(code.ToString(), $"exam/{id}");
- //通知评测删除信息
- var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "delete", root = $"exam/{id}", name = $"{code}" }.ToJsonString());
- messageBlob.ApplicationProperties.Add("name", "BlobRoot");
- var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
- await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
- List<ExamClassResult> examClassResults = new List<ExamClassResult>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(queryText: $"select c.id from c where c.examId = '{id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
- {
- examClassResults.Add(item);
- }
- List<string> resultIds = new List<string>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: $"select c.id from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamResult-{id}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- resultIds.Add(account.GetProperty("id").GetString());
- }
- }
- }
- foreach (ExamClassResult classResult in examClassResults)
- {
- await client.GetContainer("TEAMModelOS", "Common").DeleteItemStreamAsync(classResult.id, new PartitionKey($"ExamClassResult-{code}"));
- }
- await client.GetContainer("TEAMModelOS", "Common").DeleteItemsStreamAsync(resultIds, $"ExamResult-{id}");
- /*foreach (ExamResult result in results)
- {
- await client.GetContainer("TEAMModelOS", "Common").DeleteItemStreamAsync(result.id, new PartitionKey($"ExamResult-{id}"));
- }*/
- //await _azureCosmos.DeleteAll(examClassResults);
- return Ok(new { id });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/delete()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 查询考试信息
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Teacher")]
- [HttpPost("find")]
- public async Task<IActionResult> Find(JsonElement requert)
- {
- try
- {
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- List<SchoolYear> years = await _azureStorage.FindListByDict<SchoolYear>(new Dictionary<string, object>() { { "RowKey", code }, { "PartitionKey", "Exam" } });
- int year = 0;
- if (years.Count > 0)
- {
- year = years[0].year;
- }
- else
- {
- long ct = 0;
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: "SELECT top 1 c.createTime FROM c order by c.createTime ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Exam-{code}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- ct = account.GetProperty("createTime").GetInt64();
- }
- }
- }
- year = DateTimeOffset.FromUnixTimeMilliseconds(ct).Year;
- SchoolYear sy = new()
- {
- RowKey = code.ToString(),
- PartitionKey = "Exam",
- year = year
- };
- await _azureStorage.Save<SchoolYear>(sy);
- }
- var query = $"select c.id,c.name,c.code,c.period,c.startTime,c.endTime,c.stuCount,c.type,c.progress,c.examType,c.createTime,c.source, c.subjects, c.grades, c.scope,c.classes,c.sRate,c.lostStu from c ";
- if (requert.TryGetProperty("classIds", out JsonElement classIds))
- {
- List<string> ids = classIds.ToObject<List<string>>();
- HashSet<string> strs = new HashSet<string>();
- if (ids.Count > 1)
- {
- foreach (string id in ids)
- {
- strs.Add($"array_contains(c.classes,'{id}')");
- }
- }
- else
- {
- string ssr = ids.Count > 0 ? ids[0] : "";
- strs.Add($"array_contains(c.classes,'{ssr}')");
- }
- string ss = string.Join(" or ", strs);
- query = $"select c.id,c.name,c.code,c.period,c.startTime,c.endTime,c.stuCount,c.type,c.progress,c.examType,c.createTime, c.source,c.subjects, c.grades, c.scope,c.classes,c.sRate,c.lostStu from c where ({ss})";
- };
- string continuationToken = string.Empty;
- string token = default;
- //是否需要进行分页查询,默认不分页
- bool iscontinuation = false;
- if (requert.TryGetProperty("token", out JsonElement token_1))
- {
- token = token_1.GetString();
- iscontinuation = true;
- };
- //默认不指定返回大小
- int? topcout = null;
- if (requert.TryGetProperty("count", out JsonElement jcount))
- {
- if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
- {
- topcout = data;
- }
- }
- List<ExamInfo> examInfo = new List<ExamInfo>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query, continuationToken: token, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout, PartitionKey = new PartitionKey($"Exam-{code}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- //obj.TryGetProperty("progress", out JsonElement progress);
- examInfo.Add(obj.ToObject<ExamInfo>());
- }
- }
- if (iscontinuation)
- {
- continuationToken = item.GetContinuationToken();
- break;
- }
- }
- //List<string> examIds = new List<string>();
- /* List<ExamResult> examResults = new List<ExamResult>();
- foreach (ExamInfo info in examInfos) {
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamResult>(
- queryText: $"select value(c) from c where c.examId = '{info.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamResult-{info.id}") }))
- {
- examResults.Add(item);
- }
- }*/
- /* List<(string id, double scores)> listExamInfo = new List<(string id, double scores)>();
- foreach (ExamInfo info in examInfos)
- {
- //记录某次考试所有学生得分总分
- double score = 0;
- double allScore = 0;
- int stuCount = 0;
- foreach (ExamResult examResult in examResults) {
- if (info.id == examResult.examId) {
- foreach (List<double> sc in examResult.studentScores) {
- score += sc.Sum();
- }
- stuCount = examResult.studentIds.Count;
- }
- }
- double ascore = stuCount > 0 ? Math.Round(score * 0.1 / stuCount, 2) : 0;
- foreach (PaperSimple simple in info.papers) {
- allScore += simple.point.Sum();
- }
- listExamInfo.Add((info.id, (allScore> 0 ? ascore / allScore * 100: 0)));
- }
- var examInfo = examInfos.Select(o =>
- new
- {
- o.id,
- o.scope,
- o.stuCount,
- o.name,
- o.period,
- o.startTime,
- o.endTime,
- o.type,
- o.progress,
- o.examType,
- o.createTime,
- o.subjects,
- o.grades,
- o.classes,
- score = listExamInfo.FirstOrDefault(c => c.id == o.id).scores,
- }
- );*/
- return Ok(new { examInfo, token = continuationToken, year });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Teacher")]
- [HttpPost("find-summary")]
- public async Task<IActionResult> FindSummary(JsonElement requert)
- {
- try
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //if (!requert.TryGetProperty("id_token", out JsonElement id_token)) return BadRequest();
- if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- //if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
- //var jwt = new JwtSecurityToken(id_token.GetString());
- //if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.Ordinal)) return BadRequest();
- //var id = jwt.Payload.Sub;
- var client = _azureCosmos.GetCosmosClient();
- List<ExamInfo> examInfo = new List<ExamInfo>();
- //var query = $"select value(c) from c ";
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: $"select value(c) from c where c.id = '{id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{code}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- //obj.TryGetProperty("progress", out JsonElement progress);
- examInfo.Add(obj.ToObject<ExamInfo>());
- }
- }
- }
- return Ok(new { examInfo });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/FindSummary()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 学生回答问题
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Teacher")]
- [HttpPost("upsert-record")]
- public async Task<IActionResult> upsertRecord(JsonElement request)
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- //if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("answer", out JsonElement answer)) return BadRequest();
- if (!request.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- if (!request.TryGetProperty("classId", out JsonElement classId)) return BadRequest();
- if (!request.TryGetProperty("multipleRule", out JsonElement multipleRule)) return BadRequest();
- //if (!request.TryGetProperty("answers ", out JsonElement tandardAnswer)) return BadRequest();
- if (!request.TryGetProperty("paperId", out JsonElement paperId)) return BadRequest();
- //根据不同评测的类型返回对应的编码
- if (!request.TryGetProperty("code", out JsonElement school)) return BadRequest();
- if (!request.TryGetProperty("scode", out JsonElement scode)) return BadRequest();
- try
- {
- List<string> ids = new List<string>();
- ids = classId.ToObject<List<string>>();
- var client = _azureCosmos.GetCosmosClient();
- List<ExamClassResult> examClassResults = new List<ExamClassResult>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(
- queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.info.id in ({string.Join(",", ids.Select(o => $"'{o}'"))})",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- examClassResults.Add(obj.ToObject<ExamClassResult>());
- }
- }
- }
- ExamClassResult classResult = new ExamClassResult();
- List<PaperSimple> standerAnswers = new List<PaperSimple>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(
- queryText: $"select A0.point,A0.answers from c join A0 in c.papers where c.id = '{id}'and A0.id = '{paperId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- standerAnswers.Add(obj.ToObject<PaperSimple>());
- }
- }
- }
- List<List<string>> ans = answer.ToObject<List<List<string>>>();
- List<List<string>> standard = new List<List<string>>();
- List<double> points = new List<double>();
- int rule = int.Parse(multipleRule.ToString());
- foreach (PaperSimple simple in standerAnswers)
- {
- standard = simple.answers;
- points = simple.point;
- }
- List<Task<string>> tasks = new List<Task<string>>();
- foreach (ExamClassResult result in examClassResults)
- {
- int index = result.studentIds.IndexOf(studentId.ToString());
- //存放客观题作答详情
- if (result.ans.Count == 0)
- {
- foreach (string cc in result.studentIds)
- {
- List<List<string>> anc = new List<List<string>>();
- foreach (List<string> opc in standard)
- {
- anc.Add(new List<string>());
- }
- result.ans.Add(anc);
- }
- }
- //List<List<string>> oq = new List<List<string>>();
- //classResult.studentAnswers[index] = ans;
- if (index == -1)
- {
- List<double> ansPoint = new List<double>();
- foreach (List<string> num in standard)
- {
- //ans.Add(new List<string>());
- ansPoint.Add(-1);
- }
- result.studentIds.Add(studentId.ToString());
- result.studentScores.Add(ansPoint);
- result.studentAnswers.Add(new List<string>());
- result.sum.Add(0);
- }
- //int flagCount = 0;
- /*foreach (List<string> str in ans) {
- if (str.Count == 0) {
- flagCount++;
- }
- } */
- int newIndex = result.studentIds.IndexOf(studentId.ToString());
- /* if (flagCount != standard.Count)
- {*/
- StringBuilder builder = new StringBuilder();
- builder.Append(result.examId).Append("/");
- builder.Append(result.subjectId).Append("/");
- builder.Append(studentId).Append("/");
- builder.Append("ans.json");
- /*string FileName = result.examId + "/" + result.subjectId + "/" + studentId;
- string blob = FileName + "/" + "ans.json";*/
- tasks.Add(_azureStorage.UploadFileByContainer(school.ToString(), ans.ToJsonString(), "exam", builder.ToString(), false));
- result.studentAnswers[newIndex].Add(builder.ToString());
- //}
- //List<(int index ,string content, double count)> acount = new List<(int index,string content, double count)>();
- for (int i = 0; i < ans.Count; i++)
- {
- //List<string> op = new List<string>();
- var ac = ans[i].Count;
- var sc = standard[i].Count;
- //记录次数
- int n = 0;
- //result.studentAnswers[index][i] = ans[i];
- //算分处理
- if (sc > 0)
- {
- result.ans[index][i] = ans[i];
- if (ac == sc && sc == 1)
- {
- foreach (string right in ans[i])
- {
- if (standard[i].Contains(right))
- {
- result.studentScores[newIndex][i] = points[i];
- }
- else
- {
- result.studentScores[newIndex][i] = 0;
- }
- }
- }
- else
- {
- if (rule > 0)
- {
- int falseCount = 0;
- if (ac > 0)
- {
- foreach (string obj in ans[i])
- {
- if (!standard[i].Contains(obj))
- {
- falseCount++;
- }
- }
- switch (rule)
- {
- case 1:
- if (ac == sc)
- {
- if (falseCount == 0)
- {
- result.studentScores[newIndex][i] = points[i];
- }
- else
- {
- result.studentScores[newIndex][i] = 0;
- }
- }
- else
- {
- result.studentScores[newIndex][i] = 0;
- }
- break;
- case 2:
- if (falseCount > 0)
- {
- result.studentScores[newIndex][i] = 0;
- }
- else
- {
- if (ac == sc)
- {
- result.studentScores[newIndex][i] = points[i];
- }
- else
- {
- result.studentScores[newIndex][i] = points[i] / 2;
- }
- }
- break;
- case 3:
- if (falseCount > 0)
- {
- result.studentScores[newIndex][i] = 0;
- }
- else
- {
- if (ac == sc)
- {
- result.studentScores[newIndex][i] = points[i];
- }
- else
- {
- result.studentScores[newIndex][i] = System.Math.Round((double)ac / sc * points[i], 1);
- }
- }
- break;
- case 4:
- if (ac == sc)
- {
- result.studentScores[newIndex][i] = points[i];
- }
- else
- {
- double persent = (double)(sc - 2 * falseCount) / sc;
- if (persent <= 0)
- {
- result.studentScores[newIndex][i] = 0;
- }
- else
- {
- result.studentScores[newIndex][i] = System.Math.Round(persent * points[i], 1);
- }
- }
- break;
- }
- }
- else
- {
- result.studentScores[newIndex][i] = 0;
- }
- }
- }
- }
- }
- /*if (result.studentScores.Contains(-1)) {
- }*/
- bool flag = true;
- foreach (List<double> scores in result.studentScores)
- {
- foreach (double score in scores)
- {
- if (score == -1)
- {
- flag = false;
- break;
- }
- }
- }
- if (flag)
- {
- ExamInfo exam = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{scode}"));
- result.progress = true;
- /*//标记单科单班总得分
- double score = 0;
- //标准差
- double powSum = 0;
- var scount = result.studentIds.Count;
- foreach (List<double> sc in result.studentScores) {
- score += sc.Sum();
- }
- foreach (string sid in result.studentIds) {
- double ssc = result.studentScores[result.studentIds.IndexOf(sid)].Sum();
- powSum += Math.Pow(ssc - scount > 0 ? Math.Round(score * 1.0 / scount, 2) : 0, 2);
- }
- result.standard = Math.Round(scount > 0 ? Math.Pow(powSum / scount, 0.5) : 0, 2);
- result.average = scount > 0 ? Math.Round(score / scount, 2) : 0;*/
- exam.subjects.ForEach(s =>
- {
- if (s.id.Equals(subjectId.ToString()))
- {
- s.classCount += 1;
- }
- });
- await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"{scode}"));
- }
- result.sum[newIndex] = result.studentScores[newIndex].Sum();
- classResult = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
- }
- await Task.WhenAll(tasks);
- return Ok(new { classResult });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/upsertRecord()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Teacher")]
- [HttpPost("upsert-record-by-teacher")]
- public async Task<IActionResult> upsertRecordByTeacher(JsonElement request)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("point", out JsonElement point)) return BadRequest();
- if (!request.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
- //if (!request.TryGetProperty("classId", out JsonElement classId)) return BadRequest();
- //此参数表明此次操作对象为个人还是校本的评测内容
- if (!request.TryGetProperty("school", out JsonElement school)) return BadRequest();
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- //要先处理状态,判断卷子是否存在,并判断卷子归属的考试是否允许再次提交
- //List<ExamInfo> exams = await _azureCosmos.FindByDict<ExamInfo>(new Dictionary<string, object> { { "id", request.examCode } });
- List<double> ans = point.ToObject<List<double>>();
- var client = _azureCosmos.GetCosmosClient();
- List<ExamClassResult> examClassResults = new List<ExamClassResult>();
- if (request.TryGetProperty("classId", out JsonElement classId))
- {
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
- queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.info.id = '{classId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
- {
- examClassResults.Add(item);
- }
- }
- else
- {
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
- queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and array_contains(c.studentIds,'{studentId}')",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
- {
- examClassResults.Add(item);
- }
- }
- ExamClassResult classResult = new ExamClassResult();
- //ExamInfo classResult = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{code}"));
- //ExamClassResult classResult = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamClassResult>(id.ToString(), new PartitionKey($"{code}"));
- /*foreach (double index in ans) {
- classResult.studentScores.in
- }*/
- foreach (ExamClassResult result in examClassResults)
- {
- int index = result.studentIds.IndexOf(studentId.ToString());
- for (int i = 0; i < ans.Count; i++)
- {
- result.studentScores[index][i] = ans[i];
- }
- if (!result.progress)
- {
- bool flag = true;
- foreach (List<double> scores in result.studentScores)
- {
- foreach (double score in scores)
- {
- if (score == -1)
- {
- flag = false;
- break;
- }
- }
- }
- if (flag)
- {
- ExamInfo exam = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
- result.progress = true;
- exam.subjects.ForEach(s =>
- {
- if (s.id.Equals(subjectId.ToString()))
- {
- s.classCount += 1;
- }
- });
- await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"Exam-{code}"));
- }
- }
- else
- {
- ExamInfo exam = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
- exam.updateTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"Exam-{code}"));
- }
- result.sum[index] = result.studentScores[index].Sum();
- classResult = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
- }
- return Ok(new { classResult });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/upsertRecordByTeacher()\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- /*if (exams.IsNotEmpty())
- {
- ExamInfo examInfo = exams[0];
- //提交答案时间必须是状态已发布,且时间在起止时间内
- if (examInfo.startTime <= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() && examInfo.status == 200 &&
- examInfo.endTime >= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
- {
- return builder.Data(await _azureCosmos.SaveOrUpdate(request)).build();
- }
- else
- {
- return builder.Error(ResponseCode.FAILED, "请在作答时间段内提交答案!").build();
- }
- }
- else
- {
- return builder.Error(ResponseCode.DATA_EXIST, "考试不存在!").build();
- }*/
- }
- /// <summary>
- /// 查询评测详细信息(教师或者学生通用)
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Teacher")]
- [HttpPost("find-summary-record")]
- public async Task<IActionResult> findSummaryRecord(JsonElement requert)
- {
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- //if (!requert.TryGetProperty("code", out JsonElement school_code)) return BadRequest();
- if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- if (!requert.TryGetProperty("code", out JsonElement school_code)) return BadRequest();
- if (!requert.TryGetProperty("classId", out JsonElement classId)) return BadRequest();
- // 如果只有学生id则返回学生参加过的考试 只返回相关摘要信息
- var client = _azureCosmos.GetCosmosClient();
- //string code = school_code.ToString().Substring(5);
- //ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{school_code}"));
- List<object> examClassResults = new List<object>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: $"select c.id, c.code,c.info,c.studentIds,c.studentAnswers,c.studentScores,c.mark from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.info.id = '{classId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school_code}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- examClassResults.Add(obj.ToObject<object>());
- }
- }
- }
- /*if (StringHelper.getKeyCount(requert) == 1 && requert.TryGetProperty("code", out JsonElement code))
- {
- List<object> props = new List<object>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Student").GetItemQueryStreamIterator(queryText: $"select c.id, c.code, c.examCode, c.status ,c.mark, c.score from c where c.id = {id}", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamRecord-{school_code}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- props.Add(obj.ToObject<object>());
- }
- }
- }
- return Ok(new { props });
- }
- else
- {
- if (requert.TryGetProperty("examCode", out JsonElement _))
- {
- //List<string> props = new List<string> { "id", "code", "examCode", "status", "mark", "score" };
- //List<ExamRecord> examRecords = await _azureCosmos.FindByDict<ExamRecord>(request, props);
- //return builder.Data(examRecords).Extend(new Dictionary<string, object> { { "props", props } }).build();
- List<object> props = new List<object>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Student").GetItemQueryStreamIterator(queryText: $"select c.id, c.code, c.examCode, c.status ,c.mark, c.score from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamRecord-{school_code}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- props.Add(obj.ToObject<object>());
- }
- }
- }
- return Ok(new { props });
- }
- }*/
- return Ok(new { examClassResults });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findSummaryRecord()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //学生端查询评测列表
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Student")]
- [HttpPost("find-summary-by-student")]
- public async Task<IActionResult> findSummaryStudent(JsonElement requert)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- //if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!requert.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
- if (!requert.TryGetProperty("code", out JsonElement school)) return BadRequest();
- if (!requert.TryGetProperty("scode", out JsonElement scode)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- var query = $"select c.id,c.code,c.school,c.creatorId,c.progress,A0.id paperId,A0.code paperCode,A0.name paperName,A0.multipleRule,A0.scope,A0.blob from c join A0 in c.papers where c.id ='{id}'";
- List<object> papers = new List<object>();
- List<object> subjects = new List<object>();
- List<string> classIds = new List<string>();
- //存放当前学生所在班级ID或者名单ID
- HashSet<string> resultIds = new HashSet<string>();
- //List<string> ids = new List<string>();
- //处理班级人数(公共部分的校本名单)
- //List<Student> students = new List<Student>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Student").GetItemQueryStreamIterator(queryText: $"select c.classId id from c where c.id = '{studentId}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{school}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- resultIds.Add(account.GetProperty("id").GetString());
- }
- }
- }
- //获取自定义名单信息
- List<StuList> stuLists = new List<StuList>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<StuList>(queryText: $"select c.id from c join A0 in c.students where A0.id = '{studentId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList") }))
- {
- stuLists.Add(item);
- }
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<StuList>(queryText: $"select c.id from c join A0 in c.students where A0.id = '{studentId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList-{school}") }))
- {
- stuLists.Add(item);
- }
- if (stuLists.Count > 0)
- {
- foreach (StuList stuList in stuLists)
- {
- resultIds.Add(stuList.id);
- }
- }
- var queryClassId = $"select c.classes id from c where c.id ='{id}'";
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: queryClassId, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- classIds = obj.GetProperty("id").ToObject<List<string>>();
- //classIds = obj.ToObject<List<string>>();
- }
- }
- }
- //存放该学生所在班级参与当前评测的ID
- List<string> infoIds = new List<string>();
- foreach (string ids in resultIds)
- {
- if (classIds.Contains(ids))
- {
- infoIds.Add(ids);
- }
- }
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- papers.Add(obj.ToObject<object>());
- }
- }
- }
- var querySubject = $"select A0.id,A0.name from c join A0 in c.subjects where c.id ='{id}'";
- //List<object> props = new List<object>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: querySubject, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- subjects.Add(obj.ToObject<object>());
- }
- }
- }
- var queryAnswers = $"select c.id,c.code,c.studentIds,c.subjectId,c.studentAnswers,c.studentScores,c.sum,c.mark from c where c.examId ='{id}' and array_contains(c.studentIds,'{studentId}') and c.pk = 'ExamClassResult' ";
- List<ExamClassResult> answers = new List<ExamClassResult>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: queryAnswers,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- answers.Add(obj.ToObject<ExamClassResult>());
- }
- }
- }
- List<List<string>> stuAns = new List<List<string>>();
- List<List<double>> stuScore = new List<List<double>>();
- List<string> mark = new List<string>();
- List<double> total = new List<double>();
- if (answers.Count > 0)
- {
- foreach (ExamClassResult result in answers)
- {
- int index = result.studentIds.IndexOf(studentId.ToString());
- if (index == -1)
- {
- break;
- }
- stuAns.Add(result.studentAnswers[index]);
- stuScore.Add(result.studentScores[index]);
- if (result.mark.Count > 0)
- {
- mark.Add(result.mark[index]);
- }
- total.Add(result.sum.Where(s => s <= 59).Count());
- total.Add(result.sum.Where(s => s > 59 && s <= 70).Count());
- total.Add(result.sum.Where(s => s > 70 && s <= 80).Count());
- total.Add(result.sum.Where(s => s > 80 && s <= 90).Count());
- total.Add(result.sum.Where(s => s > 90 && s <= 100).Count());
- }
- }
- return Ok(new { papers, subjects, stuScore, stuAns, mark, total, claId = infoIds });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-summary-by-student()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //查询学生活动列表
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Student")]
- [HttpPost("find-all-by-student")]
- public async Task<IActionResult> findAllStudent(JsonElement requert)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!requert.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
- List<string> resultIds = new List<string>();
- var client = _azureCosmos.GetCosmosClient();
- //查询校本班级ID
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(
- queryText: $"select c.id from c join A0 in c.students where A0.id = '{studentId}' and c.pk = 'Class' "))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- resultIds.Add(account.GetProperty("id").GetString());
- }
- }
- }
- //查询私人班级ID
- await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(
- queryText: $"select c.id from c join A0 in c.students where A0.id = '{studentId}' and c.pk = 'Class' "))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- resultIds.Add(account.GetProperty("id").GetString());
- }
- }
- }
- //StringBuilder builder = new StringBuilder();
- HashSet<string> strs = new HashSet<string>();
- if (resultIds.Count > 1)
- {
- foreach (string str in resultIds)
- {
- strs.Add($"array_contains(c.classes,'{str}')");
- //builder.Append($"array_contains(c.targetClassIds,'{str}')").Append("or");
- }
- //builder.ToString().Substring(0, builder.ToString().Length - 2);
- }
- else
- {
- string ssr = resultIds.Count > 0 ? resultIds[0] : "";
- strs.Add($"array_contains(c.classes,'{ssr}')");
- //builder.Append($" array_contains(c.targetClassIds,'{ssr}')");
- }
- string ss = string.Join(" or ", strs);
- //if (!requert.TryGetProperty("school", out JsonElement school)) return BadRequest();
- var query = $"select c.id,c.code,c.name,c.startTime,c.endTime,c.type,c.progress,c.school,c.scope from c where ({ss}) and c.progress != 'pending' ";
- List<object> props = new List<object>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- props.Add(obj.ToObject<object>());
- }
- }
- }
- var queryClass = $"select c.examId,c.subjectId,c.studentIds,c.studentAnswers,c.studentScores from c where array_contains(c.studentIds,'{studentId}') and c.pk = 'ExamClassResult'";
- List<ExamClassResult> Classes = new List<ExamClassResult>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: queryClass))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- Classes.Add(obj.ToObject<ExamClassResult>());
- }
- }
- }
- List<ExamClassResult> result = new List<ExamClassResult>();
- foreach (ExamClassResult classResult in Classes)
- {
- int index = classResult.studentIds.IndexOf(studentId.ToString());
- ExamClassResult result1 = new ExamClassResult();
- result1.examId = classResult.examId;
- result1.subjectId = classResult.subjectId;
- result1.studentAnswers.Add(classResult.studentAnswers[index]);
- result1.studentScores.Add(classResult.studentScores[index]);
- result.Add(result1);
- }
- return Ok(new { props, result });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findAllStudent\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //查询学生活动列表
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Student")]
- [HttpPost("find-score-by-student")]
- public async Task<IActionResult> findScoreByStudent(JsonElement requert)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- //if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- var query = $"select c.examId,c.subjectId,c.studentScores from c where array_contains(c.studentIds,'{id}') ";
- List<object> props = new List<object>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- props.Add(obj.ToObject<object>());
- }
- }
- }
- return Ok(props);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findAllStudent\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //查询学生活动列表
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Student")]
- [HttpPost("finish")]
- public async Task<IActionResult> finish(JsonElement requert)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
- info.progress = "finish";
- info.endTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- List<ExamClassResult> classResults = new();
- if (info.scope.Equals("school"))
- {
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
- queryText: $"select value(c) from c where c.examId = '{id}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.school}") }))
- {
- classResults.Add(item);
- }
- }
- else
- {
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
- queryText: $"select value(c) from c where c.examId = '{id}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.creatorId}") }))
- {
- classResults.Add(item);
- }
- }
- foreach (ExamClassResult examClass in classResults)
- {
- examClass.progress = true;
- await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(examClass, examClass.id, new PartitionKey($"{examClass.code}"));
- }
- info = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(info, info.id, new PartitionKey($"Exam-{code}"));
- return Ok(info);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/finish\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /*//查询任务列表
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Student")]
- [HttpPost("scoring")]
- public async Task<IActionResult> Scoring(JsonElement requert)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
- int index = 0;
- foreach (ExamSubject subject in info.subjects) {
- if (!subject.id.Equals(subjectId.ToString()))
- {
- index++;
- }
- else {
- break;
- }
- }
- List<string> stuAns = new();
- Dictionary<string, List<List<double>>> keyValues = new();
- List<ExamClassResult> classResults = new();
- if (info.scope.Equals("school"))
- {
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
- queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.school}") }))
- {
- classResults.Add(item);
- }
- }
- else
- {
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
- queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.creatorId}") }))
- {
- classResults.Add(item);
- }
- }
- List<List<double>> itemScore = new();
- for (int i = 0; i < info.papers[index].point.Count; i++)
- {
- List<double> score = new();
- foreach (ExamClassResult examClass in classResults)
- {
- foreach (List<double> sc in examClass.studentScores)
- {
- score.Add(sc[i]);
- }
- }
- itemScore.Add(score);
- }
- foreach (ExamClassResult examClass in classResults)
- {
- foreach (List<string> ans in examClass.studentAnswers)
- {
- if (ans.Count > 0)
- {
- stuAns.Add(ans[0]);
- }
- else
- {
- stuAns.Add("");
- }
- }
- }
- //info = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(info, info.id, new PartitionKey($"Exam-{code}"));
- return Ok(new { score = itemScore , stuAns, paper = info.papers });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/scoring\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }*/
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Student")]
- [HttpPost("scoring")]
- public async Task<IActionResult> scoring(JsonElement requert)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- if (!requert.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- var redisClient = _azureRedis.GetRedisClient(8);
- ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
- List<ExamClassResult> classResults = new();
- List<dynamic> attr = new List<dynamic>();
- //List<dynamic> all = new List<dynamic>();
- var record = await redisClient.HashGetAllAsync($"Exam:Scoring:{id}-{subjectId}");
- foreach (var rcd in record)
- {
- var value = JsonDocument.Parse(rcd.Value.ToString());
- value.RootElement.TryGetProperty("tmdId", out JsonElement tmdId);
- if (tId.ToString().Equals(tmdId.ToString()))
- {
- attr.Add(new { stuId = rcd.Name.ToString(), info = value });
- }
- }
- int index = 0;
- foreach (ExamSubject subject in info.subjects)
- {
- if (!subject.id.Equals(subjectId.ToString()))
- {
- index++;
- }
- else
- {
- break;
- }
- }
- return Ok(new { attr, paper = info.papers[index].blob });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/scoring\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //批阅,给老师随机分配阅卷数据,以及查询改老师已有的阅卷数据
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Student")]
- [HttpPost("review")]
- public async Task<IActionResult> Review(JsonElement requert)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- if (!requert.TryGetProperty("count", out JsonElement count)) return BadRequest();
- if (!requert.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- var redisClient = _azureRedis.GetRedisClient(8);
- List<ExamClassResult> classResults = new();
- List<dynamic> recs = new List<dynamic>();
- List<dynamic> all = new List<dynamic>();
- var record = await redisClient.HashGetAllAsync($"Exam:Scoring:{id}-{subjectId}");
- foreach (var rcd in record)
- {
- var value = JsonDocument.Parse(rcd.Value.ToString());
- value.RootElement.TryGetProperty("tmdId", out JsonElement tmdId);
- if (tId.ToString().Equals(tmdId.ToString()))
- {
- recs.Add(new { stuId = rcd.Name.ToString(), ans = value });
- }
- if (string.IsNullOrEmpty(tmdId.ToString()))
- {
- all.Add(new { stuId = rcd.Name.ToString(), ans = value });
- }
- }
- if (requert.TryGetProperty("stuId", out JsonElement stuId))
- {
- var stuAns = await redisClient.HashGetAsync($"Exam:Scoring:{id}-{subjectId}", stuId.ToString());
- var value = JsonDocument.Parse(stuAns.ToString());
- //保证此学生与该老师绑定
- value.RootElement.TryGetProperty("ans", out JsonElement blob);
- value.RootElement.TryGetProperty("score", out JsonElement sc);
- await redisClient.HashSetAsync($"Exam:Scoring:{id}-{subjectId}", stuId.ToString(), new { ans = blob, score = sc, tmdId = tId }.ToJsonString());
- return Ok(value);
- }
- else
- {
- if (recs.Count == count.GetInt32())
- {
- return Ok( new { msg = "分配人数已到上限"});
- }
- else
- {
- if (all.Count == 0) {
- return Ok(new { msg = "暂无可选学生" });
- }
- //随机选取一名学生打分
- Random random = new Random();
- int n = random.Next(all.Count);
- dynamic item = all[n];
- //序列化单个学生作答记录、得分情况、批注情况
- var cs = JsonSerializer.Serialize(item);
- var json = JsonDocument.Parse(cs);
- json.RootElement.TryGetProperty("stuId", out JsonElement sId);
- json.RootElement.TryGetProperty("ans", out JsonElement ans);
- ans.TryGetProperty("score", out JsonElement sc);
- ans.TryGetProperty("ans", out JsonElement blob);
- //选取后,缓存池相应的减少,以便于分配给其他的老师
- await redisClient.HashSetAsync($"Exam:Scoring:{id}-{subjectId}", sId.ToString(), new { ans = blob, score = sc, tmdId = tId }.ToJsonString());
- return Ok(item);
- }
-
- }
- //var json = JsonDocument.Parse(record);
- /*if (info.scope.Equals("school"))
- {
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
- queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.school}") }))
- {
- classResults.Add(item);
- }
- }
- else
- {
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
- queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.creatorId}") }))
- {
- classResults.Add(item);
- }
- }
- List<Task<bool>> tasks = new List<Task<bool>>();
- foreach (ExamClassResult examClass in classResults)
- {
- foreach (string stuId in examClass.studentIds)
- {
- int index = examClass.studentIds.IndexOf(stuId);
- tasks.Add(redisClient.HashSetAsync($"Exam:Scoring:{id}-{subjectId}", stuId, new { ans = examClass.studentAnswers[index].Count > 0 ? examClass.studentAnswers[index][0]: "", score = examClass.studentScores[index] }.ToJsonString()));
- }
- }
- await Task.WhenAll(tasks);*/
- //info = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(info, info.id, new PartitionKey($"Exam-{code}"));
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/review\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //批阅 提交分数
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Student")]
- [HttpPost("sub-result")]
- public async Task<IActionResult> SubResult(JsonElement requert)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!requert.TryGetProperty("stuId", out JsonElement sId)) return BadRequest();
- if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- if (!requert.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
- if (!requert.TryGetProperty("score", out JsonElement score)) return BadRequest();
- if (!requert.TryGetProperty("count", out JsonElement count)) return BadRequest();
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- //if (!requert.TryGetProperty("mark", out JsonElement mark)) return BadRequest();
- requert.TryGetProperty("mark", out JsonElement mark);
- var client = _azureCosmos.GetCosmosClient();
- var redisClient = _azureRedis.GetRedisClient(8);
- List<ExamClassResult> classResults = new();
- List<dynamic> recs = new List<dynamic>();
- var record = await redisClient.HashGetAllAsync($"Exam:Scoring:{id}-{subjectId}");
- foreach (var rcd in record)
- {
- var values = JsonDocument.Parse(rcd.Value.ToString());
- values.RootElement.TryGetProperty("tmdId", out JsonElement tmdId);
- if (tId.ToString().Equals(tmdId.ToString()))
- {
- recs.Add(new { stuId = rcd.Name.ToString(), ans = values });
- }
- }
- var stuAns = await redisClient.HashGetAsync($"Exam:Scoring:{id}-{subjectId}", sId.ToString());
- var value = JsonDocument.Parse(stuAns.ToString());
- value.RootElement.TryGetProperty("ans", out JsonElement blob);
- //存放老师批注信息到blob
- StringBuilder builder = new StringBuilder();
- builder.Append(id).Append("/");
- builder.Append(subjectId).Append("/");
- builder.Append(sId).Append("mark").Append("/");
- builder.Append("ans.json");
- await _azureStorage.UploadFileByContainer(code.ToString(), mark.ToJsonString(), "exam", builder.ToString(), false);
- await redisClient.HashSetAsync($"Exam:Scoring:{id}-{subjectId}", sId.ToString(), new { ans = blob, score = score, tmdId = tId, mark = builder.ToString() }.ToJsonString());
- if (recs.Count == count.GetInt32())
- {
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
- queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
- {
- classResults.Add(item);
- }
- foreach (ExamClassResult exam in classResults)
- {
- foreach (dynamic re in recs)
- {
- var cs = JsonSerializer.Serialize(re);
- var json = JsonDocument.Parse(cs);
- json.RootElement.TryGetProperty("stuId", out JsonElement stuId);
- json.RootElement.TryGetProperty("ans", out JsonElement ans);
- ans.TryGetProperty("score", out JsonElement sc);
- ans.TryGetProperty("mark", out JsonElement marks);
- int index = exam.studentIds.IndexOf(stuId.ToString());
- if (index != -1)
- {
- exam.studentScores[index] = sc.ToObject<List<double>>();
- exam.mark[index] = marks.ToString();
- }
- }
- await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
- }
- }
- return Ok(new { code = 200 });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/sub-result\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- }
- }
|