12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313 |
- using Azure.Cosmos;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Options;
- using System;
- using System.Collections.Generic;
- 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.Extension;
- 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;
- using Microsoft.AspNetCore.Hosting;
- using static TEAMModelOS.SDK.SchoolService;
- using Azure.Core;
- using DocumentFormat.OpenXml.Spreadsheet;
- using DocumentFormat.OpenXml.Wordprocessing;
- using Item = TEAMModelOS.SDK.Models.Cosmos.Common.Item;
- using DocumentFormat.OpenXml.Office2016.Excel;
- using OpenXmlPowerTools;
- using TEAMModelOS.SDK.Services;
- using TEAMModelOS.SDK.Models.Service.BI;
- using MathNet.Numerics.RootFinding;
- using TEAMModelOS.SDK.Models.Cosmos.Student;
- using DocumentFormat.OpenXml.Drawing.Charts;
- using ClouDASLibx;
- using HTEXLib.Helpers.ShapeHelpers;
- using TEAMModelOS.SDK.Helper.Common.DateTimeHelper;
- using Microsoft.Extensions.Hosting;
- using System.Configuration;
- using DocumentFormat.OpenXml.Presentation;
- using static SKIT.FlurlHttpClient.Wechat.TenpayV3.Models.CreateApplyForSubjectApplymentRequest.Types;
- using TEAMModelOS.Controllers.Core;
- using Azure.Storage.Blobs.Models;
- using Top.Api;
- using Newtonsoft.Json.Linq;
- using System.IO;
- 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 CoreAPIHttpService _coreAPIHttpService;
- private readonly IWebHostEnvironment _environment;
- public ExamController(IWebHostEnvironment environment, CoreAPIHttpService coreAPIHttpService, AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing,
- IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, IConfiguration configuration)
- {
- _azureCosmos = azureCosmos;
- _serviceBus = serviceBus;
- _snowflakeId = snowflakeId;
- _dingDing = dingDing;
- _option = option?.Value;
- _azureStorage = azureStorage;
- _azureRedis = azureRedis;
- _configuration = configuration;
- _coreAPIHttpService = coreAPIHttpService;
- _environment = environment;
- }
- /// <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.GetMemberByListids(_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}");
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = request.school }, _serviceBus, _configuration, _azureRedis);
- }
- else
- {
- request.size = await _azureStorage.GetBlobContainerClient(request.creatorId).GetBlobsSize($"exam/{request.id}");
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = request.creatorId }, _serviceBus, _configuration, _azureRedis);
- }
- 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}"));
- await BIStats.SetTypeAddStats(client, _dingDing, exam.school, "Exam", 1);//BI统计增/减量
- }
- else
- {
- var response = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(request.id, new PartitionKey($"{request.code}"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- ExamInfo info = json.ToObject<ExamInfo>();
- 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}");
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = $"exam", name = request.school }, _serviceBus, _configuration, _azureRedis);
- }
- else
- {
- request.size = await _azureStorage.GetBlobContainerClient(request.creatorId).GetBlobsSize($"exam/{request.id}");
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = $"exam", name = request.creatorId }, _serviceBus, _configuration, _azureRedis);
- }
- 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}"));
- }
- else
- {
- 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}");
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = request.school }, _serviceBus, _configuration, _azureRedis);
- }
- else
- {
- request.size = await _azureStorage.GetBlobContainerClient(request.creatorId).GetBlobsSize($"exam/{request.id}");
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = request.creatorId }, _serviceBus, _configuration, _azureRedis);
- }
- int n = 0;
- List<string> sheetIds = new List<string>();
- foreach (PaperSimple simple in request.papers)
- {
- if (!string.IsNullOrEmpty(simple.subjectId))
- {
- simple.blob = $"/exam/{request.id}/paper/{simple.subjectId}/{simple.id}";
- }
- else
- {
- 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}"));
- await BIStats.SetTypeAddStats(client, _dingDing, exam.school, "Exam", 1);//BI统计增/减量
- }
- }
- return Ok(new { exam });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/save()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /* [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher,admin")]
- [HttpPost("read-score")]
- // [Authorize(Roles = "IES")]
- public async Task<IActionResult> getAverage(JsonElement request) {
- var client = _azureCosmos.GetCosmosClient();
- var grades = ExamService.getGradeScore(_coreAPIHttpService,_dingDing,client,2021,"二年级", "463db08d-cbe7-48a0-a81a-fc39b3c1fep1","hbcn", 1688349974000, 1693706774000);
- return Ok(grades);
- }*/
- /// <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}\n", 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;
- var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.GetString(), new PartitionKey($"Exam-{code}"));
- if (response.Status == 200)
- {
- using var jsonExam = await JsonDocument.ParseAsync(response.ContentStream);
- exam = jsonExam.ToObject<ExamInfo>();
- 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}" });
- //通知评测删除信息
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "delete", root = $"exam", name = $"{code}" }, _serviceBus, _configuration, _azureRedis);
- //删除阅卷配置
- 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}");
- }
- return Ok(new { id });
- }
- else
- {
- return NotFound(new { msg = "未找到对应内容" });
- }
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/delete()\n{e.Message}\n{e.StackTrace}\n", 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 request)
- {
- try
- {
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- StringBuilder stringBuilder = new($"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.stuLists, c.sRate,c.lostStu,c.sStatus,c.qamode,c.school,c.cloudas from c where (c.status<>404 or IS_DEFINED(c.status) = false) ");
- if (request.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);
- stringBuilder.Append($" and {ss}");
- };
- //开始时间,
- if (request.TryGetProperty("stime", out JsonElement stime))
- {
- if (long.TryParse($"{stime}", out long data))
- {
- stringBuilder.Append($" and c.createTime >= {data} ");
- };
- };
- //默认当前时间
- if (request.TryGetProperty("etime", out JsonElement etime))
- {
- if (long.TryParse($"{etime}", out long data))
- {
- stringBuilder.Append($" and c.createTime <= {data} ");
- };
- };
- if (request.TryGetProperty("period", out JsonElement period) && !string.IsNullOrWhiteSpace($"{period}"))
- {
- stringBuilder.Append($" and c.period.id = '{period}' ");
- }
- if (request.TryGetProperty("name", out JsonElement name) && !string.IsNullOrWhiteSpace($"{name}"))
- {
- stringBuilder.Append($" and Contains( c.name , '{name}') = true ");
- }
- if (request.TryGetProperty("progress", out JsonElement progress) && !string.IsNullOrWhiteSpace($"{progress}"))
- {
- stringBuilder.Append($" and c.progress = '{progress}' ");
- }
- if (request.TryGetProperty("source", out JsonElement source) && !string.IsNullOrWhiteSpace($"{source}"))
- {
- stringBuilder.Append($" and c.source = '{source}' ");
- }
- stringBuilder.Append("order by c.createTime desc");
- //string token = null;
- string token = default;
- //默认不指定返回大小
- int? topcout = null;
- if (request.TryGetProperty("count", out JsonElement jcount))
- {
- if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
- {
- topcout = data;
- }
- }
- //是否需要进行分页查询,默认不分页
- bool iscontinuation = false;
- if (topcout != null && topcout.Value > 0)
- {
- iscontinuation = true;
- }
- //如果指定了返回大小
- if (request.TryGetProperty("token", out JsonElement token_1))
- {
- if (!token_1.ValueKind.Equals(JsonValueKind.Null) && token_1.ValueKind.Equals(JsonValueKind.String))
- {
- token = token_1.GetString();
- }
- }
- List<ExamInfo> examInfo = new List<ExamInfo>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: stringBuilder.ToString(), 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)
- {
- token = item.GetContinuationToken();
- break;
- }
- }
- return Ok(new { examInfo, token = token });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find()\n{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin,student")]
- #if !DEBUG
- [Authorize(Roles = "IES")]
- #endif
- [HttpPost("find-by-analysis")]
- public async Task<IActionResult> FindByAnalysis(JsonElement request)
- {
- try
- {
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- var table = _azureStorage.GetCloudTableClient().GetTableReference("SchoolYear");
- List<SchoolYear> years = await table.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 table.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 table.Save<SchoolYear>(sy);
- }
- string sub = string.Empty;
- string subject = string.Empty;
- if (request.TryGetProperty("subjectId", out JsonElement subjectId) && !string.IsNullOrWhiteSpace($"{subjectId}"))
- {
- sub = $" join A0 in c.subjects ";
- subject = $" and A0.id = '{subjectId}'";
- }
- string grade = string.Empty;
- string grades = string.Empty;
- if (request.TryGetProperty("grades", out JsonElement gs) && !string.IsNullOrWhiteSpace($"{gs}"))
- {
- grade = $" join A1 in c.grades ";
- grades = $" and A1.id = '{gs}'";
- }
- StringBuilder stringBuilder = new StringBuilder($"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,c.qamode,c.school,c.creatorId from c {sub} {grade}" +
- $"where (c.status<>404 or IS_DEFINED(c.status) = false) and c.scope = 'school' and c.qamode <> 2 and c.school = '{code}' and c.pk = 'Exam' {subject} {grades}");
- if (request.TryGetProperty("period", out JsonElement period) && !string.IsNullOrWhiteSpace($"{period}"))
- {
- stringBuilder.Append($" and c.period.id = '{period}' ");
- }
- if (request.TryGetProperty("owner", out JsonElement owner) && !string.IsNullOrWhiteSpace($"{owner}"))
- {
- stringBuilder.Append($" and c.owner= '{owner}' ");
- }
- if (request.TryGetProperty("year", out JsonElement yy) && !string.IsNullOrWhiteSpace($"{yy}"))
- {
- int end = yy.GetInt32() + 1;
- long stime = DateTimeOffset.Parse($"{yy.GetInt32()}-1-1").ToUnixTimeMilliseconds();
- long etime = DateTimeOffset.Parse($"{end}-1-1").ToUnixTimeMilliseconds();
- stringBuilder.Append($" and c.startTime >= {stime} and c.startTime < {etime} ");
- }
- if (request.TryGetProperty("name", out JsonElement name) && !string.IsNullOrWhiteSpace($"{name}"))
- {
- stringBuilder.Append($" and Contains( c.name , '{name}') = true ");
- }
- if (request.TryGetProperty("examType", out JsonElement examType) && !string.IsNullOrWhiteSpace($"{examType}"))
- {
- stringBuilder.Append($" and c.examType.id = '{examType}' ");
- }
- if (request.TryGetProperty("progress", out JsonElement progress) && !string.IsNullOrWhiteSpace($"{progress}"))
- {
- stringBuilder.Append($" and c.progress = '{progress}' ");
- }
- if (request.TryGetProperty("source", out JsonElement source) && !string.IsNullOrWhiteSpace($"{source}"))
- {
- stringBuilder.Append($" and c.source = '{source}' ");
- }
- if (request.TryGetProperty("creatorId", out JsonElement creatorId) && !string.IsNullOrWhiteSpace($"{creatorId}"))
- {
- stringBuilder.Append($" and c.creatorId = '{creatorId}' ");
- }
- stringBuilder.Append("order by c.createTime desc");
- string token = default;
- //是否需要进行分页查询,默认不分页
- bool iscontinuation = false;
- if (request.TryGetProperty("token", out JsonElement token_1))
- {
- token = token_1.GetString();
- };
- //默认不指定返回大小
- int? topcout = null;
- if (request.TryGetProperty("count", out JsonElement jcount))
- {
- if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
- {
- topcout = data;
- }
- }
- if (topcout != null && topcout.Value > 0)
- {
- iscontinuation = true;
- }
- List<ExamInfo> examInfo = new List<ExamInfo>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: stringBuilder.ToString(), continuationToken: token, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout }))
- {
- 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)
- {
- token = item.GetContinuationToken();
- break;
- }
- }
- List<ExamInfo> exams = new List<ExamInfo>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: stringBuilder.ToString()))
- {
- 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())
- {
- exams.Add(obj.ToObject<ExamInfo>());
- }
- }
- }
- var groups = exams.Where(e => null != e.examType && !string.IsNullOrWhiteSpace(e.examType.id)).GroupBy(x => x.examType.name).Select(y => new { key = y.Key, count = y.ToList().Count }).ToList();
- return Ok(new { examInfo, token = token, year, count = exams.Count, groups });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-by-analysis()\n{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("find-summary")]
- public async Task<IActionResult> FindSummary(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();
- 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}\n{e.StackTrace}", 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, name, picture, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- List<string> ids = new List<string>();
- ids = classId.ToObject<List<string>>();
- var client = _azureCosmos.GetCosmosClient();
- ExamInfo info = new();
- var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"{scode}"));
- if (response.Status == 200)
- {
- using var cJson = await JsonDocument.ParseAsync(response.ContentStream);
- info = cJson.ToObject<ExamInfo>();
- }
- else
- {
- return Ok(new { code = 404, msg = "该活动未被找到" });
- }
- //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 = 404, msg = "未找到相关班级信息" });
- if (string.IsNullOrEmpty(userId)) return Ok(new { code = 404, 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);
- // }
- //}
- int newIndex = result.studentIds.IndexOf(userId.ToString());
- StringBuilder builder = new();
- 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.GetBlobContainerClient(code.ToString()).UploadFileByContainer(ans.ToJsonString(), "exam", builder.ToString(), false));
- result.studentAnswers[newIndex].Add(builder.ToString());
- result.status[newIndex] = 0;
- //}
- //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 sc = standard[i].Count;
- var ac = ans[i].Where(a => a.Trim().Length > 0).ToList().Count;
- //算分处理
- if (sc > 0)
- {
- /* if (ans[i].Count == 0)
- {
- continue;
- }*/
- result.ans[newIndex][i] = ans[i];
- if (ac == sc && sc == 1)
- {
- foreach (string right in ans[i])
- {
- if (standard[i].Contains(right.Trim()))
- {
- 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;
- var a = result.studentScores.Where(z => z.Contains(-1));
- if (a.Any())
- {
- flag = false;
- }
- //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);
- int userType = $"{scope}".Equals(Constant.ScopeStudent) ? 2 : 1;
- 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}"));
- }
- result.sum[newIndex] = result.studentScores[newIndex].Sum();
- classResult = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
- 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 = 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}"));
- }
- }
- else
- {
- if (request.TryGetProperty("artId", out JsonElement artId) && request.TryGetProperty("quotaId", out JsonElement quotaId))
- {
- await getArtInfoAsync(client, artId.GetString(), school, result.sum[newIndex], id.GetString(), subjectId.GetString(), quotaId.GetString(), userId, picture, name, userType, ids);
- };
- 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}"));
- }
- }
- }
- 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}\n\n{id.GetString()}\n{request.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- private async Task getArtInfoAsync(CosmosClient client, string artId, string school, double score, string acId, string subject, string quotaId, string userid, string picture, string name, int userType, List<string> cIds)
- {
- var aresponse = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(artId, new PartitionKey($"Art-{school}"));
- ArtEvaluation art;
- StudentArtResult artResult;
- string rId = string.Format("{0}{1}{2}", school, "-", userid);
- if (aresponse.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(aresponse.ContentStream);
- art = json.ToObject<ArtEvaluation>();
- var response = await client.GetContainer("TEAMModelOS", "Student").ReadItemStreamAsync(rId, new PartitionKey($"ArtResult-{artId}"));
- if (response.Status == 200)
- {
- using var json_1 = await JsonDocument.ParseAsync(response.ContentStream);
- artResult = json_1.ToObject<StudentArtResult>();
- //bool flage = artResult.results.Exists(a => a.taskId == acId);
- artResult.results.ForEach(a =>
- {
- if (a.taskId == acId)
- {
- a.score = score;
- }
- });
- await client.GetContainer("TEAMModelOS", "Student").ReplaceItemAsync(artResult, artResult.id, new PartitionKey($"{artResult.code}"));
- }
- else
- {
- artResult = new StudentArtResult
- {
- id = rId,
- pk = "ArtResult",
- code = $"ArtResult-{artId}",
- studentId = userid,
- picture = picture,
- studentName = name,
- school = school,
- userType = userType,
- artId = artId,
- classIds = cIds,
- };
- art.settings.ForEach(qIds =>
- {
- qIds.task.ForEach(task =>
- {
- ArtQuotaResult quotaResult = new()
- {
- quotaId = qIds.id,
- quotaName = qIds.quotaname,
- quotaType = (int)task.type,
- taskId = task.acId,
- subjectId = task.subject
- };
- if (!string.IsNullOrEmpty(quotaResult.taskId))
- {
- if (quotaResult.taskId.Equals(acId))
- {
- quotaResult.score = score;
- }
- }
- artResult.results.Add(quotaResult);
- });
- });
- //foreach (var qIds in art.settings)
- //{
- // foreach (var task in qIds.task)
- // {
- // ArtQuotaResult quotaResult = new()
- // {
- // quotaId = qIds.id,
- // quotaName = qIds.quotaname,
- // quotaType = (int)task.type,
- // taskId = task.acId,
- // subjectId = task.subject
- // };
- // if (!string.IsNullOrEmpty(quotaResult.taskId))
- // {
- // if (quotaResult.taskId.Equals(acId))
- // {
- // quotaResult.score = score;
- // }
- // }
- // artResult.results.Add(quotaResult);
- // }
- //}
- await client.GetContainer("TEAMModelOS", "Student").CreateItemAsync(artResult, new PartitionKey($"{artResult.code}"));
- }
- }
- }
- [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\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 distinct c.id,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.scIds[index]}-{s.id}"));
- activity.sStatus = 1;
- await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{result.scIds[index]}-{s.id}"));*/
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{_option.Location}\n{ex.Message}\n{ex.StackTrace}\n\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);
- }
- //检查所有成员是否完成打分
- List<List<double>> ers = new List<List<double>>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(
- queryText: $"select c.studentScores as scores from c where c.examId = '{id}'",
- 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)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- List<List<double>> sc = account.GetProperty("scores").ToObject<List<List<double>>>();
- ers.AddRange(sc);
- }
- }
- }
- var isScore = ers.Exists(c => !c.Contains(-1));
- return Ok(new { classResult, isScore });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/upsertRecordByTeacher()\n\n", 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 request)
- {
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- //if (!request.TryGetProperty("code", out JsonElement school_code)) return BadRequest();
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement school_code)) return BadRequest();
- if (!request.TryGetProperty("classId", out JsonElement classId)) return BadRequest();
- try
- {
- // 如果只有学生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.scIds,c.info,c.studentIds,c.studentAnswers,c.studentScores,c.mark,c.status 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();
- //List<string> codes = new();
- foreach (ExamClassResult result in examClassResults)
- {
- ids.AddRange(result.studentIds);
- //codes.AddRange(result.scIds);
- }
- List<string> cid = new()
- {
- classId.GetString()
- };
- (List<RMember> members, List<RGroupList> groups) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, cid, $"{school}");
- //await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<GroupList>(classId.GetString, new PartitionKey($"Exam-{code}"));
- ///获取真实的名称
- List<ufo> ufos = new();
- List<string> delIds = new();
- if (groups.Count > 0)
- {
- string scode = groups[0].school;
- if (ids.Count > 0)
- {
- List<string> sIds = new();
- List<string> tIds = new();
- List<ufo> students = new List<ufo>();
- if (string.IsNullOrEmpty(scode))
- {
- 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.location}用户转换失败:{_coreAPIHttpService.options.coreUrl}{json}\n ", GroupNames.醍摩豆服務運維群組);
- }
- }
- }
- else
- {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: $"select distinct c.id,c.name from c where c.id in ({string.Join(",", ids.Select(o => $"'{o}'"))}) and c.pk = 'Base'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{scode}") }))
- {
- 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(),
- //schoolId = account.GetProperty("schoolId").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.location}用户转换失败:{_coreAPIHttpService.options.coreUrl}{json}\n ", GroupNames.醍摩豆服務運維群組);
- }
- }
- }
- delIds = ids.Except(sIds.Union(tIds)).ToList();
- }
- }
- }
- }
- //List<ufo> students = new List<ufo>();
- /*if (StringHelper.getKeyCount(request) == 1 && request.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 (request.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}\n{ex.StackTrace}\n\n{id.GetString()}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //学生端查询评测列表
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "student,teacher,admin")]
- [HttpPost("find-summary-by-student")]
- public async Task<IActionResult> findSummaryStudent(JsonElement request)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("cIds", out JsonElement cIds)) return BadRequest();
- if (!request.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement school)) return BadRequest();
- if (!request.TryGetProperty("scode", out JsonElement scode)) return BadRequest();
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- //var query = $"select value(c) where c.id ='{id}'";
- //List<ExamInfo> exams = new List<ExamInfo>();
- List<object> subjects = new List<object>();
- List<string> classIds = new List<string>();
- //List<string> stus = new List<string>();
- //存放当前学生所在班级ID或者名单ID
- /*HashSet<string> resultIds = new();
- //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);
- }
- }*/
- //List<string> infoIds = cIds.ToObject<List<string>>();
- List<string> infoIds = new();
- ExamInfo info = new();
- var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"{scode}"));
- if (response.Status == 200)
- {
- using var cJson = await JsonDocument.ParseAsync(response.ContentStream);
- info = cJson.ToObject<ExamInfo>();
- }
- /*await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamInfo>(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
- {
- exams.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.average,c.sum,c.mark,c.krate,c.frate,c.info.id as cId 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>());
- infoIds.Add(obj.GetProperty("cId").GetString());
- }
- }
- }
- var queryResult = $"select c.id,c.code,c.studentIds,c.subjectId,c.studentAnswers,c.studentScores,c.average,c.sum,c.mark,c.krate,c.frate,c.info.id as cId from c where c.examId ='{id}' and c.pk = 'ExamClassResult' ";
- List<ExamClassResult> classResults = new List<ExamClassResult>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(queryText: queryResult,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
- {
- classResults.Add(item);
- }
- //查询结果
- List<ExamResult> results = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamResult>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamResult-{id}") }))
- {
- results.Add(item);
- }
- 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, List<double> akps)> know = new();
- List<(List<int> fs, List<double> fps, List<double> cfps, List<double> afps)> fp = new();
- List<List<double>> wno = new();
- List<KeyValuePair<string, List<KeyValuePair<string, Dictionary<string, string>>>>> subjectScatter = new();
- if (!string.IsNullOrEmpty(info.progress) && info.progress.Equals("finish"))
- {
- (List<RMember> members, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, infoIds, school.GetString(), null);
- await foreach (var s in stuTask(subId, info.papers, answers, classResults, studentId.GetString()))
- {
- know = s.know;
- fp = s.filed;
- }
- foreach (ExamResult exam in results)
- {
- subjectScatter.Add(DoSubjectScatter(exam, members));
- //确定当前循环科目索引位置
- int index = subId.IndexOf(exam.subjectId);
- //根据索引找到试卷分数
- List<double> points = info.papers[index].point;
- List<double> wn = await getWrongNum(exam, points, infoIds);
- wno.Add(wn);
- }
- if (info.papers.IsNotEmpty())
- {
- var knowledge = know.Select(k => new { k.kn, k.kps, k.ckps, k.akps });
- var filed = fp.Select(k => new { k.fs, k.fps, k.cfps, k.afps });
- //papers = papers
- return Ok(new { info.cloudas, info.papers, subjects, stuScore, stuAns, mark, total, claId = infoIds, knowledge, filed, average, wno, subjectScatter, status = 200 });
- }
- }
- return Ok(new { info.cloudas, info.papers, subjects, stuScore, stuAns, mark, total, claId = infoIds, knowledge = new List<object>(), filed = new List<object>(), average, wno, subjectScatter, status = 200 });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-summary-by-student()\n{ex.Message}\n{ex.StackTrace}\n\n{id.GetString()}", GroupNames.醍摩豆服務運維群組);
- return Ok(new { status = 500 });
- }
- }
- private async IAsyncEnumerable<(List<(List<string> kn, List<double> kps, List<double> ckps, List<double> akps)> know, List<(List<int> fs, List<double> fps, List<double> cfps, List<double> afps)> filed)> stuTask(List<string> subjectIds, List<PaperSimple> papers, List<ExamClassResult> answers, List<ExamClassResult> results, string stuId)
- {
- List<(List<string> kn, List<double> kps, List<double> ckps, List<double> akps)> know = new List<(List<string> kn, List<double> kps, List<double> ckps, List<double> akp)>();
- List<(List<int> fs, List<double> fps, List<double> cfps, List<double> afps)> filed = new List<(List<int> fs, List<double> fps, List<double> cfps, List<double> afps)>();
- int no = 0;
- foreach (string sub in subjectIds)
- {
- List<double> kp = new();
- List<double> akp = new();
- List<double> fp = new();
- List<double> afp = 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)
- {
- knowles = new HashSet<string>(kones.SelectMany(z => z));
- }
- knowledges.AddRange(knowles.Where(z => !string.IsNullOrWhiteSpace(z)));
- List<ExamClassResult> classResults = answers.Where(result => !string.IsNullOrWhiteSpace(result?.subjectId) && result.subjectId.Equals(sub)).ToList();
- List<ExamClassResult> allResults = results.Where(result => !string.IsNullOrWhiteSpace(result?.subjectId) && result.subjectId.Equals(sub)).ToList();
- foreach (ExamClassResult result in classResults)
- {
- 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] * itemPersent;
- }
- }
- }
- 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;
- }
- foreach (string k in knowledges)
- {
- double score = 0;
- double allScore = 0;
- int count = 0;
- foreach (ExamClassResult result in allResults)
- {
- 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)
- {
- /*score += result.studentScores.ForEach(r => r[n]) * itemPersent;*/
- foreach (List<double> sc in result.studentScores)
- {
- double tsc = sc[n] == -1 ? 0 : sc[n];
- score += tsc * itemPersent;
- }
- }
- }
- n++;
- }
- count += result.studentIds.Count;
- }
- double per = count > 0 ? Math.Round(score / count, 2) : 0;
- akp.Add(allScore > 0 ? Math.Round(per / allScore, 2) : 0);
- }
- //处理认知层次
- foreach (int k in fields)
- {
- //初始化认知层次得分
- double score = 0;
- double allScore = 0;
- int count = 0;
- foreach (ExamClassResult result in allResults)
- {
- if (result.subjectId.Equals(sub))
- {
- 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)
- {
- foreach (List<double> sc in result.studentScores)
- {
- double tsc = sc[n] == -1 ? 0 : sc[n];
- score += tsc * itemPersent;
- }
- }
- }
- n++;
- }
- count += result.studentIds.Count;
- }
- }
- double per = count > 0 ? Math.Round(score / count, 2) : 0;
- afp.Add(allScore > 0 ? Math.Round(per / allScore, 2) : 0);
- }
- know.Add((knowledges, kp, ckp, akp));
- filed.Add((fields, fp, cfp, afp));
- no++;
- }
- yield return (know, filed);
- }
- private KeyValuePair<string, List<KeyValuePair<string, Dictionary<string, string>>>> DoSubjectScatter(ExamResult e, List<RMember> members)
- {
- List<KeyValuePair<string, Dictionary<string, string>>> datas = new();
- double[] point = StringHelper.ListTodouble(e.paper.point);
- double[,] result = StringHelper.ListToDouble(e.studentScores);
- List<string> scatterKey = new List<string>
- {
- "name",
- "className",
- "x",
- "y",
- "memberId",
- "score",
- "trueNum",
- "falseNum",
- "hardList",
- "carefulList",
- "scatter"
- };
- try
- {
- var cdm = new ClouDASMatrix(result, point);
- //学生通过率
- List<double> pass = cdm.ScoringRate;
- //学生稳定度
- List<double> sta = cdm.StabilityRate;
- //落点区域
- List<string> stu = cdm.StuFallArea;
- //需努力的题型
- List<int[]> strive = cdm.StriveTopic;
- //需小心的题型
- List<int[]> careful = cdm.CarefulTopic;
- int i = 0;
- for (int k = e.studentIds.Count - 1; k >= 0; k--)
- {
- if (e.studentIds[k].Equals("0"))
- {
- e.studentIds.Remove(e.studentIds[k]);
- }
- }
- e.studentIds.ForEach(s =>
- {
- List<string> info = new()
- {
- members.Where(c => c.id.Equals(s)).FirstOrDefault()?.name,
- "-",
- sta[i] > 1 ? "1": sta[i].ToString(),
- pass[i].ToString(),
- i + 1 + "",
- Math.Round(e.studentScores[i].Sum(),2).ToString()
- };
- int right = 0;
- int wrong = 0;
- foreach (double p in e.studentScores[i])
- {
- if (p > 0)
- {
- right++;
- }
- else
- {
- wrong++;
- }
- }
- info.Add(right + "");
- info.Add(wrong + "");
- int[] str = strive[i];
- string striveAll = "";
- foreach (int n in str)
- {
- striveAll += n.ToString() + ",";
- }
- int[] care = careful[i];
- string careAll = "";
- foreach (int n in care)
- {
- careAll += n.ToString() + ",";
- }
- if (string.IsNullOrEmpty(striveAll))
- {
- info.Add("-");
- }
- else
- {
- info.Add(striveAll.Substring(0, striveAll.Length - 1));
- }
- if (string.IsNullOrEmpty(careAll))
- {
- info.Add("-");
- }
- else
- {
- info.Add(careAll.Substring(0, careAll.Length - 1)); ;
- }
- info.Add(stu[i].ToString());
- int m = 0;
- Dictionary<string, string> scatter = new();
- foreach (string key in info)
- {
- scatter.Add(scatterKey[m], key);
- m++;
- }
- KeyValuePair<string, Dictionary<string, string>> keyValue = new(s, scatter);
- datas.Add(keyValue);
- //}
- i++;
- });
- return new KeyValuePair<string, List<KeyValuePair<string, Dictionary<string, string>>>>(e.subjectId, datas);
- }
- catch (Exception ex)
- {
- BadRequest(ex.Message + ex.StackTrace);
- }
- return default;
- }
- //查询学生活动列表
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "student")]
- [HttpPost("find-all-by-student")]
- public async Task<IActionResult> findAllStudent(JsonElement request)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.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 (!request.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}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return Ok(new { status = 500 });
- }
- }
- //查询学生活动列表
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "student")]
- [HttpPost("find-score-by-student")]
- public async Task<IActionResult> findScoreByStudent(JsonElement request)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- //if (!request.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}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return Ok(new { status = 500 });
- }
- }
- //查询学生活动列表
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("finish")]
- public async Task<IActionResult> finish(JsonElement request)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.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}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return Ok(new { status = 500 });
- }
- }
- /*//查询任务列表
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Student")]
- [HttpPost("scoring")]
- public async Task<IActionResult> Scoring(JsonElement request)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, 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("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}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }*/
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("scoring")]
- public async Task<IActionResult> scoring(JsonElement request)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, 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("subjectId", out JsonElement subjectId)) return BadRequest();
- //if (!request.TryGetProperty("type", out JsonElement type)) return BadRequest();
- if (!request.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
- if (!request.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 (request.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}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return Ok(new { status = 500 });
- }
- }
- //查找异常卷
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("find-err")]
- public async Task<IActionResult> findErr(JsonElement request)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, 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("subjectId", out JsonElement subjectId)) return BadRequest();
- //if (!request.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 Ok(new { status = response.Status });
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-err\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return Ok(new { status = 500 });
- }
- }
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("find-arb")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> findArb(JsonElement request)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, 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("subjectId", out JsonElement subjectId)) return BadRequest();
- if (!request.TryGetProperty("et", out JsonElement et)) return BadRequest();
- //if (!request.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}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return Ok(new { status = 500 });
- }
- }
- //批阅,给老师随机分配阅卷数据,以及查询改老师已有的阅卷数据
- 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", 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 request)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("stuId", out JsonElement sId)) return BadRequest();
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- if (!request.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
- if (!request.TryGetProperty("score", out JsonElement score)) return BadRequest();
- if (!request.TryGetProperty("count", out JsonElement count)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- request.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 (request.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();
- await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey(scoring.code));
- string sql = $"select c.id, c.name ,c.lang as code from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))})";
- List<IdNameCode> idNameCodes = new List<IdNameCode>();
- await foreach (var idNameCode in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIterator<IdNameCode>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- idNameCodes.Add(idNameCode);
- }
- _coreAPIHttpService.PushNotify(idNameCodes, $"{bizcode}_school", Constant.NotifyType_IES5_Task,
- new Dictionary<string, object> { { "tmdname", name }, { "schoolName", schname }, { "schoolId", $"{school}" }, { "tmdid", userid } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
- 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", GroupNames.醍摩豆服務運維群組);
- return Ok(new { status = 500 });
- }
- }
- //查询阅卷类型数据
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("find-scoring")]
- public async Task<IActionResult> findScoring(JsonElement request)
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("stuId", out JsonElement sId)) return BadRequest();
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- if (!request.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
- if (!request.TryGetProperty("type", out JsonElement type)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- List<SDK.Models.Cosmos.Common.Scoring> attr = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<SDK.Models.Cosmos.Common.Scoring>(
- queryText: $"select value(c) from c where c.examId = '{id}' 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 request)
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("err", out JsonElement err)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("index", out JsonElement index)) return BadRequest();
- if (!request.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();
- string sql = $"select c.id, c.name ,c.lang as code from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))})";
- List<IdNameCode> idNameCodes = new List<IdNameCode>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIterator<IdNameCode>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- idNameCodes.Add(item);
- }
- _coreAPIHttpService.PushNotify(idNameCodes, $"{bizcode}_school", Constant.NotifyType_IES5_Task,
- new Dictionary<string, object> { { "tmdname", name }, { "schoolName", schname }, { "schoolId", $"{school}" }, { "tmdid", userid } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
- /* 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 request)
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("improve", out JsonElement improve)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("index", out JsonElement index)) return BadRequest();
- //if (!request.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 request)
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("score", out JsonElement score)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!request.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]
- [AuthToken(Roles = "teacher,admin,student")]
- [HttpPost("score")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> score(JsonElement request)
- {
- if (!request.TryGetProperty("courseId", out JsonElement courseId)) return BadRequest();
- if (!request.TryGetProperty("cId", out JsonElement cId)) return BadRequest();
- //if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- List<(string eId, string cId, string cname, List<string> sIds, List<double> sum)> classResults = new();
- List<string> eIds = new();
- List<string> cIds = cId.ToObject<List<string>>();
- string soc = courseId.GetString();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(
- queryText: $"select c.examId as eId,c.info.id as cId,c.info.name as cName,c.studentIds,c.sum from c where c.subjectId = '{courseId}' and c.info.id in ({string.Join(",", cIds.Select(o => $"'{o}'"))})"))
- {
- 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;
- List<string> sIds = account.GetProperty("studentIds").ToObject<List<string>>();
- List<double> sum = account.GetProperty("sum").ToObject<List<double>>();
- eIds.Add(account.GetProperty("eId").GetString());
- List<double> nsum = new();
- foreach (double s in sum)
- {
- double ns = 0;
- if (s < 0)
- {
- ns = 0;
- }
- else
- {
- ns = s;
- }
- nsum.Add(ns);
- }
- classResults.Add((account.GetProperty("eId").GetString(), account.GetProperty("cId").GetString(), account.GetProperty("cName").GetString(), sIds, nsum));
- }
- }
- }
- string sub = string.Empty;
- if (request.TryGetProperty("subjectId", out JsonElement subjectId))
- {
- sub = subjectId.GetString();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(
- queryText: $"select c.examId as eId,c.info.id as cId,c.info.name as cName,c.studentIds,c.sum from c where c.subjectId = '{subjectId}' and c.info.id in ({string.Join(",", cIds.Select(o => $"'{o}'"))})"))
- {
- 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;
- List<string> sIds = account.GetProperty("studentIds").ToObject<List<string>>();
- List<double> sum = account.GetProperty("sum").ToObject<List<double>>();
- List<double> nsum = new();
- foreach (double s in sum)
- {
- double ns = 0;
- if (s < 0)
- {
- ns = 0;
- }
- else
- {
- ns = s;
- }
- nsum.Add(ns);
- }
- eIds.Add(account.GetProperty("eId").GetString());
- classResults.Add((account.GetProperty("eId").GetString(), account.GetProperty("cId").GetString(), account.GetProperty("cName").GetString(), sIds, nsum));
- }
- }
- }
- }
- List<(string id, string name, SDK.Models.Custom eType, string scope, string owner, long ctime, List<PaperSimple> points, List<ExamSubject> subject, string source)> exam = new();
- if (eIds.Count == 0)
- {
- return Ok(new { code = 404 });
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(
- queryText: $"select c.id,c.name,c.examType,c.scope,c.owner,c.createTime,c.papers ,c.subjects,c.source from c where c.id in ({string.Join(",", eIds.Select(o => $"'{o}'"))})"))
- {
- 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;
- SDK.Models.Custom eType = new();
- List<ExamSubject> subs = new();
- List<PaperSimple> ps = new();
- if (account.TryGetProperty("examType", out JsonElement examType))
- {
- eType = examType.ToObject<SDK.Models.Custom>();
- }
- if (account.TryGetProperty("papers", out JsonElement papers))
- {
- ps = papers.ToObject<List<PaperSimple>>();
- }
- if (account.TryGetProperty("subjects", out JsonElement subject))
- {
- subs = subject.ToObject<List<ExamSubject>>();
- }
- exam.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString(), eType, account.GetProperty("scope").GetString(),
- account.GetProperty("owner").GetString(), account.GetProperty("createTime").GetInt64(), ps, subs, account.GetProperty("source").GetString()));
- }
- }
- }
- var scores = classResults.Select(x => new
- {
- examId = x.eId,
- examName = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().name,
- scope = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().scope,
- eType = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().eType,
- classId = x.cId,
- cname = x.cname,
- studentIds = x.sIds,
- source = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().source,
- owner = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().owner,
- createTime = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().ctime,
- subject = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().subject,
- papers = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().points,
- sum = x.sum
- });
- if (request.TryGetProperty("stuId", out JsonElement stuId))
- {
- var info = scores.Where(x => !string.IsNullOrEmpty(x.examName) && x.studentIds.Contains(stuId.GetString())).Select(x => new
- {
- x.examId,
- x.examName,
- x.cname,
- studentId = stuId.GetString(),
- x.owner,
- x.createTime,
- x.eType,
- x.source,
- point = x.papers.Select(p => p.point),
- x.subject,
- sum = x.sum.ToList()[x.studentIds.IndexOf(stuId.GetString())]
- });
- return Ok(new { info });
- }
- else
- {
- var info = scores.Where(x => !string.IsNullOrEmpty(x.examName)).Select(x => new
- {
- x.examId,
- x.examName,
- x.cname,
- x.studentIds,
- x.owner,
- x.createTime,
- x.eType,
- x.source,
- point = x.papers.Select(p => p.point),
- x.subject,
- x.sum
- });
- return Ok(new { info });
- };
- }
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin,student")]
- [HttpPost("get-error-item")]
- public async Task<IActionResult> getErrorItems(JsonElement request)
- {
- //stuId
- if (!request.TryGetProperty("stuId", out JsonElement stuId)) return BadRequest();
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- StringBuilder stringBuilder = new($"select value(c) from c where c.stuId = '{stuId}' and c.subjectId = '{subjectId}'");
- /*if (request.TryGetProperty("period", out JsonElement period) && !string.IsNullOrWhiteSpace($"{period}"))
- {
- stringBuilder.Append($" and c.period.id = '{period}' ");
- }
- if (request.TryGetProperty("name", out JsonElement name) && !string.IsNullOrWhiteSpace($"{name}"))
- {
- stringBuilder.Append($" and Contains( c.name , '{name}') = true ");
- }
- if (request.TryGetProperty("progress", out JsonElement progress) && !string.IsNullOrWhiteSpace($"{progress}"))
- {
- stringBuilder.Append($" and c.progress = '{progress}' ");
- }
- if (request.TryGetProperty("source", out JsonElement source) && !string.IsNullOrWhiteSpace($"{source}"))
- {
- stringBuilder.Append($" and c.source = '{source}' ");
- }*/
- string pk = "ErrorItems";
- if (request.TryGetProperty("code", out JsonElement code) && !string.IsNullOrWhiteSpace($"{code}"))
- {
- stringBuilder.Append($" and c.school = '{code}' ");
- pk = $"ErrorItems-{code}";
- };
- stringBuilder.Append("order by c._ts desc");
- //string token = null;
- string token = default;
- //默认不指定返回大小
- int? topcout = null;
- if (request.TryGetProperty("count", out JsonElement jcount))
- {
- if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
- {
- topcout = data;
- }
- }
- //是否需要进行分页查询,默认不分页
- bool iscontinuation = false;
- if (topcout != null && topcout.Value > 0)
- {
- iscontinuation = true;
- }
- //如果指定了返回大小
- if (request.TryGetProperty("token", out JsonElement token_1))
- {
- if (!token_1.ValueKind.Equals(JsonValueKind.Null) && token_1.ValueKind.Equals(JsonValueKind.String))
- {
- token = token_1.GetString();
- }
- }
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- //var queryTeacher = $"select value(c) from c where c.stuId = '{stuId}' and c.school = '{code}' and c.subjectId = '{subjectId}'";
- List<ErrorItems> errorItems = new();
- List<string> ids = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: $"select A0.id from c join A0 in c.its where c.stuId = '{stuId}' and c.subjectId = '{subjectId}' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{pk}") }))
- {
- 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())
- {
- ids.Add(obj.GetProperty("id").ToString());
- }
- }
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: stringBuilder.ToString(), continuationToken: token, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout, PartitionKey = new PartitionKey($"{pk}") }))
- {
- 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())
- {
- errorItems.Add(obj.ToObject<ErrorItems>());
- }
- }
- if (iscontinuation)
- {
- token = item.GetContinuationToken();
- break;
- }
- }
- errorItems = errorItems.Where((x, i) => errorItems.FindIndex(z => z.id == x.id) == i).ToList();
- return Ok(new { errorItems, token,ids.Count });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/get-error-item()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest(new { code = 500 });
- }
- }
- //取得錯題庫前日錯題數及現在錯題數
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin,student")]
- [HttpPost("get-error-item-cnt")]
- public async Task<IActionResult> getErrorItemsCount(JsonElement request)
- {
- //輸入值
- if (!request.TryGetProperty("stuId", out JsonElement stuId)) return BadRequest();
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- string code = (request.TryGetProperty("code", out JsonElement codeJobj)) ? codeJobj.GetString() : string.Empty;
- string schCode = (!string.IsNullOrWhiteSpace(code)) ? code : "noschoolid";
- string teacherid = (request.TryGetProperty("teacherId", out JsonElement teacherId)) ? teacherId.GetString() : string.Empty;
- //取得Redis該學生該科目的錯題數 [算法變更,昨日錯題總數不再計入redis]
- int record = 0; //昨日取得的錯題數
- //var redisClient = _azureRedis.GetRedisClient(8);
- //string hkey = $"ErrorItems:{schCode}";
- //string hval = await redisClient.HashGetAsync(hkey, $"{stuId}");
- //List<stuErrorItemCnt> stuErrCntList = (hval != null) ? JsonSerializer.Deserialize<List<stuErrorItemCnt>>(hval) : new List<stuErrorItemCnt>();
- //stuErrorItemCnt stuErrCnt = stuErrCntList.Where(s => s.subjectId.Equals($"{subjectId}")).FirstOrDefault();
- //if (stuErrCnt != null)
- //{
- // record = stuErrCnt.number;
- //}
- //取得CosmosDB該學生該科目現在錯題數
- int avaliable = 0; //現在取得的錯題數
- List<string> itemIdList = new List<string>();
- var client = _azureCosmos.GetCosmosClient();
- string qryAdd = (!string.IsNullOrWhiteSpace(code)) ? $" AND c.school = '{code}' " : string.Empty;
- //string qry = $"SELECT SUM(ARRAY_LENGTH(c.its)) AS number, c.stuId, c.school, c.subjectId FROM c WHERE CONTAINS(c.code, 'ErrorItems') AND c.stuId = '{stuId}' AND c.subjectId = '{subjectId}'{qryAdd} GROUP BY c.stuId, c.school, c.subjectId";
- string pk = "ErrorItems";
- //string qry = "SELECT ARRAY(SELECT VALUE t.id FROM t IN c.its ) AS itemIds, c.stuId, c.school AS schoolId, c.subjectId, c.code FROM c WHERE " +
- // $"c.stuId = '{stuId}' AND c.subjectId = '{subjectId}'{qryAdd} ";
- string qry = $"SELECT i.blob, i.id, i.pId, c.stuId, c.school AS schoolId, c.subjectId, c.code FROM c JOIN i IN c.its WHERE " +
- $" c.stuId = '{stuId}' AND c.subjectId = '{subjectId}' {qryAdd} ";
- if (!string.IsNullOrWhiteSpace(code))
- {
- //qry += $"AND c.school = '{code}' ";
- pk = $"ErrorItems-{code}";
- };
- //await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: qry, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{pk}") }))
- //{
- // 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())
- // {
- // List<string> itemIdListRow = obj.GetProperty("itemIds").ToObject<List<string>>();
- // itemIdList = itemIdList.Union(itemIdListRow).ToList();
- // }
- // }
- //}
- //avaliable = itemIdList.Count;
- //return Ok(new { record, avaliable });
- Dictionary<string, string> dict = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: qry, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{pk}") }))
- {
- 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())
- {
- if (!dict.ContainsKey(obj.GetProperty("id").ToString()))
- {//去重複
- dict.Add(obj.GetProperty("id").ToString(), obj.GetProperty("blob").ToString());
- //if (!String.IsNullOrWhiteSpace(obj.GetProperty("pId") + ""))
- //{
- // if (!dict.ContainsKey(obj.GetProperty("pId").ToString()))
- // {
- // dict.Add(obj.GetProperty("pId").ToString(), obj.GetProperty("blob").ToString());
- // }
- //}
- //else
- //{
- // dict.Add(obj.GetProperty("id").ToString(), obj.GetProperty("blob").ToString());
- //}
- }
- }
- }
- }
- foreach (var obj in dict)
- {
- if (schCode != null && schCode != "noschoolid")
- {
- if (_azureStorage.GetBlobContainerClient(schCode).GetBlobClient($"{obj.Value}/{obj.Key}.json").Exists())
- {// 去除blob不存在項目
- avaliable++;
- }
- }
- else if (!string.IsNullOrWhiteSpace(teacherid))
- {
- if (_azureStorage.GetBlobContainerClient(teacherid).GetBlobClient($"{obj.Value}/{obj.Key}.json").Exists())
- {
- avaliable++;
- }
- }
- }
- return Ok(new { record, avaliable });
- }
- //取得錯題庫新增數
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin,student")]
- [HttpPost("get-error-item-today-cnt")]
- public async Task<IActionResult> getErrorItemsTodayCount(JsonElement request)
- {
- //輸入值
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest(); //科目ID
- if (!request.TryGetProperty("stuId", out JsonElement _stuId)) return BadRequest(); //學生ID 或 TMID
- string stuId = _stuId.GetString();
- string schoolid = (request.TryGetProperty("code", out JsonElement codeJobj)) ? codeJobj.GetString() : string.Empty; //學校簡碼,TMID時為空
- string tmdid = string.Empty;
- if (string.IsNullOrWhiteSpace(schoolid)) tmdid = stuId;
- string maLearnCode = string.Empty;
- //檢查參數 必須有 teammodelId 或是同時有學校id及學號
- if (!string.IsNullOrWhiteSpace(tmdid + ""))
- {
- maLearnCode = $"MaLearn-{tmdid}";
- }
- else if (!string.IsNullOrWhiteSpace(schoolid + "") && !string.IsNullOrWhiteSpace(stuId + ""))
- {
- maLearnCode = $"MaLearn-{schoolid}-{stuId}";
- }
- else { return BadRequest(); }
- DateTime nowDate = DateTime.Now;
- DateTime beforeDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
- string qry_All = $"SELECT COUNT(1) as num FROM c WHERE c.type = 'answer' AND c.unitId = '{subjectId}' AND IS_DEFINED(c.createdTime) AND c.createdTime <= {DateTimeHelper.ToUnixTimestamp(nowDate)}";
- string qry_before = $"SELECT COUNT(1) as num FROM c WHERE c.type = 'answer' AND c.unitId = '{subjectId}' AND IS_DEFINED(c.createdTime) AND c.createdTime <= {DateTimeHelper.ToUnixTimestamp(beforeDate)} ";
- var client = _azureCosmos.GetCosmosClient();
- int avaliable = 0;
- int allNum = 0;
- int berforeNum = 0;
- // 取全部錯題數量
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: qry_All, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{maLearnCode}") }))
- {
- 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())
- {
- if (obj.TryGetProperty("num", out JsonElement num))
- {
- allNum = num.GetInt32();
- }
- }
- }
- }
- // 取今天之前錯題的數量
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: qry_before, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{maLearnCode}") }))
- {
- 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())
- {
- if (obj.TryGetProperty("num", out JsonElement num))
- {
- berforeNum = num.GetInt32();
- }
- }
- }
- }
- avaliable = allNum - berforeNum;
- return Ok(new { avaliable });
- }
- //阅卷信息统计
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("analysis-scoring")]
- public async Task<IActionResult> Analysis(JsonElement request)
- {
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- //if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- //if (!request.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 Ok(new { status = response.Status });
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/analysis-scoring\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return Ok(new { status = 500 });
- }
- }
- /*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);
- }
- private Task<List<double>> getWrongNum(ExamResult result, List<double> points, List<string> infoIds)
- {
- int num = 0;
- List<double> wn = new List<double>();
- foreach (var point in points)
- {
- int wnum = 0;
- double p = point * 0.8;
- foreach (ClassRange range in result.classes)
- {
- if (!infoIds.Contains(range.id)) continue;
- for (int i = range.range[0]; i <= range.range[1]; i++)
- {
- //判断推送的数据中,学生正常得分数据
- if (result.studentScores[i].Count > 0)
- {
- if (result.studentScores[i][num] < point)
- {
- if (result.studentScores[i][num] < p)
- {
- wnum++;
- }
- else
- {
- continue;
- }
- }
- else
- {
- continue;
- }
- }
- else
- {
- wnum++;
- }
- }
- }
- wn.Add(wnum);
- num++;
- }
- return Task.FromResult(wn);
- }
- //获取题目信息
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher,admin,student")]
- [HttpPost("get-item")]
- //[Authorize(Roles = "IES")]
- public async Task<IActionResult> getItemInfo(JsonElement request)
- {
- if (!request.TryGetProperty("errorItems", out JsonElement items)) return BadRequest();
- List<errorItemInfo> errors = items.ToObject<List<errorItemInfo>>();
- var client = _azureCosmos.GetCosmosClient();
- List<string> ids = errors.Select(c => c.activityId).ToList();
- var queryClass = $"select value(c) from c where c.id in ({string.Join(",", ids.Select(o => $"'{o}'"))}) and c.pk = 'Exam'";
- List<ExamInfo> exams = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamInfo>(queryText: queryClass))
- {
- exams.Add(item);
- }
- List<JsonElement> elements = new();
- if (exams.Count > 0)
- {
- foreach (errorItemInfo itemInfo in errors) {
- ExamInfo info = exams.Where(c => c.id.Equals(itemInfo.activityId)).FirstOrDefault();
- List<ExamSubject> subjects = info.subjects;
- int index = 0;
- foreach (ExamSubject subject in subjects)
- {
- if (subject.id.Equals(itemInfo.unitId))
- {
- continue;
- }
- else
- {
- index++;
- }
- }
- List<PaperSimple> simples = info.papers;
- string blob = simples[index].blob;
- try {
- BlobDownloadResult index_item_json;
- if (info.scope.Equals("school"))
- {
- index_item_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{blob}/{itemInfo.qId}.json").DownloadContentAsync();
- }
- else
- {
- index_item_json = await _azureStorage.GetBlobContainerClient($"{info.creatorId}").GetBlobClient($"{blob}/{itemInfo.qId}.json").DownloadContentAsync();
- }
- JsonElement itemJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(index_item_json.Content.ToString()))).RootElement;
- elements.Add(itemJson);
- if (itemJson.TryGetProperty("pid", out JsonElement pid))
- {
- if (!string.IsNullOrEmpty(pid.ToString()))
- {
- BlobDownloadResult index_pid_item_json;
- if (info.scope.Equals("school"))
- {
- index_pid_item_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{blob}/{pid}.json").DownloadContentAsync();
- }
- else
- {
- index_pid_item_json = await _azureStorage.GetBlobContainerClient($"{info.creatorId}").GetBlobClient($"{blob}/{pid}.json").DownloadContentAsync();
- }
- JsonElement pidJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(index_pid_item_json.Content.ToString()))).RootElement;
- elements.Add(pidJson);
- }
- }
- } catch (Exception e) {
- return BadRequest(new { msg = "blob 文件读取异常" });
- }
-
- }
- }
- else
- {
- return BadRequest(new { msg = "暂无数据" });
- }
- return Ok(elements);
- }
- }
- 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; }
- }
- public class stuErrorItemCnt
- {
- public string subjectId { get; set; }
- public int number { get; set; }
- }
- public class errorItemInfo {
- public string activityId { get; set; }
- public string qId { get; set; }
- public string unitId { get; set; }
- }
- }
|