1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573 |
- using Microsoft.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 Microsoft.AspNetCore.Authorization;
- using System.Net.Http;
- using Microsoft.AspNetCore.Hosting;
- using static TEAMModelOS.SDK.SchoolService;
- using Azure.Core;
- using Item = TEAMModelOS.SDK.Models.Cosmos.Common.Item;
- using TEAMModelOS.SDK.Services;
- using TEAMModelOS.SDK.Models.Service.BI;
- using MathNet.Numerics.RootFinding;
- using TEAMModelOS.SDK.Models.Cosmos.Student;
- using ClouDASLibx;
- using Azure.Storage.Blobs.Models;
- using System.IO;
- using TEAMModelOS.SDK.Helper.Common.StringHelper;
- 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;
- private readonly IHttpClientFactory _httpClient;
- 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, IHttpClientFactory httpClient)
- {
- _azureCosmos = azureCosmos;
- _serviceBus = serviceBus;
- _snowflakeId = snowflakeId;
- _dingDing = dingDing;
- _option = option?.Value;
- _azureStorage = azureStorage;
- _azureRedis = azureRedis;
- _configuration = configuration;
- _coreAPIHttpService = coreAPIHttpService;
- _environment = environment;
- _httpClient = httpClient;
- }
- /// <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").GetItemQueryStreamIteratorSql(queryText: $"select c.id from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{request.school}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- 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").GetItemQueryStreamIteratorSql(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.Content);
- 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").GetItemQueryIteratorSql<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").GetItemQueryIteratorSql<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;
- }*/
- //var (grade, per) = await ThirdService.GetGradeAsync(client, request);
- /*var data = new
- {
- examName = request.name,
- examCategory = 1,
- //grade = int.Parse(grade),
- grade = 7,
- term = 2,
- examType = "单元测试",
- examDate = request.startTime,
- schId = 1,
- boeId = "",
- subjects = request.subjects.Select(c => c.name).ToList()
- };*/
- 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;
- }
-
- //string moofenCode = await ThirdService.CreateMoofenExam(_httpClient, data.ToJsonString().ToObject<JsonElement>(),_dingDing);
- //request.moofenCode = moofenCode;
- exam = await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(request, new PartitionKey($"{request.code}"));
-
- await BIStats.SetTypeAddStats(client, _dingDing, exam.school, "Exam", 1);//BI统计增/减量
- //await SystemService.RecordAccumulateData(_azureRedis, _dingDing, new SDK.Models.Dtos.Accumulate { client = "web", count = 1, id = request.id, key = "exam-submit", name = request.name, scope = request.scope, target = "hbcn/tmdid" });
- }
- else
- {
- var response = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(request.id, new PartitionKey($"{request.code}"));
- if (response.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- 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;
- }
- //string moofenCode = await ThirdService.CreateMoofenExam(_httpClient, data.ToJsonString().ToObject<JsonElement>());
- 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.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- 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.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var jsonExam = await JsonDocument.ParseAsync(response.Content);
- 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.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(cresponse.Content);
- 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").GetItemQueryIteratorSql<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").GetItemQueryStreamIteratorSql(queryText: $"select c.id from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamResult-{id}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- 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();
- //if (request.TryGetProperty("period", out JsonElement period)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- //if (!request.TryGetProperty("userId", out JsonElement userId)) return BadRequest();
- //if (!request.TryGetProperty("school", out JsonElement school)) return BadRequest();
- var (userId, _, _, school) = HttpContext.GetAuthTokenInfo();
- 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) and c.pk = 'Exam'");
- /*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} ");
- };
- };
- string periodId = string.Empty;
- if (request.TryGetProperty("period", out JsonElement period) && !string.IsNullOrWhiteSpace($"{period}"))
- {
- stringBuilder.Append($" and (c.period.id = '{period}' or c.period.id = null)");
- periodId = period.GetString();
- }
-
- if (request.TryGetProperty("opt", out JsonElement opt))
- {
- if (opt.GetString().Equals("private"))
- {
- //针对于个人活动获取教师 任教或者助教大名单
- var groupList = await GroupListService.GetTeacherTeachGroupList(_coreAPIHttpService, client, _dingDing, userId, school, periodId);
- List<string> ids = new();
- foreach (var groups in groupList) {
- foreach (var gp in groups.groups) {
- ids.Add(gp.id);
- }
- }
- HashSet<string> strs = new HashSet<string>();
- if (ids.Count > 1)
- {
- foreach (string id in ids)
- {
- strs.Add($" array_contains(c.stuLists,'{id}') or array_contains(c.classes,'{id}')");
- }
- }
- else
- {
- string ssr = ids.Count > 0 ? ids[0] : "";
- strs.Add($" array_contains(c.stuLists,'{ssr}') or array_contains(c.classes,'{ssr}') ");
-
-
- }
- string ss = string.Join(" or ", strs);
- stringBuilder.Append($" and ({ss})");
- stringBuilder.Append($" and c.owner = 'teacher'");
-
- }
- else {
- stringBuilder.Append($" and c.code = 'Exam-{code}' ");
- }
- };
-
- 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").GetItemQueryStreamIteratorSql(queryText: stringBuilder.ToString(), continuationToken: token, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- 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").GetItemQueryStreamIteratorSql(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.Content);
- 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").GetItemQueryStreamIteratorSql(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.Content);
- 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").GetItemQueryStreamIteratorSql(queryText: stringBuilder.ToString(), continuationToken: token, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- 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").GetItemQueryStreamIteratorSql(queryText: stringBuilder.ToString()))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- 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").GetItemQueryStreamIteratorSql(queryText: $"select value(c) from c where c.id = '{id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{code}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- 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("paperAns", out JsonElement paperAns)) return BadRequest();
- if (!request.TryGetProperty("point", out JsonElement point)) 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.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var cJson = await JsonDocument.ParseAsync(response.Content);
- 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").GetItemQueryStreamIteratorSql(
- 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.Content);
- 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").GetItemQueryStreamIteratorSql(
- 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.Content);
- 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").GetItemQueryStreamIteratorSql(
- 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.Content);
- 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").GetItemQueryStreamIteratorSql(
- queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.info.id in ({string.Join(",", ids.Select(o => $"'{o}'"))})",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- 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>());
- }
- }
- }
- examClassResults = examClassResults.Where(c => c.studentIds.Contains(userId)).ToList();
- ExamClassResult classResult = new ExamClassResult();
- /* List<PaperSimple> standerAnswers = new List<PaperSimple>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(
- 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.Content);
- 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 = paperAns.ToObject<List<List<string>>>();
- List<double> points = point.ToObject<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;
- }
- if (s.classCount > info.classes.Count) {
- s.classCount = info.classes.Count;
- }
- });
- }
- result.sum[newIndex] = result.studentScores[newIndex].Sum();
- classResult = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
- var target = info.scope.Equals("school") ? info.school : info.creatorId;
- string _client = "web";
- if (info.source.Equals("1")) {
- _client="hiteach";
- }
- await SystemService.RecordAccumulateData(_azureRedis, _dingDing, new SDK.Models.Dtos.Accumulate { client =_client, count = 1, id = info.id, key = "exam-submit", name = info.name, scope = info.scope, target = target });
- 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}"));
- //}
- }
- }
- //当作答班级数量与实际班级数量一致时才触发结算
- var ansCount = info.subjects.Where(c => c.id.Equals(subjectId)).FirstOrDefault()?.classCount;
- if (ansCount == info.classes.Count)
- {
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(info, id.ToString(), new PartitionKey($"{scode}"));
- }
- 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();
- }
- }
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "student,teacher")]
- [HttpPost("update-ans")]
- public async Task<IActionResult> updateAns(JsonElement request)
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("paperId", out JsonElement paperId)) return BadRequest();
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- if (!request.TryGetProperty("paperAns", out JsonElement paperAns)) return BadRequest();
- if (!request.TryGetProperty("point", out JsonElement point)) return BadRequest();
- if (!request.TryGetProperty("kno", out JsonElement kno)) return BadRequest();
- if (!request.TryGetProperty("multipleRule", out JsonElement multipleRule)) return BadRequest();
- //根据不同评测的类型返回对应的编码
- if (!request.TryGetProperty("scode", out JsonElement scode)) return BadRequest();
- //var (userId, name, picture, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- ExamInfo info = new();
- var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"{scode}"));
- if (response.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var cJson = await JsonDocument.ParseAsync(response.Content);
- info = cJson.ToObject<ExamInfo>();
- }
- else
- {
- return Ok(new { code = 404, msg = "该活动未被找到" });
- }
-
- //if (string.IsNullOrEmpty(userId)) return Ok(new { code = 404, msg = "当前用户信息未找到" });
-
- List<ExamClassResult> examClassResults = new List<ExamClassResult>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(
- queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- 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>());
- }
- }
- }
- //examClassResults = examClassResults.Where(c => c.studentIds.Contains(userId)).ToList(); wo
- ExamClassResult classResult = new();
- List<List<string>> standard = paperAns.ToObject<List<List<string>>>();
- int rule = int.Parse(multipleRule.ToString());
- List<double> points = point.ToObject<List<double>>();
- List<Task<string>> tasks = new List<Task<string>>();
- info.papers.ForEach(c => {
- if (c.id.Equals(paperId.GetString())) {
- c.answers = standard;
- c.point = points;
- }
- });
- foreach (ExamClassResult result in examClassResults)
- {
- int index = 0;
- foreach (var ans in result.ans) {
- if (ans.Count == 0) continue;
- 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 (ac == sc && sc == 1)
- {
- foreach (string right in ans[i])
- {
- if (standard[i].Contains(right.Trim()))
- {
- result.studentScores[index][i] = points[i];
- }
- else
- {
- result.studentScores[index][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[index][i] = points[i];
- }
- else
- {
- result.studentScores[index][i] = 0;
- }
- }
- else
- {
- result.studentScores[index][i] = 0;
- }
- break;
- case 2:
- if (falseCount > 0)
- {
- result.studentScores[index][i] = 0;
- }
- else
- {
- if (ac == sc)
- {
- result.studentScores[index][i] = points[i];
- }
- else
- {
- result.studentScores[index][i] = points[i] / 2;
- }
- }
- break;
- case 3:
- if (falseCount > 0)
- {
- result.studentScores[index][i] = 0;
- }
- else
- {
- if (ac == sc)
- {
- result.studentScores[index][i] = points[i];
- }
- else
- {
- result.studentScores[index][i] = System.Math.Round((double)ac / sc * points[i], 1);
- }
- }
- break;
- case 4:
- if (ac == sc)
- {
- result.studentScores[index][i] = points[i];
- }
- else
- {
- double persent = (double)(sc - 2 * falseCount) / sc;
- if (persent <= 0)
- {
- result.studentScores[index][i] = 0;
- }
- else
- {
- result.studentScores[index][i] = System.Math.Round(persent * points[i], 1);
- }
- }
- break;
- }
- }
- else
- {
- result.studentScores[index][i] = 0;
- }
- }
- }
- }
- }
- result.sum[index] = result.studentScores[index].Sum();
- index++;
- }
- classResult = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
-
- }
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(info, id.ToString(), new PartitionKey($"{scode}"));
-
- return Ok(new { code= 200, info });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/updateAns()\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.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(aresponse.Content);
- art = json.ToObject<ArtEvaluation>();
- var response = await client.GetContainer("TEAMModelOS", "Student").ReadItemStreamAsync(rId, new PartitionKey($"ArtResult-{artId}"));
- if (response.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var json_1 = await JsonDocument.ParseAsync(response.Content);
- 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").GetItemQueryIteratorSql<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").GetItemQueryIteratorSql<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>>>();
- 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.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- //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").GetItemQueryStreamIteratorSql(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.Content);
- 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("schoolId").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}")));
- }
- }
- }
- 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").GetItemQueryStreamIteratorSql(
- 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.Content);
- 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{ex.StackTrace}\n{ex.Message}", 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();
- if (!request.TryGetProperty("startTime", out JsonElement startTime)) return BadRequest();
- try
- {
- /* var data = new
- {
- examCode = 2001717656163218,
- subjects = new List<string> {"语文"}
- };
- var info = await ThirdService.CreateMoofenExamResult(_httpClient, data.ToJsonString().ToObject<JsonElement>(), _dingDing);*/
- // 如果只有学生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($"Exam-{school_code}"));
- List<ExamClassResult> examClassResults = new List<ExamClassResult>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<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}", null, -1, startTime.GetInt64());
- //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 = members.Where(c => c.type == 2).Select(z => z.id).ToList();
- List<string> tIds = members.Where(c => c.type == 1).Select(z => z.id).ToList();
- List<ufo> students = new List<ufo>();
- if (tIds.Any())
- {
- var tmds = ids.Intersect(tIds).ToList();
- delIds.AddRange(ids.Except(tIds).ToList());
- if (tmds.Any()) {
- var content = new StringContent(tmds.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;
- }
- ufos.AddRange(tmdInfos);
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.location}用户转换失败:{_coreAPIHttpService.options.coreUrl}{json}\n ", GroupNames.醍摩豆服務運維群組);
- }
- }
- }
-
- }
- if(sIds.Any())
- {
- var stus = ids.Intersect(sIds).ToList();
- delIds.AddRange(ids.Except(sIds).ToList());
- if (stus.Any()) {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIteratorSql(queryText: $"select distinct c.id,c.name from c where c.id in ({string.Join(",", stus.Select(o => $"'{o}'"))}) and c.pk = 'Base'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{school}") }))
- {
- using var stuJson = await JsonDocument.ParseAsync(item.Content);
- 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);
- }
- }
- }
- ufos.AddRange(students);
- }
- }
- }
- }
- //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").GetItemQueryStreamIteratorSql(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.Content);
- 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").GetItemQueryStreamIteratorSql(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.Content);
- 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").GetItemQueryStreamIteratorSql(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.Content);
- 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").GetItemQueryIteratorSql<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").GetItemQueryIteratorSql<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").GetItemQueryStreamIteratorSql(queryText: queryClassId, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- 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.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var cJson = await JsonDocument.ParseAsync(response.Content);
- info = cJson.ToObject<ExamInfo>();
- }
- /*await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<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").GetItemQueryStreamIteratorSql(queryText: querySubject, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- 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").GetItemQueryStreamIteratorSql(queryText: queryAnswers,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- 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").GetItemQueryIteratorSql<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").GetItemQueryIteratorSql<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, info.school, null,-1,info.startTime);
- 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").GetItemQueryStreamIteratorSql(
- 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.Content);
- 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").GetItemQueryStreamIteratorSql(
- 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.Content);
- 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").GetItemQueryStreamIteratorSql(queryText: query))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- 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").GetItemQueryStreamIteratorSql(queryText: queryClass))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- 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").GetItemQueryStreamIteratorSql(queryText: query))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- 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").GetItemQueryIteratorSql<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").GetItemQueryIteratorSql<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").GetItemQueryIteratorSql<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").GetItemQueryIteratorSql<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").GetItemQueryIteratorSql<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").GetItemQueryIteratorSql<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.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var cJson = await JsonDocument.ParseAsync(cResponse.Content);
- 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.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- 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").GetItemQueryIteratorSql<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").GetItemQueryIteratorSql<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").GetItemQueryIteratorSql<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").GetItemQueryIteratorSql<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.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var schjson = await JsonDocument.ParseAsync(schresponse.Content);
- 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").GetItemQueryIteratorSql<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.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var cJson = await JsonDocument.ParseAsync(cResponse.Content);
- correct = cJson.ToObject<Correct>();
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<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)
- .GetItemQueryIteratorSql<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").GetItemQueryIteratorSql<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.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var schjson = await JsonDocument.ParseAsync(schresponse.Content);
- 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.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var cJson = await JsonDocument.ParseAsync(cResponse.Content);
- 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)
- .GetItemQueryIteratorSql<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").GetItemQueryIteratorSql<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").GetItemQueryStreamIteratorSql(
- 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.Content);
- 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").GetItemQueryStreamIteratorSql(
- 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.Content);
- 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").GetItemQueryStreamIteratorSql(
- 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.Content);
- 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").GetItemQueryStreamIteratorSql(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.Content);
- 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").GetItemQueryStreamIteratorSql(queryText: stringBuilder.ToString(), continuationToken: token, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout, PartitionKey = new PartitionKey($"{pk}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- 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該學生該科目現在錯題數
- HashSet<string> avaliableQidList = new HashSet<string>(); //最終去重後可取得的錯題ID
- 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}";
- };
- Dictionary<string, List<string>> dict = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIteratorSql(queryText: qry, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{pk}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- 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()))
- {
- if (!dict[obj.GetProperty("id").ToString()].Contains(obj.GetProperty("blob").ToString()))
- {
- dict[obj.GetProperty("id").ToString()].Add(obj.GetProperty("blob").ToString());
- }
- }
- else
- {
- dict.Add(obj.GetProperty("id").ToString(), new List<string> { obj.GetProperty("blob").ToString() });
- }
- }
- }
- }
- foreach (var obj in dict)
- {
- if (schCode != null && schCode != "noschoolid")
- {
- string qid = obj.Key;
- List<string> blobs = obj.Value;
- foreach(string blob in blobs)
- {
- if (_azureStorage.GetBlobContainerClient(schCode).GetBlobClient($"{blob}/{qid}.json").Exists())
- {// 去除blob不存在項目
- avaliableQidList.Add(qid);
- }
- }
-
- }
- else if (!string.IsNullOrWhiteSpace(teacherid))
- {
- string qid = obj.Key;
- List<string> blobs = obj.Value;
- foreach (string blob in blobs)
- {
- if (_azureStorage.GetBlobContainerClient(teacherid).GetBlobClient($"{blob}/{qid}.json").Exists())
- {
- avaliableQidList.Add(qid);
- }
- }
- }
- }
- return Ok(new { record, avaliable = avaliableQidList.Count });
- }
- //取得錯題庫新增數
- [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").GetItemQueryStreamIteratorSql(queryText: qry_All, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{maLearnCode}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- 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").GetItemQueryStreamIteratorSql(queryText: qry_before, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{maLearnCode}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- 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").GetItemQueryStreamIteratorSql(queryText: queryTeacher, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- 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.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- 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").GetItemQueryIteratorSql<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.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var cJson = await JsonDocument.ParseAsync(cResponse.Content);
- 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").GetItemQueryStreamIteratorSql(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.Content);
- 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").GetItemQueryStreamIteratorSql(queryText: queryClass, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- 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).Distinct().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").GetItemQueryIteratorSql<ExamInfo>(queryText: queryClass))
- {
- exams.Add(item);
- }
- List<(JsonElement items, List<string> attachments,int qamode)> elements = new();
- if (exams.Count > 0)
- {
- foreach (errorItemInfo itemInfo in errors) {
- ExamInfo info = exams.Where(c => c.id.Equals(itemInfo.activityId)).FirstOrDefault();
- if(info==null) continue; //[Jeff]無法取得評量紀錄報錯bug修正
- 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 {
- List<string> attachments = new();
- if (info.qamode == 1)
- {
- BlobDownloadResult index_json;
- if (info.scope.Equals("school"))
- {
- index_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{blob}/index.json").DownloadContentAsync();
- }
- else
- {
- index_json = await _azureStorage.GetBlobContainerClient($"{info.creatorId}").GetBlobClient($"{blob}/index.json").DownloadContentAsync();
- }
- JsonElement RecordingJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(index_json.Content.ToString()))).RootElement;
- attachments = RecordingJson.GetProperty("attachments").ToObject<List<string>>();
- if (attachments.Count == 0)
- {
- continue;
- }
- }
- 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,attachments,info.qamode));
- 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, attachments, info.qamode));
- }
- }
- } catch (Exception e) {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/get-item\n{e.Message}\n{e.StackTrace}\n{info.id}", GroupNames.成都开发測試群組);
- continue;
- //return BadRequest(new { msg = "blob 文件读取异常" });
- }
-
- }
- }
- else
- {
- var values = elements.Select(c => new {
- c.items,
- c.attachments,
- c.qamode
- });
- return Ok(new { error = values });
- }
- var error = elements.Select(c => new {
- c.items,
- c.attachments,
- c.qamode
- });
- return Ok(new { error });
- }
- }
- 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; }
- }
- }
|