123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210 |
- 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.DI;
- using TEAMModelOS.SDK.DI.AzureCosmos.Inner;
- using TEAMModelOS.SDK.Extension;
- 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;
- using TEAMModelOS.Filter;
- using TEAMModelOS.SDK.Models.Service;
- using TEAMModelOS.SDK.Models.Cosmos;
- using HTEXLib.COMM.Helpers;
- using Microsoft.AspNetCore.Authorization;
- using System.Net.Http;
- namespace TEAMModelOS.Controllers
- {
- [ProducesResponseType(StatusCodes.Status200OK)]
- [ProducesResponseType(StatusCodes.Status400BadRequest)]
- [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; }
- private readonly NotificationService _notificationService;
- private readonly CoreAPIHttpService _coreAPIHttpService;
- public ExamController(CoreAPIHttpService coreAPIHttpService, AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing,
- IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, NotificationService notificationService, IConfiguration configuration)
- {
- _azureCosmos = azureCosmos;
- _serviceBus = serviceBus;
- _snowflakeId = snowflakeId;
- _dingDing = dingDing;
- _option = option?.Value;
- _azureStorage = azureStorage;
- _azureRedis = azureRedis;
- _configuration = configuration;
- _notificationService = notificationService;
- _coreAPIHttpService = coreAPIHttpService;
- }
- /// <summary>
- /// 保存考试信息
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("save")]
- [Authorize(Roles = "IES")]
- 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;
- }
- //查询所有学生名单
- /* List<string> sids = new List<string>();
- //List<Student> students = new List<Student>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: $"select c.id from c", 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;
- sids.Add(account.GetProperty("id").GetString());
- }
- }
- }*/
- //int stuCount = 0;
- List<(string pId, List<string> gid)> ps = new();
- var group = request.groupLists;
- if (group.Count > 0)
- {
- foreach (var keys in group)
- {
- foreach (KeyValuePair<string, List<string>> pp in keys)
- {
- ps.Add((pp.Key, pp.Value));
- }
- }
- }
- List<string> classes = ExamService.getClasses(request.classes, request.stuLists);
- (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, classes, request.school, ps);
- request.stuCount = tchList.Count;
- /*for (int i = 0; i < classes.Count; i++)
- {
- List<string> ids = new List<string>();
- //处理班级人数(公共部分的校本名单)
- //List<Student> students = new List<Student>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: $"select c.id from c where c.classId = '{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<GroupList> stuLists = new List<GroupList>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<GroupList>(queryText: $"select value(c) from c where c.id = '{classes[i]}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList") }))
- {
- stuLists.Add(item);
- }
- }
- else
- {
- //request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"exam/{request.id}");
- //发布对象为自选名单(校本)
- List<GroupList> stuLists = new List<GroupList>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupList>(queryText: $"select value(c) from c where c.id = '{classes[i]}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{request.school}") }))
- {
- stuLists.Add(item);
- }
- }
- stuCount += ids.Count;
- }*/
- 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;
- List<string> sheetIds = new List<string>();
- foreach (PaperSimple simple in request.papers)
- {
- simple.blob = $"/exam/{request.id}/paper/{request.subjects[n].id}";
- n++;
- simple.sheet = null;
- }
- exam = await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(request, new PartitionKey($"{request.code}"));
- }
- else
- {
- ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(request.id, new PartitionKey($"{request.code}"));
- //info.name = request.name;
- if (info.progress.Equals("going"))
- {
- //exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(request, request.id, new PartitionKey($"{request.code}"));
- return Ok(new { v = "活动正在进行中,无法修改", code = 200 });
- }
- 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++;
- }
- exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(request, request.id, new PartitionKey($"{request.code}"));
- }
- return Ok(new { exam });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/save()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 保存考试信息
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("update-end-time")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> updateTime(JsonElement request)
- {
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.GetString(), new PartitionKey($"Exam-{code}"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- ExamInfo exam = json.ToObject<ExamInfo>();
- if (request.TryGetProperty("time", out JsonElement time))
- {
- exam.endTime = time.GetInt64();
- }
- if (request.TryGetProperty("name", out JsonElement name))
- {
- exam.name = name.GetString();
- }
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
- }
- return Ok(new { code = 200 });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/update-end-time()\n{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //TODO blob 批量删除
- /// <summary>
- /// 删除
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("delete")]
- [Authorize(Roles = "IES")]
- 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();*/
- var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
- 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();
- ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.GetString(), new PartitionKey($"Exam-{code}"));
- bool flag = false;
- //必须是本人或者这个学校的管理者才能删除
- if (exam.creatorId == userid)
- {
- flag = true;
- }
- else
- {
- if (exam.scope == "school" && exam.school.Equals(school))
- {
- flag = true;
- }
- }
- if (flag)
- {
- exam.status = 404;
- exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
- //string school_code = code.ToString().Substring(typeof(ExamClassResult).Name.Length + 1);
- //var response = await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Exam-{code}"));
- //删除blob 相关资料
- await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, code.ToString(), new List<string> { $"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);
- //删除阅卷配置
- 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}"));
- }
- List<ExamClassResult> examClassResults = new List<ExamClassResult>();
- await foreach (var item in client.GetContainer(Constant.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(Constant.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(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(classResult.id, new PartitionKey($"ExamClassResult-{code}"));
- }
- await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemsStreamAsync(resultIds, $"ExamResult-{id}");
- /*foreach (ExamResult result in results)
- {
- await client.GetContainer(Constant.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}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 查询考试信息
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [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;
- if (year == 1970)
- {
- long ct = 0;
- await foreach (var item in client.GetContainer(Constant.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 = ct == 0 ? DateTimeOffset.UtcNow.Year : DateTimeOffset.FromUnixTimeMilliseconds(ct).Year;
- years[0].year = year;
- await _azureStorage.SaveOrUpdate<SchoolYear>(years[0]);
- }
- }
- else
- {
- long ct = 0;
- await foreach (var item in client.GetContainer(Constant.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 = ct == 0 ? DateTimeOffset.UtcNow.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.owner, c.scope,c.classes,c.sRate,c.lostStu,c.sStatus 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.owner, c.scope,c.classes,c.sRate,c.lostStu,c.sStatus 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(Constant.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(Constant.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]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("find-summary")]
- public async Task<IActionResult> FindSummary(JsonElement requert)
- {
- try
- {
- if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- List<ExamInfo> examInfo = new List<ExamInfo>();
- //var query = $"select value(c) from c ";
- await foreach (var item in client.GetContainer(Constant.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]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "student,teacher")]
- [HttpPost("upsert-record")]
- public async Task<IActionResult> upsertRecord(JsonElement request)
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- //学校编码
- //if (!request.TryGetProperty("school", out JsonElement school)) 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("classIds", 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 code)) return BadRequest();
- if (!request.TryGetProperty("scode", out JsonElement scode)) return BadRequest();
- var (userId, _, _, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- List<string> ids = new List<string>();
- ids = classId.ToObject<List<string>>();
- var client = _azureCosmos.GetCosmosClient();
- ExamInfo info = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.GetString(), new PartitionKey($"{scode}"));
- //确定当前学生所在班级且该班级参与该活动
- List<string> cIds = new();
- if (ids.Count == 0) return Ok(new { code = 1, msg = "未找到相关班级信息" });
- if (string.IsNullOrEmpty(userId)) return Ok(new { code = 1, msg = "当前用户信息未找到" });
- foreach (string cId in ids)
- {
- //List<string> stus = new List<string>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(
- queryText: $"select c.classId as id from c where c.classId = '{cId}' and c.id = '{userId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{info.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;
- cIds.Add(account.GetProperty("id").GetString());
- }
- break;
- }
- }
- if (info.scope.Equals("private"))
- {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(
- queryText: $"select c.id from c join A0 in c.members where c.id = '{cId}' and A0.id = '{userId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList") }))
- {
- 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;
- cIds.Add(account.GetProperty("id").GetString());
- }
- break;
- }
- }
- /*await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(
- queryText: $"select c.id from c where c.id = '{cId}' and array_contains(c.tmids,'{userId}') ",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList") }))
- {
- 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;
- cIds.Add(account.GetProperty("id").GetString());
- }
- break;
- }
- }*/
- }
- else
- {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(
- queryText: $"select c.id from c join A0 in c.members where c.id = '{cId}' and A0.id = '{userId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{info.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;
- cIds.Add(account.GetProperty("id").GetString());
- }
- break;
- }
- }
- }
- }
- List<ExamClassResult> examClassResults = new List<ExamClassResult>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(
- queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.info.id in ({string.Join(",", cIds.Select(o => $"'{o}'"))})",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{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<ExamClassResult>());
- }
- }
- }
- ExamClassResult classResult = new ExamClassResult();
- List<PaperSimple> standerAnswers = new List<PaperSimple>();
- await foreach (var item in client.GetContainer(Constant.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(userId.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>();
- List<List<string>> anc = new List<List<string>>();
- List<List<Details>> mark = new List<List<Details>>();
- foreach (List<string> num in standard)
- {
- List<string> newAns = new List<string>();
- foreach (string san in num)
- {
- newAns.Add(san);
- }
- anc.Add(newAns);
- ansPoint.Add(-1);
- mark.Add(new List<Details>());
- }
- result.mark.Add(mark);
- result.ans.Add(anc);
- result.studentIds.Add(userId.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(userId.ToString());
- /* if (flagCount != standard.Count)
- {*/
- StringBuilder builder = new StringBuilder();
- builder.Append(result.examId).Append("/");
- builder.Append(result.subjectId).Append("/");
- builder.Append(userId).Append("/");
- builder.Append("ans.json");
- /*string FileName = result.examId + "/" + result.subjectId + "/" + studentId;
- string blob = FileName + "/" + "ans.json";*/
- tasks.Add(_azureStorage.UploadFileByContainer(code.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++)
- {
- var ac = ans[i].Where(a => a.Trim().Length > 0).ToList().Count;
- var sc = standard[i].Count;
- //算分处理
- if (sc > 0)
- {
- result.ans[newIndex][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;
- }
- }
- }
- //bool isAns = true;
- bool isAns = result.studentScores[newIndex].Exists(s => s == -1);
- HttpContext.Items.TryGetValue("Scope", out object scope);
- if (flag)
- {
- result.progress = true;
- info.subjects.ForEach(s =>
- {
- if (s.id.Equals(subjectId.ToString()))
- {
- s.classCount += 1;
- }
- });
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(info, id.ToString(), new PartitionKey($"{scode}"));
- }
- if (isAns)
- {
- if ($"{scope}".Equals(Constant.ScopeStudent))
- {
- StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{school}-{userId}"));
- activity.taskStatus = 1;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{school}-{userId}"));
- }
- if ($"{scope}".Equals(Constant.ScopeTmdUser))
- {
- StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{userId}"));
- activity.taskStatus = 1;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{userId}"));
- }
- if ($"{scope}".Equals(Constant.ScopeTeacher))
- {
- StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{userId}"));
- activity.taskStatus = 1;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{userId}"));
- }
- }
- else
- {
- if ($"{scope}".Equals(Constant.ScopeStudent))
- {
- StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{school}-{userId}"));
- activity.taskStatus = 0;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{school}-{userId}"));
- }
- if ($"{scope}".Equals(Constant.ScopeTmdUser))
- {
- StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{userId}"));
- activity.taskStatus = 0;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{userId}"));
- }
- if ($"{scope}".Equals(Constant.ScopeTeacher))
- {
- StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{userId}"));
- activity.taskStatus = 0;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{userId}"));
- }
- }
- result.sum[newIndex] = result.studentScores[newIndex].Sum();
- classResult = await client.GetContainer(Constant.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}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [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<List<double>> ans = point.ToObject<List<List<double>>>();
- List<stus> sIds = studentId.ToObject<List<stus>>();
- var client = _azureCosmos.GetCosmosClient();
- List<ExamClassResult> examClassResults = new List<ExamClassResult>();
- if (request.TryGetProperty("classId", out JsonElement classId))
- {
- await foreach (var item in client.GetContainer(Constant.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(Constant.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-{school}") }))
- {
- examClassResults.Add(item);
- }
- }
- ExamClassResult classResult = new ExamClassResult();
- List<Task<ItemResponse<StuActivity>>> tasks = new List<Task<ItemResponse<StuActivity>>>();
- //ExamInfo classResult = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{code}"));
- //ExamClassResult classResult = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamClassResult>(id.ToString(), new PartitionKey($"{code}"));
- /*foreach (double index in ans) {
- classResult.studentScores.in
- }*/
- foreach (ExamClassResult result in examClassResults)
- {
- int index_sc = 0;
- foreach (stus s in sIds)
- {
- int index = result.studentIds.IndexOf(s.id.ToString());
- for (int i = 0; i < ans[index_sc].Count; i++)
- {
- result.studentScores[index][i] = ans[index_sc][i];
- }
- result.sum[index] = result.studentScores[index].Sum();
- bool flag = result.studentScores[index].Exists(r => r == -1);
- if (!flag)
- {
- if (s.type == 1)
- {
- try
- {
- StuActivity activity = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{s.id}"));
- activity.sStatus = 1;
- tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(activity, activity.id, new PartitionKey($"{activity.code}")));
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{_option.Location}\n{ex.Message}\n{ex.StackTrace}\n,id:{id},code:{s.id},school:{result?.school}", GroupNames.成都开发測試群組);
- }
- }
- else
- {
- try
- {
- var response = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Activity-{result.school}-{s.id}"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- StuActivity activity = json.ToObject<StuActivity>();
- activity.sStatus = 1;
- tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(activity, activity.id, new PartitionKey($"{activity.code}")));
- }else
- {
- List<string> scode = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: $"select c.shoolId from c where c.id = '{s.id}' and c.pk = 'Base'"))
- {
- using var stuJson = await JsonDocument.ParseAsync(item.ContentStream);
- if (stuJson.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = stuJson.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- scode.Add(account.GetProperty("shoolId").GetString());
- }
- }
- }
- foreach (var sid in scode)
- {
- StuActivity activity = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{sid}-{s.id}"));
- activity.sStatus = 1;
- tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(activity, activity.id, new PartitionKey($"{activity.code}")));
- }
- }
- //StuActivity activity = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{result.school}-{s.id}"));
-
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{_option.Location}\n{ex.Message}\n{ex.StackTrace}\n,id:{id},code:{s.id},school:{result?.school}", GroupNames.成都开发測試群組);
- }
- }
- }
- index_sc++;
- }
- 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(Constant.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(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"Exam-{code}"));
- }
- }
- else
- {
- ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
- exam.updateTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"Exam-{code}"));
- }
- classResult = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
- await Task.WhenAll(tasks);
- }
- 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]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [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();
- var (_, _, _, school) = HttpContext.GetAuthTokenInfo();
- //string code = school_code.ToString().Substring(5);
- //ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{school_code}"));
- List<ExamClassResult> examClassResults = new List<ExamClassResult>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(queryText: $"select c.id,c.subjectId,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}") }))
- {
- examClassResults.Add(item);
- }
- List<string> ids = new();
- foreach (ExamClassResult result in examClassResults)
- {
- ids.AddRange(result.studentIds);
- }
- ///获取真实的名称
- List<ufo> ufos = new();
- List<string> delIds = new();
- if (ids.Count > 0)
- {
- List<string> sIds = new();
- List<string> tIds = new();
- List<ufo> students = new List<ufo>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: $"select c.id,c.name from c where c.id in ({string.Join(",", ids.Select(o => $"'{o}'"))}) and c.pk = 'Base'"))
- {
- using var stuJson = await JsonDocument.ParseAsync(item.ContentStream);
- if (stuJson.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = stuJson.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- ufo fo = new()
- {
- id = account.GetProperty("id").GetString(),
- name = account.GetProperty("name").GetString(),
- type = 2
- };
- students.Add(fo);
- }
- }
- }
- if (students.Count > 0)
- {
- ufos.AddRange(students);
- foreach (ufo f in students)
- {
- sIds.Add(f.id);
- }
- if (ids.Count > sIds.Count)
- {
- tIds = ids.Except(sIds).ToList();
- var content = new StringContent(tIds.ToJsonString(), Encoding.UTF8, "application/json");
- string json = await _coreAPIHttpService.GetUserInfos(content);
- if (!string.IsNullOrWhiteSpace(json))
- {
- try
- {
- List<ufo> tmdInfos = json.ToObject<List<ufo>>();
- if (tmdInfos.IsNotEmpty())
- {
- foreach (ufo fo in tmdInfos)
- {
- fo.type = 1;
- tIds.Add(fo.id);
- }
- ufos.AddRange(tmdInfos);
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.Get("Default").location}用户转换失败:{_coreAPIHttpService.options.Get("Default").url}{json}\n {ex.StackTrace}", GroupNames.成都开发測試群組);
- }
- }
- }
- delIds = ids.Except(sIds.Union(tIds)).ToList();
- }
- else
- {
- var content = new StringContent(ids.ToJsonString(), Encoding.UTF8, "application/json");
- string json = await _coreAPIHttpService.GetUserInfos(content);
- if (!string.IsNullOrWhiteSpace(json))
- {
- try
- {
- List<ufo> tmdInfos = json.ToObject<List<ufo>>();
- if (tmdInfos.IsNotEmpty())
- {
- foreach (ufo fo in tmdInfos)
- {
- fo.type = 1;
- tIds.Add(fo.id);
- }
- ufos.AddRange(tmdInfos);
- delIds = ids.Except(tIds).ToList();
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.Get("Default").location}用户转换失败:{_coreAPIHttpService.options.Get("Default").url}{json}\n {ex.StackTrace}", GroupNames.成都开发測試群組);
- }
- }
- }
- }
- /*if (StringHelper.getKeyCount(requert) == 1 && requert.TryGetProperty("code", out JsonElement code))
- {
- List<object> props = new List<object>();
- await foreach (var item in client.GetContainer(Constant.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(Constant.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, ufos, delIds });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findSummaryRecord()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //学生端查询评测列表
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "student,teacher,admin")]
- [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.knowledge,A0.point,A0.field,A0.multipleRule,A0.scope,A0.blob,A0.time from c join A0 in c.papers where c.id ='{id}'";
- List<PaperSimple> papers = new List<PaperSimple>();
- List<object> subjects = new List<object>();
- List<string> classIds = new List<string>();
- //List<string> stus = 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(Constant.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<GroupList> stuLists = new List<GroupList>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<GroupList>(queryText: $"select c.id from c join A0 in c.students where A0.id = '{studentId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList") }))
- {
- stuLists.Add(item);
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupList>(queryText: $"select c.id from c join A0 in c.students where A0.id = '{studentId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
- {
- stuLists.Add(item);
- }
- if (stuLists.Count > 0)
- {
- foreach (GroupList stuList in stuLists)
- {
- resultIds.Add(stuList.id);
- }
- }
- var queryClassId = $"select c.classes id,c.stuLists stus from c where c.id ='{id}'";
- await foreach (var item in client.GetContainer(Constant.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.AddRange(obj.GetProperty("id").ToObject<List<string>>());
- classIds.AddRange(obj.GetProperty("stus").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(Constant.TEAMModelOS, "Common").GetItemQueryIterator<PaperSimple>(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
- {
- papers.Add(item);
- }
- var querySubject = $"select A0.id,A0.name from c join A0 in c.subjects where c.id ='{id}'";
- //List<object> props = new List<object>();
- List<string> subId = new();
- await foreach (var item in client.GetContainer(Constant.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>());
- subId.Add(obj.GetProperty("id").GetString());
- }
- }
- }
- var queryAnswers = $"select c.id,c.code,c.studentIds,c.subjectId,c.studentAnswers,c.studentScores,c.sum,c.mark,c.krate,c.frate 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(Constant.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<double>> stuScore = new();
- List<List<List<Details>>> mark = new();
- List<List<double>> total = new();
- List<double> average = new();
- if (answers.Count > 0)
- {
- foreach (ExamClassResult result in answers)
- {
- List<double> sTotal = new();
- int index = result.studentIds.IndexOf(studentId.ToString());
- if (index == -1)
- {
- break;
- }
- stuAns.Add(result.studentAnswers[index]);
- stuScore.Add(result.studentScores[index]);
- mark.Add(result.mark[index]);
- average.Add(result.average);
- sTotal.Add(result.sum.Where(s => s <= 59).Count());
- sTotal.Add(result.sum.Where(s => s > 59 && s <= 70).Count());
- sTotal.Add(result.sum.Where(s => s > 70 && s <= 80).Count());
- sTotal.Add(result.sum.Where(s => s > 80 && s <= 90).Count());
- sTotal.Add(result.sum.Where(s => s > 90 && s <= 100).Count());
- total.Add(sTotal);
- }
- }
- List<(List<string> kn, List<double> kps, List<double> ckps)> know = new();
- List<(List<int> fs, List<double> fps, List<double> cfps)> fp = new();
- foreach (var s in stuTask(subId, papers, answers, studentId.GetString()))
- {
- know = s.know;
- fp = s.filed;
- }
- if (papers.IsNotEmpty())
- {
- var knowledge = know.Select(k => new { k.kn, k.kps, k.ckps });
- var filed = fp.Select(k => new { k.fs, k.fps, k.cfps });
- //papers = papers
- return Ok(new { papers, subjects, stuScore, stuAns, mark, total, claId = infoIds, knowledge, filed, average, status = 200 });
- }
- else
- {
- return Ok(new { papers, subjects, stuScore, stuAns, mark, total, claId = infoIds, status = 404 });
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-summary-by-student()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return Ok(new { status = 400 });
- }
- }
- private IEnumerable<(List<(List<string> kn, List<double> kps, List<double> ckps)> know, List<(List<int> fs, List<double> fps, List<double> cfps)> filed)> stuTask(List<string> subjectIds, List<PaperSimple> papers, List<ExamClassResult> answers, string stuId)
- {
- List<(List<string> kn, List<double> kps, List<double> ckps)> know = new List<(List<string> kn, List<double> kps, List<double> ckps)>();
- List<(List<int> fs, List<double> fps, List<double> cfps)> filed = new List<(List<int> fs, List<double> fps, List<double> cfps)>();
- int no = 0;
- foreach (string sub in subjectIds)
- {
- List<double> kp = new();
- List<double> fp = new();
- List<double> ckp = new();
- List<double> cfp = new();
- List<int> fields = new() { 1, 2, 3, 4, 5, 6 };
- //获取该试卷所有知识点和认知层次分布
- List<List<string>> kones = papers[no].knowledge;
- List<int> fs = papers[no].field;
- List<double> point = papers[no].point;
- //去重知识点
- HashSet<string> knowles = new();
- List<string> knowledges = new();
- if (kones.Count > 0)
- {
- kones.ForEach(kno =>
- {
- kno.ForEach(k =>
- {
- knowles.Add(k);
- });
- });
- }
- foreach (string cla in knowles)
- {
- knowledges.Add(cla);
- }
- for (int k = 0; k < knowledges.Count; k++)
- {
- if (null == knowledges[k])
- {
- knowledges.Remove(knowledges[k]);
- }
- }
- foreach (ExamClassResult result in answers)
- {
- if (result.subjectId.Equals(sub))
- {
- int index = result.studentIds.IndexOf(stuId.ToString());
- //处理知识点
- foreach (string k in knowledges)
- {
- //初始化单个知识点得分
- double score = 0;
- double allScore = 0;
- int n = 0;
- foreach (List<string> str in kones)
- {
- if (str.Contains(k))
- {
- var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
- allScore += point.Count > 0 ? point[n] * itemPersent : 0;
- if (result.studentScores.Count > 0)
- {
- if (result.studentScores[index].Count > 0)
- {
- score += result.studentScores[index][n] == -1 ? 0 : result.studentScores[index][n];
- }
- }
- }
- n++;
- }
- kp.Add(allScore > 0 ? Math.Round(score / allScore, 2) : 0);
- }
- //处理认知层次
- foreach (int k in fields)
- {
- //初始化认知层次得分
- double score = 0;
- double allScore = 0;
- int n = 0;
- foreach (int str in fs)
- {
- if (str == k)
- {
- var itemPersent = 1;
- allScore += point.Count > 0 ? point[n] * itemPersent : 0;
- if (result.studentScores.Count > 0)
- {
- if (result.studentScores[index].Count > 0)
- {
- score += result.studentScores[index][n] == -1 ? 0 : result.studentScores[index][n];
- }
- }
- }
- n++;
- }
- fp.Add(allScore > 0 ? Math.Round(score / allScore, 2) : 0);
- }
- ckp = result.krate;
- cfp = result.frate;
- }
- }
- know.Add((knowledges, kp, ckp));
- filed.Add((fields, fp, cfp));
- no++;
- }
- yield return (know, filed);
- }
- //查询学生活动列表
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [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(Constant.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(Constant.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(Constant.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(Constant.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]
- [Authorize(Roles = "IES")]
- [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(Constant.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]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [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(Constant.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(Constant.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(Constant.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(Constant.TEAMModelOS, "Common").ReplaceItemAsync(examClass, examClass.id, new PartitionKey($"{examClass.code}"));
- }
- info = await client.GetContainer(Constant.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(Constant.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(Constant.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(Constant.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(Constant.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]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [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("type", out JsonElement type)) return BadRequest();
- if (!requert.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
- if (!requert.TryGetProperty("count", out JsonElement scount)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- //var redisClient = _azureRedis.GetRedisClient(8);
- ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
- List<ExamClassResult> classResults = new();
- List<SDK.Models.Cosmos.Common.Scoring> attr = new List<SDK.Models.Cosmos.Common.Scoring>();
- 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}' and c.subjectId = '{subjectId}' and array_contains(c.tIds,'{tId}') ",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
- {
- attr.Add(item);
- }
- List<SDK.Models.Cosmos.Common.Scoring> attrSc = new List<SDK.Models.Cosmos.Common.Scoring>();
- 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}' and c.subjectId = '{subjectId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
- {
- attrSc.Add(item);
- }
- int index = 0;
- foreach (ExamSubject subject in info.subjects)
- {
- if (!subject.id.Equals(subjectId.ToString()))
- {
- index++;
- }
- else
- {
- break;
- }
- }
- List<dynamic> objs = new List<dynamic>();
- List<dynamic> wobjs = new List<dynamic>();
- /*if (type.GetInt32() != 1) {
- return Ok(new { attr, paper = info.papers[index].blob });
- }*/
- //List<SDK.Models.Cosmos.Common.Scoring> errs = new();
- //List<SDK.Models.Cosmos.Common.Scoring> arbs = new();
- Correct correct = null;
- var cResponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Correct-{code}"));
- if (cResponse.Status == 200)
- {
- using var cJson = await JsonDocument.ParseAsync(cResponse.ContentStream);
- correct = cJson.ToObject<Correct>();
- }
- int finishCount = 0;
- foreach (SDK.Models.Cosmos.Common.Scoring ss in attrSc)
- {
- for (int i = 0; i < correct.num; i++)
- {
- List<double> tsc = new List<double>();
- foreach (Item item in ss.items)
- {
- if (item.scores.Count > 0)
- {
- if (i >= item.scores.Count)
- {
- break;
- }
- else
- {
- tsc.Add(item.scores[i].sc);
- }
- }
- }
- bool flag = tsc.Exists(s => s == -1);
- if (!flag && tsc.Count > 0)
- {
- finishCount++;
- }
- }
- }
- if (attr.Count > 0)
- {
- foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
- {
- //var scc = ss.items.SelectMany(p => p.scores, (p, d) => new { p.ssc, d.sc, d.tmdId }).Where(x => x.tmdId.Equals(tId.GetString())).Select(m => new { m.sc ,m.ssc});
- List<dynamic> sc = new List<dynamic>();
- List<dynamic> allSc = new List<dynamic>();
- ss.qs = ss.qs.Where(s => !string.IsNullOrEmpty(s.tId)).ToList();
- int indexScore = 0;
- (string ansBlob, List<double> scores) = await getMoreStuInfo(client, ss.stuId, ss.examId, ss.subjectId, code.GetString());
- foreach (Item item in ss.items)
- {
- var count = item.scores.GroupBy(i => new { i.tmdId, i.sc }).Select(c => c.Key.sc).ToList();
- allSc.Add(count.FirstOrDefault());
- List<double> scc = item.scores.Where(x => x.tmdId.Equals(tId.GetString())).Select(c => c.sc).ToList();
- List<string> blob = item.scores.Where(x => x.tmdId.Equals(tId.GetString())).Select(c => c.mark).ToList();
- //item.scores.Where(x => x.tmdId.Equals(tId.GetString())).SelectMany(p => p.sc, (p, d) => new { });
- if (scc.Count > 0)
- {
- sc.Add(new { sc = scc.FirstOrDefault(), blob = blob.FirstOrDefault(), item.ssc });
- }
- else
- {
- ss.scores = scores;
- sc.Add(new { sc = ss.scores[indexScore], blob = "", item.ssc });
- }
- indexScore++;
- }
- var obj = new { ss.id, ss.stuId, ss.examId, ss.subjectId, item = sc, ss.qs, blob = ansBlob, ss.tIds, scores = scores, ss.model, ss.mode };
- objs.Add(obj);
- }
- }
- else
- {
- if (requert.TryGetProperty("stuId", out JsonElement stuId))
- {
- objs = await Review(attrSc, id.GetString(), code.GetString(), subjectId.GetString(), scount.GetInt32(), tId.GetString(), stuId.GetString());
- }
- else
- {
- objs = await Review(attrSc, id.GetString(), code.GetString(), subjectId.GetString(), scount.GetInt32(), tId.GetString(), "");
- }
- }
- var fp = attr.Count > 0 ? Math.Round(finishCount * 1.0 / (attrSc.Count * correct.num), 2) : 0;
- return Ok(new { objs, paper = info.papers[index].blob, fp });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/scoring\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //查找异常卷
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("find-err")]
- public async Task<IActionResult> findErr(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 response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Exam-{code}"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- ExamInfo info = json.ToObject<ExamInfo>();
- //ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
- List<ExamClassResult> classResults = new();
- List<SDK.Models.Cosmos.Common.Scoring> attr = new List<SDK.Models.Cosmos.Common.Scoring>();
- 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}' and c.subjectId = '{subjectId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
- {
- attr.Add(item);
- }
- int index = 0;
- foreach (ExamSubject subject in info.subjects)
- {
- if (!subject.id.Equals(subjectId.ToString()))
- {
- index++;
- }
- else
- {
- break;
- }
- }
- List<dynamic> objs = new List<dynamic>();
- List<SDK.Models.Cosmos.Common.Scoring> errs = new();
- foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
- {
- List<Qs> qs = ss.qs.Where(s => !string.IsNullOrEmpty(s.err)).ToList();
- if (qs.Count > 0)
- {
- ss.qs = qs;
- errs.Add(ss);
- }
- }
- return Ok(new { errs, paper = info.papers[index].blob });
- }
- else
- {
- return BadRequest();
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-err\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("find-arb")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> findArb(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("et", out JsonElement et)) return BadRequest();
- //if (!requert.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- long time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- if (et.GetInt64() > time)
- {
- return Ok(new { msg = "还在进行中", code = 202 });
- }
- ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
- List<ExamClassResult> classResults = new();
- List<SDK.Models.Cosmos.Common.Scoring> attr = new List<SDK.Models.Cosmos.Common.Scoring>();
- 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}' and c.subjectId = '{subjectId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
- {
- attr.Add(item);
- }
- int index = 0;
- foreach (ExamSubject subject in info.subjects)
- {
- if (!subject.id.Equals(subjectId.ToString()))
- {
- index++;
- }
- else
- {
- break;
- }
- }
- List<dynamic> objs = new List<dynamic>();
- /*if (type.GetInt32() != 1) {
- return Ok(new { attr, paper = info.papers[index].blob });
- }*/
- //List<SDK.Models.Cosmos.Common.Scoring> errs = new();
- List<SDK.Models.Cosmos.Common.Scoring> arbs = new();
- //List<(string id,List<double>)> osc = new List<(string id, List<double>)>();
- foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
- {
- //List<double> original = new List<double>();
- List<Item> arb = ss.items.Where(s => s.flag == false).ToList();
- (string ansBlob, List<double> scores) = await getMoreStuInfo(client, ss.stuId, ss.examId, ss.subjectId, code.GetString());
- ss.blob = ansBlob;
- ss.scores = scores;
- if (arb.Count > 0)
- {
- ss.items = arb;
- arbs.Add(ss);
- }
- }
- return Ok(new { arbs = arbs.Select(a => new { a.items, a.blob, a.stuId, a.subjectId, a.id, a.scores }), paper = info.papers[index].blob });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-arb\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //批阅,给老师随机分配阅卷数据,以及查询改老师已有的阅卷数据
- private async Task<List<dynamic>> Review(List<SDK.Models.Cosmos.Common.Scoring> attr, string id, string code, string subjectId, int count, string tId, string stuId)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- //var redisClient = _azureRedis.GetRedisClient(8);
- List<ExamClassResult> classResults = new();
- List<SDK.Models.Cosmos.Common.Scoring> recs = new();
- List<SDK.Models.Cosmos.Common.Scoring> all = new();
- //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}' and c.subjectId = '{subjectId}' ",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
- {
- attr.Add(item);
- }*/
- foreach (SDK.Models.Cosmos.Common.Scoring scoring in attr)
- {
- if (scoring.tIds.Contains(tId.ToString()))
- {
- recs.Add(scoring);
- }
- else if (scoring.tIds.Count < scoring.count * scoring.model)
- {
- all.Add(scoring);
- }
- }
- if (!string.IsNullOrEmpty(stuId))
- {
- List<SDK.Models.Cosmos.Common.Scoring> value = 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}' and c.subjectId = '{subjectId}' and c.stuId = '{stuId}' ",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
- {
- value.Add(item);
- }
- if (value.Count > 0)
- {
- foreach (SDK.Models.Cosmos.Common.Scoring scoring in value)
- {
- if (scoring.tIds.Contains(tId.ToString()))
- {
- break;
- }
- else
- {
- scoring.tIds.Add(tId.ToString());
- await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey(scoring.code));
- }
- }
- }
- List<dynamic> objs = new List<dynamic>();
- List<SDK.Models.Cosmos.Common.Scoring> val = new List<SDK.Models.Cosmos.Common.Scoring>();
- foreach (SDK.Models.Cosmos.Common.Scoring ss in value)
- {
- //var scc = ss.items.SelectMany(p => p.scores, (p, d) => new { p.ssc, d.sc, d.tmdId }).Where(x => x.tmdId.Equals(tId.GetString())).Select(m => new { m.sc, m.ssc });
- List<dynamic> sc = new List<dynamic>();
- int indexScore = 0;
- ss.qs = ss.qs.Where(s => !string.IsNullOrEmpty(s.tId)).ToList();
- (string ansBlob, List<double> scores) = await getMoreStuInfo(client, ss.stuId, ss.examId, ss.subjectId, code);
- foreach (Item item in ss.items)
- {
- List<double> scc = item.scores.Where(x => x.tmdId.Equals(tId)).Select(c => c.sc).ToList();
- //item.scores.Where(x => x.tmdId.Equals(tId.GetString())).SelectMany(p => p.sc, (p, d) => new { });
- if (scc.Count > 0)
- {
- sc.Add(new { sc = scc.FirstOrDefault(), item.ssc });
- }
- else
- {
- ss.scores = scores;
- sc.Add(new { sc = ss.scores[indexScore], item.ssc });
- }
- indexScore++;
- }
- var obj = new { ss.id, ss.stuId, ss.examId, ss.subjectId, item = sc, ss.qs, blob = ansBlob, ss.tIds, scores = scores, ss.model, ss.mode };
- objs.Add(obj);
- }
- return objs;
- }
- else
- {
- List<SDK.Models.Cosmos.Common.Scoring> notYet = new();
- notYet = all.Where(x => x.tIds.Count < x.count * x.model - 1).ToList();
- List<dynamic> objs = new List<dynamic>();
- for (int i = 0; i < count; i++)
- {
- Random random = new Random();
- SDK.Models.Cosmos.Common.Scoring item = new();
- if (notYet.Count > 0)
- {
- int index = random.Next(notYet.Count);
- item = notYet[index];
- notYet.RemoveAt(index);
- }
- else
- {
- int index = random.Next(all.Count);
- item = all[index];
- all.RemoveAt(index);
- }
- if (!item.tIds.Contains(tId.ToString()))
- {
- item.tIds.Add(tId.ToString());
- }
- await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
- List<dynamic> sc = new List<dynamic>();
- (string ansBlob, List<double> scores) = await getMoreStuInfo(client, item.stuId, item.examId, item.subjectId, code);
- int indexScore = 0;
- item.qs = item.qs.Where(s => !string.IsNullOrEmpty(s.tId)).ToList();
- foreach (Item its in item.items)
- {
- List<double> ssc = its.scores.Where(x => x.tmdId.Equals(tId)).Select(c => c.sc).ToList();
- if (ssc.Count > 0)
- {
- sc.Add(new { sc = ssc.FirstOrDefault(), its.ssc });
- }
- else
- {
- item.scores = scores;
- sc.Add(new { sc = item.scores[indexScore], its.ssc });
- }
- indexScore++;
- }
- var obj = new { item.id, item.stuId, item.examId, item.subjectId, item = sc, item.qs, blob = ansBlob, item.tIds, scores = scores, item.model, item.mode };
- objs.Add(obj);
- }
- return objs;
- /*if (recs.Count == count.GetInt32())
- {
- return Ok(new { msg = "分配人数已到上限" });
- }
- else
- {
- if (all.Count == 0)
- {
- return Ok(new { msg = "暂无可选学生" });
- }
- //随机选取一名学生打分
- Random random = new Random();
- SDK.Models.Cosmos.Common.Scoring item = new();
- List<SDK.Models.Cosmos.Common.Scoring> notYet = new();
- notYet = all.Where(x => x.tIds.Count < x.count * x.model - 1).ToList();
- if (notYet.Count > 0)
- {
- item = notYet[random.Next(notYet.Count)];
- }
- else
- {
- item = all[random.Next(all.Count)];
- }
- if (!item.tIds.Contains(tId.ToString()))
- {
- item.tIds.Add(tId.ToString());
- }
- await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
- List<dynamic> sc = new List<dynamic>();
- (string ansBlob, List<double> scores) = await getMoreStuInfo(client, item.stuId, item.examId, item.subjectId, code.GetString());
- int indexScore = 0;
- foreach (Item its in item.items)
- {
- List<double> ssc = its.scores.Where(x => x.tmdId.Equals(tId.GetString())).Select(c => c.sc).ToList();
- if (ssc.Count > 0)
- {
- sc.Add(new { sc = ssc.FirstOrDefault(), its.ssc });
- }
- else
- {
- item.scores = scores;
- sc.Add(new { sc = item.scores[indexScore], its.ssc });
- }
- indexScore++;
- }
- var obj = new { item.id, item.stuId, item.examId, item.subjectId, item = sc, item.qs, blob = ansBlob, item.tIds, scores = scores, item.model, item.mode };
- return Ok(obj);
- }*/
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/review\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return new List<dynamic>() { new { code = 404, msg = "分配任务异常" } };
- }
- }
- //批阅 提交分数
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("sub-result")]
- [Authorize(Roles = "IES")]
- 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();
- requert.TryGetProperty("mark", out JsonElement mark);
- var client = _azureCosmos.GetCosmosClient();
- 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();
- }
- List<ExamClassResult> classResults = new();
- 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}' and c.subjectId = '{subjectId}' and c.stuId = '{sId}' and array_contains(c.tIds,'{tId}') ",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
- {
- attr.Add(item);
- }
- List<double> ssc = score.ToObject<List<double>>();
- List<string> marks = mark.ToObject<List<string>>();
- StringBuilder builder = new();
- if (attr.Count > 0)
- {
- foreach (SDK.Models.Cosmos.Common.Scoring scoring in attr)
- {
- int itemIndex = 0;
- //int tIdIndex = scoring.tIds.IndexOf(tId.GetString());
- if (requert.TryGetProperty("qu", out JsonElement qu))
- {
- List<int> nos = qu.ToObject<List<int>>();
- foreach (int number in nos)
- {
- List<Info> items = scoring.items[number].scores.Where(x => x.tmdId.Equals(tId.GetString())).ToList();
- if (items.Count > 0)
- {
- foreach (Info info in items)
- {
- info.sc = ssc[number];
- info.mark = marks.Count > 0 ? marks[number] : "";
- }
- }
- else
- {
- Info info = new();
- info.sc = ssc[number];
- info.tmdId = tId.GetString();
- info.mark = marks.Count > 0 ? marks[number] : "";
- info.index = number;
- scoring.items[number].scores.Add(info);
- }
- }
- }
- else
- {
- foreach (Item item in scoring.items)
- {
- List<Info> items = item.scores.Where(x => x.tmdId.Equals(tId.GetString())).ToList();
- if (items.Count > 0)
- {
- foreach (Info info in items)
- {
- info.sc = ssc[itemIndex];
- info.mark = marks.Count > 0 ? marks[itemIndex] : "";
- }
- }
- else
- {
- if (ssc[itemIndex] >= 0)
- {
- Info info = new();
- info.sc = ssc[itemIndex];
- info.tmdId = tId.GetString();
- info.mark = marks.Count > 0 ? marks[itemIndex] : "";
- info.index = itemIndex;
- item.scores.Add(info);
- }
- }
- itemIndex++;
- }
- }
- await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey(scoring.code));
- }
- }
- else
- {
- return BadRequest();
- }
- Correct correct = null;
- var cResponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Correct-{code}"));
- if (cResponse.Status == 200)
- {
- using var cJson = await JsonDocument.ParseAsync(cResponse.ContentStream);
- correct = cJson.ToObject<Correct>();
- }
- await foreach (var item in client.GetContainer(Constant.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);
- }
- bool isFinish = false;
- int scount = attr.Select(a => a.items[0].scores).ToList().Count;
- foreach (SDK.Models.Cosmos.Common.Scoring sc in attr)
- {
- foreach (var item in sc.items)
- {
- if (item.scores.Count == 0)
- {
- isFinish = false;
- break;
- }
- else
- {
- if (item.scores.Count != correct.num)
- {
- isFinish = false;
- break;
- }
- else
- {
- isFinish = true;
- }
- }
- }
- }
- if (isFinish)
- {
- foreach (ExamClassResult exam in classResults)
- {
- foreach (SDK.Models.Cosmos.Common.Scoring scoring in attr)
- {
- int index = exam.studentIds.IndexOf(scoring.stuId);
- if (index != -1)
- {
- int itemIndex = 0;
- foreach (Item item in scoring.items)
- {
- var ace = item.scores.Where(x => string.IsNullOrEmpty(x.tmdId)).ToList();
- if (ace.Count > 0)
- {
- return Ok(new { code = 1, msg = "用户信息未找到" });
- }
- //判定是否仲裁卷
- if (!item.flag)
- {
- item.isArb = 0;
- string bizcode = "scoring-arb";
- List<string> ids = new List<string>();
- foreach (CorSub sub in correct.subs)
- {
- ids = sub.arb;
- }
- //request.subs.Select(r => r.markers).ToList();
- 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 = correct.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);
- await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey(scoring.code));
- return Ok(new { msg = "需要仲裁", code = 2 });
- }
- if (item.scores.Count > 0)
- {
- double sc = item.scores.Select(x => x.sc).ToList().Aggregate((i, j) => (i + j) / item.scores.Count);
- scoring.scores[itemIndex] = sc;
- }
- string tmdId = tId.GetString();
- //定位老师是几阅
- int indexOfSc = 0;
- foreach (Info info in item.scores)
- {
- if (info.tmdId.Equals(tmdId))
- {
- break;
- }
- else
- {
- indexOfSc++;
- }
- }
- //判定是否已经存在对应的批注信息
- bool flag = exam.mark[index][itemIndex].Exists(x => x.tmdId.Equals(tmdId));
- if (flag)
- {
- //重复打分更新部分值
- exam.mark[index][itemIndex].Where(x => x.tmdId.Equals(tmdId)).ToList().ForEach(score =>
- {
- score.sc = item.scores[indexOfSc].sc;
- score.mark = item.scores[indexOfSc].mark;
- });
- }
- else
- {
- Details dt = new()
- {
- index = item.scores[indexOfSc].index,
- sc = item.scores[indexOfSc].sc,
- tmdId = item.scores[indexOfSc].tmdId,
- mark = item.scores[indexOfSc].mark,
- identity = item.scores[indexOfSc].identity
- };
- exam.mark[index][itemIndex].Add(dt);
- }
- itemIndex++;
- }
- exam.studentScores[index] = scoring.scores;
- exam.sum[index] = exam.studentScores[index].Sum();
- }
- }
- await client.GetContainer(Constant.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();
- }
- }
- //查询阅卷类型数据
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("find-scoring")]
- public async Task<IActionResult> findScoring(JsonElement requert)
- {
- 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("type", out JsonElement type)) return BadRequest();
- if (!requert.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}' and c.subjectId = '{subjectId}' and c.stuId = '{sId}' and c.type = '{type}' and array_contains(c.tIds,'{tId}') ",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
- {
- attr.Add(item);
- }
- return Ok(attr);
- }
- //申报异常卷内容
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("save-err")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> saveErr(JsonElement requert)
- {
- if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!requert.TryGetProperty("err", out JsonElement err)) return BadRequest();
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!requert.TryGetProperty("index", out JsonElement index)) return BadRequest();
- if (!requert.TryGetProperty("tId", out JsonElement tId)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- 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();
- }
- SDK.Models.Cosmos.Common.Scoring scoring = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<SDK.Models.Cosmos.Common.Scoring>(id.GetString(), new PartitionKey($"Scoring-{code}"));
- if (null != scoring)
- {
- Correct correct = null;
- var cResponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(scoring.examId, new PartitionKey($"Correct-{code}"));
- if (cResponse.Status == 200)
- {
- using var cJson = await JsonDocument.ParseAsync(cResponse.ContentStream);
- correct = cJson.ToObject<Correct>();
- }
- if (string.IsNullOrEmpty(scoring.qs[index.GetInt32()].tId))
- {
- scoring.qs[index.GetInt32()].err = err.GetString();
- scoring.qs[index.GetInt32()].tId = tId.GetString();
- scoring.qs[index.GetInt32()].index = index.GetInt32();
- }
- else
- {
- return Ok(new { msg = "改题已经被申报", code = 404 });
- }
- string bizcode = "scoring-err";
- List<string> ids = new List<string>();
- foreach (CorSub sub in correct.subs)
- {
- ids = sub.err;
- }
- //request.subs.Select(r => r.markers).ToList();
- 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 = correct.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);
- /* scoring.type = 2;
- scoring.err = err.GetString();*/
- }
- else
- {
- return Ok(new { code = 404 });
- }
- var sc = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey($"{scoring.code}"));
- return Ok(new { sc });
- }
- //处理异常卷内容
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("fd-err")]
- public async Task<IActionResult> fdErr(JsonElement requert)
- {
- if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!requert.TryGetProperty("improve", out JsonElement improve)) return BadRequest();
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!requert.TryGetProperty("index", out JsonElement index)) return BadRequest();
- //if (!requert.TryGetProperty("tId", out JsonElement tId)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- SDK.Models.Cosmos.Common.Scoring scoring = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<SDK.Models.Cosmos.Common.Scoring>(id.GetString(), new PartitionKey($"Scoring-{code}"));
- if (null != scoring)
- {
- if (string.IsNullOrEmpty(scoring.qs[index.GetInt32()].improve))
- {
- scoring.qs[index.GetInt32()].improve = improve.GetString();
- //scoring.qs[index.GetInt32()].tId = tId.GetString();
- //scoring.qs[index.GetInt32()].index = index.GetInt32();
- }
- else
- {
- return Ok(new { msg = "改题已经被处理", code = 404 });
- }
- /* scoring.type = 2;
- scoring.err = err.GetString();*/
- }
- else
- {
- return Ok(new { code = 404 });
- }
- var sc = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey($"{scoring.code}"));
- return Ok(new { sc });
- }
- //处理仲裁卷内容
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("save-arb")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> saveArb(JsonElement requert)
- {
- if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!requert.TryGetProperty("score", out JsonElement score)) return BadRequest();
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!requert.TryGetProperty("index", out JsonElement indexScore)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- //List<double> scs = score.ToObject<List<double>>();
- List<ExamClassResult> classResults = new();
- int sin = indexScore.GetInt32();
- SDK.Models.Cosmos.Common.Scoring scoring = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<SDK.Models.Cosmos.Common.Scoring>(id.GetString(), new PartitionKey($"Scoring-{code}"));
- if (null != scoring)
- {
- scoring.scores[sin] = score.GetDouble();
- scoring.items[sin].isArb = 1;
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
- queryText: $"select value(c) from c where c.examId = '{scoring.examId}' and c.subjectId = '{scoring.subjectId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
- {
- classResults.Add(item);
- }
- foreach (ExamClassResult exam in classResults)
- {
- int index = exam.studentIds.IndexOf(scoring.stuId);
- if (index != -1)
- {
- exam.studentScores[index][sin] = score.GetDouble();
- //exam.mark[index] = scoring.marks;
- }
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
- }
- }
- else
- {
- return Ok(new { code = 404 });
- }
- var sc = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey($"{scoring.code}"));
- return Ok(new { sc });
- }
- //阅卷信息统计
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("analysis-scoring")]
- public async Task<IActionResult> Analysis(JsonElement requert)
- {
- 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 queryTeacher = $"select c.id,c.name from c ";
- //List<object> props = new List<object>();
- List<(string id, string name)> tInfos = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: queryTeacher, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
- {
- 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())
- {
- tInfos.Add((obj.GetProperty("id").GetString(), obj.GetProperty("name").GetString()));
- }
- }
- }
- var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Exam-{code}"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- ExamInfo info = json.ToObject<ExamInfo>();
- List<ExamClassResult> classResults = new();
- List<SDK.Models.Cosmos.Common.Scoring> attr = new List<SDK.Models.Cosmos.Common.Scoring>();
- 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);
- }
- List<SDK.Models.Cosmos.Common.Scoring> errs = new();
- List<(string subjectId, int count)> ps = new List<(string subjectId, int count)>();
- List<(string subjectId, int count)> tps = new List<(string subjectId, int count)>();
- List<(string subjectId, int count)> arbs = new List<(string subjectId, int count)>();
- List<(string subjectId, int count)> tarbs = new List<(string subjectId, int count)>();
- List<(string subjectId, int count)> cs = new List<(string subjectId, int count)>();
- foreach (ExamSubject subject in info.subjects)
- {
- int qsCount = 0;
- int tqsCount = 0;
- int arbCount = 0;
- int tarbCount = 0;
- int csCount = 0;
- foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
- {
- if (subject.id.Equals(ss.subjectId))
- {
- List<Qs> qs = ss.qs.Where(s => !string.IsNullOrEmpty(s.err)).ToList();
- if (qs.Count > 0)
- {
- qsCount++;
- }
- List<Qs> tqs = ss.qs.Where(s => !string.IsNullOrEmpty(s.improve)).ToList();
- if (tqs.Count > 0)
- {
- tqsCount++;
- }
- List<Item> arb = ss.items.Where(s => s.flag == false).ToList();
- if (arb.Count > 0)
- {
- arbCount++;
- }
- List<Item> tarb = ss.items.Where(s => s.isArb == 1 && s.flag == false).ToList();
- if (tarb.Count > 0)
- {
- tarbCount++;
- }
- bool flag = ss.scores.Exists(s => s == -1);
- if (!flag) csCount++;
- }
- }
- ps.Add((subject.id, qsCount));
- tps.Add((subject.id, tqsCount));
- arbs.Add((subject.id, arbCount));
- tarbs.Add((subject.id, tarbCount));
- cs.Add((subject.id, csCount));
- }
- //阅卷老师
- List<object> teachers = new();
- Correct correct = null;
- List<(string sub, List<string> ids)> errIds = new();
- List<(string sub, List<string> ids)> arbIds = new();
- var cResponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Correct-{code}"));
- if (cResponse.Status == 200)
- {
- using var cJson = await JsonDocument.ParseAsync(cResponse.ContentStream);
- correct = cJson.ToObject<Correct>();
- foreach (CorSub corSub in correct.subs)
- {
- List<string> eName = new();
- List<string> aName = new();
- foreach (string s in corSub.err)
- {
- eName.Add(tInfos.Where(t => t.id.Equals(s)).Select(s => s.name).First());
- }
- foreach (string s in corSub.arb)
- {
- aName.Add(tInfos.Where(t => t.id.Equals(s)).Select(s => s.name).First());
- }
- errIds.Add((corSub.id, eName));
- arbIds.Add((corSub.id, aName));
- foreach (CorTmd corTmd in corSub.markers)
- {
- int qus = 0;
- int quf = 0;
- int tArbs = 0;
- int fArbs = 0;
- int sCount = 0;
- int fCount = 0;
- foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
- {
- if (ss.subjectId.Equals(corSub.id))
- {
- foreach (Qs qs in ss.qs)
- {
- if (!string.IsNullOrEmpty(qs.err) && qs.tId.Equals(corTmd.id))
- {
- qus++;
- }
- if (!string.IsNullOrEmpty(qs.improve) && qs.tId.Equals(corTmd.id))
- {
- quf++;
- }
- }
- List<double> sigles = new();
- foreach (Item item in ss.items)
- {
- if (item.scores.Exists(sc => sc.tmdId.Equals(corTmd.id)) && item.isArb == 1)
- {
- tArbs++;
- }
- if (item.flag == true && item.isArb == 1)
- {
- fArbs++;
- }
- var tsc = item.scores.Where(t => t.tmdId.Equals(corTmd.id)).Select(s => s.sc).ToList();
- sigles.AddRange(tsc);
- }
- bool flag = sigles.Exists(s => s == -1);
- if (!flag && sigles.Count == ss.items.Count)
- {
- fCount++;
- }
- sCount = corTmd.count;
- }
- }
- var obj = new
- {
- sId = corSub.id,
- sName = corSub.name,
- name = corTmd.name,
- qus,
- quf,
- tArbs,
- fArbs,
- fCount,
- sCount,
- };
- teachers.Add(obj);
- }
- }
- }
- var sc = info.subjects.Select(s => new
- {
- s.name,
- count = info.stuCount,
- num = info.stuCount * correct.num,
- tqs = tps.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First(),
- qs = ps.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First(),
- errName = errIds.Where(q => q.sub.Equals(s.id)).Select(c => c.ids).FirstOrDefault(),
- tarbs = tarbs.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First(),
- arbs = arbs.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First(),
- arbName = arbIds.Where(q => q.sub.Equals(s.id)).Select(c => c.ids).FirstOrDefault(),
- cs = cs.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First()
- }); ;
- return Ok(new { sc, teachers });
- }
- else
- {
- return BadRequest();
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/analysis-scoring\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /*private async Task deleteAsync(CosmosClient client, string id, string tId)
- {
- List<string> correctIds = new List<string>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: $"select c.id from c where c.cid = '{id}' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"CorrectTask-{tId}") }))
- {
- using var jsonTask = await JsonDocument.ParseAsync(item.ContentStream);
- if (jsonTask.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = jsonTask.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- correctIds.Add(account.GetProperty("id").GetString());
- }
- }
- }
- if (correctIds.Count > 0)
- {
- await client.GetContainer(Constant.TEAMModelOS, "Teacher").DeleteItemsStreamAsync(correctIds, $"CorrectTask-{tId}");
- }
- }*/
- private async Task<(string blob, List<double>)> getMoreStuInfo(CosmosClient client, string stuId, string examId, string subjectId, string code)
- {
- var queryClass = $"select c.studentAnswers,c.studentIds,c.studentScores from c where array_contains(c.studentIds,'{stuId}') and c.examId = '{examId}' and c.subjectId = '{subjectId}'";
- List<List<string>> ans = new List<List<string>>();
- List<string> ids = new List<string>();
- List<List<double>> scs = new List<List<double>>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: queryClass, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{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;
- ans = account.GetProperty("studentAnswers").ToObject<List<List<string>>>();
- ids = account.GetProperty("studentIds").ToObject<List<string>>();
- scs = account.GetProperty("studentScores").ToObject<List<List<double>>>();
- }
- }
- }
- int num = ids.IndexOf(stuId);
- string ansBlob = "";
- List<double> scores = new List<double>();
- if (num >= 0)
- {
- if (ans[num].Count > 0)
- {
- ansBlob = ans[num].First();
- }
- scores = scs[num];
- }
- return (ansBlob, scores);
- }
- }
- public class stus
- {
- public string id { get; set; }
- public int type { get; set; }
- }
- public class ufo
- {
- public string id { get; set; }
- public string name { get; set; }
- public int type { get; set; }
- }
- }
|