ExamController.cs 282 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162
  1. using Microsoft.Azure.Cosmos;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.Extensions.Options;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Text.Json;
  10. using System.Threading.Tasks;
  11. using TEAMModelOS.Models;
  12. using TEAMModelOS.SDK.Models;
  13. using TEAMModelOS.SDK;
  14. using TEAMModelOS.SDK.DI;
  15. using TEAMModelOS.SDK.Extension;
  16. using TEAMModelOS.SDK.Models.Cosmos.Common;
  17. using TEAMModelOS.SDK.Models.Table;
  18. using Azure.Messaging.ServiceBus;
  19. using Microsoft.Extensions.Configuration;
  20. using TEAMModelOS.Filter;
  21. using TEAMModelOS.SDK.Models.Service;
  22. using TEAMModelOS.SDK.Models.Cosmos;
  23. using Microsoft.AspNetCore.Authorization;
  24. using System.Net.Http;
  25. using Microsoft.AspNetCore.Hosting;
  26. using static TEAMModelOS.SDK.SchoolService;
  27. using Azure.Core;
  28. using Item = TEAMModelOS.SDK.Models.Cosmos.Common.Item;
  29. using TEAMModelOS.SDK.Services;
  30. using TEAMModelOS.SDK.Models.Service.BI;
  31. using MathNet.Numerics.RootFinding;
  32. using TEAMModelOS.SDK.Models.Cosmos.Student;
  33. using ClouDASLibx;
  34. using Azure.Storage.Blobs.Models;
  35. using System.IO;
  36. using TEAMModelOS.SDK.Helper.Common.StringHelper;
  37. using Microsoft.AspNetCore.SignalR;
  38. using static SKIT.FlurlHttpClient.Wechat.TenpayV3.Models.CreateApplyForSubjectApplymentRequest.Types;
  39. using TEAMModelOS.Controllers.Analysis;
  40. using DocumentFormat.OpenXml.Office2010.Excel;
  41. using DocumentFormat.OpenXml.Wordprocessing;
  42. using Microsoft.AspNetCore.Http.HttpResults;
  43. using DocumentFormat.OpenXml.Drawing.Charts;
  44. using TEAMModelOS.Models.Dto;
  45. using FastJSON;
  46. namespace TEAMModelOS.Controllers
  47. {
  48. [ProducesResponseType(StatusCodes.Status200OK)]
  49. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  50. [Route("common/exam")]
  51. [ApiController]
  52. public class ExamController : ControllerBase
  53. {
  54. private readonly AzureCosmosFactory _azureCosmos;
  55. private readonly SnowflakeId _snowflakeId;
  56. private readonly AzureServiceBusFactory _serviceBus;
  57. private readonly DingDing _dingDing;
  58. private readonly Option _option;
  59. private readonly AzureStorageFactory _azureStorage;
  60. private readonly AzureRedisFactory _azureRedis;
  61. private readonly IHttpClientFactory _httpClient;
  62. public IConfiguration _configuration { get; set; }
  63. private readonly CoreAPIHttpService _coreAPIHttpService;
  64. private readonly IWebHostEnvironment _environment;
  65. public ExamController(IWebHostEnvironment environment, CoreAPIHttpService coreAPIHttpService, AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing,
  66. IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, IConfiguration configuration, IHttpClientFactory httpClient)
  67. {
  68. _azureCosmos = azureCosmos;
  69. _serviceBus = serviceBus;
  70. _snowflakeId = snowflakeId;
  71. _dingDing = dingDing;
  72. _option = option?.Value;
  73. _azureStorage = azureStorage;
  74. _azureRedis = azureRedis;
  75. _configuration = configuration;
  76. _coreAPIHttpService = coreAPIHttpService;
  77. _environment = environment;
  78. _httpClient = httpClient;
  79. }
  80. /// <summary>
  81. /// 保存考试信息
  82. /// </summary>
  83. /// <param name="request"></param>
  84. /// <returns></returns>
  85. [ProducesDefaultResponseType]
  86. [AuthToken(Roles = "teacher,admin")]
  87. [HttpPost("save")]
  88. [Authorize(Roles = "IES")]
  89. public async Task<IActionResult> Save(ExamInfo request)
  90. {
  91. try
  92. {
  93. //新增
  94. //string code = request.code;
  95. var client = _azureCosmos.GetCosmosClient();
  96. ExamInfo exam;
  97. string code = request.code;
  98. request.ttl = -1;
  99. request.code = "Exam-" + request.code;
  100. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  101. request.createTime = now;
  102. if (request.startTime <= 0)
  103. {
  104. request.startTime = now;
  105. }
  106. //查询所有学生名单
  107. /* List<string> sids = new List<string>();
  108. //List<Student> students = new List<Student>();
  109. 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}") }))
  110. {
  111. using var json = await JsonDocument.ParseAsync(item.Content);
  112. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  113. {
  114. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  115. while (accounts.MoveNext())
  116. {
  117. JsonElement account = accounts.Current;
  118. sids.Add(account.GetProperty("id").GetString());
  119. }
  120. }
  121. }*/
  122. //int stuCount = 0;
  123. List<(string pId, List<string> gid)> ps = new();
  124. var group = request.groupLists;
  125. if (group.Count > 0)
  126. {
  127. foreach (var keys in group)
  128. {
  129. foreach (KeyValuePair<string, List<string>> pp in keys)
  130. {
  131. ps.Add((pp.Key, pp.Value));
  132. }
  133. }
  134. }
  135. List<string> classes = ExamService.getClasses(request.classes, request.stuLists);
  136. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, classes, request.school, ps);
  137. request.stuCount = tchList.Count;
  138. /*for (int i = 0; i < classes.Count; i++)
  139. {
  140. List<string> ids = new List<string>();
  141. //处理班级人数(公共部分的校本名单)
  142. //List<Student> students = new List<Student>();
  143. 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}") }))
  144. {
  145. using var json = await JsonDocument.ParseAsync(item.Content);
  146. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  147. {
  148. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  149. while (accounts.MoveNext())
  150. {
  151. JsonElement account = accounts.Current;
  152. ids.Add(account.GetProperty("id").GetString());
  153. }
  154. }
  155. }
  156. if (request.scope.Equals("private"))
  157. {
  158. //处理发布对象为自选名单(个人)
  159. List<GroupList> stuLists = new List<GroupList>();
  160. 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") }))
  161. {
  162. stuLists.Add(item);
  163. }
  164. }
  165. else
  166. {
  167. //request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"exam/{request.id}");
  168. //发布对象为自选名单(校本)
  169. List<GroupList> stuLists = new List<GroupList>();
  170. 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}") }))
  171. {
  172. stuLists.Add(item);
  173. }
  174. }
  175. stuCount += ids.Count;
  176. }*/
  177. //var (grade, per) = await ThirdService.GetGradeAsync(client, request);
  178. /*var data = new
  179. {
  180. examName = request.name,
  181. examCategory = 1,
  182. //grade = int.Parse(grade),
  183. grade = 7,
  184. term = 2,
  185. examType = "单元测试",
  186. examDate = request.startTime,
  187. schId = 1,
  188. boeId = "",
  189. subjects = request.subjects.Select(c => c.name).ToList()
  190. };*/
  191. if (string.IsNullOrEmpty(request.id))
  192. {
  193. request.id = Guid.NewGuid().ToString();
  194. if (request.startTime > now)
  195. {
  196. request.progress = "pending";
  197. }
  198. else
  199. {
  200. request.progress = "going";
  201. }
  202. var messageBlob = new ServiceBusMessage();
  203. if (request.scope.Equals("school"))
  204. {
  205. request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"exam/{request.id}");
  206. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = request.school }, _serviceBus, _configuration, _azureRedis);
  207. }
  208. else
  209. {
  210. request.size = await _azureStorage.GetBlobContainerClient(request.creatorId).GetBlobsSize($"exam/{request.id}");
  211. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = request.creatorId }, _serviceBus, _configuration, _azureRedis);
  212. }
  213. int n = 0;
  214. List<string> sheetIds = new List<string>();
  215. foreach (PaperSimple simple in request.papers)
  216. {
  217. simple.blob = $"/exam/{request.id}/paper/{request.subjects[n].id}";
  218. n++;
  219. simple.sheet = null;
  220. }
  221. //string moofenCode = await ThirdService.CreateMoofenExam(_httpClient, data.ToJsonString().ToObject<JsonElement>(),_dingDing);
  222. //request.moofenCode = moofenCode;
  223. exam = await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(request, new PartitionKey($"{request.code}"));
  224. await BIStats.SetTypeAddStats(client, _dingDing, exam.school, "Exam", 1);//BI统计增/减量
  225. //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" });
  226. }
  227. else
  228. {
  229. var response = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(request.id, new PartitionKey($"{request.code}"));
  230. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  231. {
  232. using var json = await JsonDocument.ParseAsync(response.Content);
  233. ExamInfo info = json.ToObject<ExamInfo>();
  234. if (info.progress.Equals("going"))
  235. {
  236. //exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(request, request.id, new PartitionKey($"{request.code}"));
  237. return Ok(new { v = "活动正在进行中,无法修改", code = 200 });
  238. }
  239. var messageBlob = new ServiceBusMessage();
  240. if (request.scope.Equals("school"))
  241. {
  242. request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"exam/{request.id}");
  243. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = $"exam", name = request.school }, _serviceBus, _configuration, _azureRedis);
  244. }
  245. else
  246. {
  247. request.size = await _azureStorage.GetBlobContainerClient(request.creatorId).GetBlobsSize($"exam/{request.id}");
  248. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = $"exam", name = request.creatorId }, _serviceBus, _configuration, _azureRedis);
  249. }
  250. request.progress = info.progress;
  251. int n = 0;
  252. foreach (PaperSimple simple in request.papers)
  253. {
  254. simple.blob = "/exam/" + request.id + "/paper/" + request.subjects[n].id;
  255. n++;
  256. }
  257. exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(request, request.id, new PartitionKey($"{request.code}"));
  258. }
  259. else
  260. {
  261. if (request.startTime > now)
  262. {
  263. request.progress = "pending";
  264. }
  265. else
  266. {
  267. request.progress = "going";
  268. }
  269. var messageBlob = new ServiceBusMessage();
  270. if (request.scope.Equals("school"))
  271. {
  272. request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"exam/{request.id}");
  273. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = request.school }, _serviceBus, _configuration, _azureRedis);
  274. }
  275. else
  276. {
  277. request.size = await _azureStorage.GetBlobContainerClient(request.creatorId).GetBlobsSize($"exam/{request.id}");
  278. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = request.creatorId }, _serviceBus, _configuration, _azureRedis);
  279. }
  280. int n = 0;
  281. List<string> sheetIds = new List<string>();
  282. foreach (PaperSimple simple in request.papers)
  283. {
  284. if (!string.IsNullOrEmpty(simple.subjectId))
  285. {
  286. simple.blob = $"/exam/{request.id}/paper/{simple.subjectId}/{simple.id}";
  287. }
  288. else
  289. {
  290. simple.blob = $"/exam/{request.id}/paper/{request.subjects[n].id}";
  291. n++;
  292. }
  293. simple.sheet = null;
  294. }
  295. //string moofenCode = await ThirdService.CreateMoofenExam(_httpClient, data.ToJsonString().ToObject<JsonElement>());
  296. exam = await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(request, new PartitionKey($"{request.code}"));
  297. await BIStats.SetTypeAddStats(client, _dingDing, exam.school, "Exam", 1);//BI统计增/减量
  298. }
  299. }
  300. return Ok(new { exam });
  301. }
  302. catch (Exception ex)
  303. {
  304. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/save()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  305. return BadRequest();
  306. }
  307. }
  308. /* [ProducesDefaultResponseType]
  309. //[AuthToken(Roles = "teacher,admin")]
  310. [HttpPost("read-score")]
  311. // [Authorize(Roles = "IES")]
  312. public async Task<IActionResult> getAverage(JsonElement request) {
  313. var client = _azureCosmos.GetCosmosClient();
  314. var grades = ExamService.getGradeScore(_coreAPIHttpService,_dingDing,client,2021,"二年级", "463db08d-cbe7-48a0-a81a-fc39b3c1fep1","hbcn", 1688349974000, 1693706774000);
  315. return Ok(grades);
  316. }*/
  317. /// <summary>
  318. /// 保存考试信息
  319. /// </summary>
  320. /// <param name="request"></param>
  321. /// <returns></returns>
  322. [ProducesDefaultResponseType]
  323. [AuthToken(Roles = "teacher,admin")]
  324. [HttpPost("update-end-time")]
  325. [Authorize(Roles = "IES")]
  326. public async Task<IActionResult> updateTime(JsonElement request)
  327. {
  328. try
  329. {
  330. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  331. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  332. var client = _azureCosmos.GetCosmosClient();
  333. var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.GetString(), new PartitionKey($"Exam-{code}"));
  334. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  335. {
  336. using var json = await JsonDocument.ParseAsync(response.Content);
  337. ExamInfo exam = json.ToObject<ExamInfo>();
  338. if (request.TryGetProperty("time", out JsonElement time))
  339. {
  340. exam.endTime = time.GetInt64();
  341. }
  342. if (request.TryGetProperty("name", out JsonElement name))
  343. {
  344. exam.name = name.GetString();
  345. }
  346. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
  347. }
  348. return Ok(new { code = 200 });
  349. }
  350. catch (Exception e)
  351. {
  352. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/update-end-time()\n{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  353. return BadRequest();
  354. }
  355. }
  356. [ProducesDefaultResponseType]
  357. //[AuthToken(Roles = "teacher,admin")]
  358. [HttpPost("get-exam-point")]
  359. //[Authorize(Roles = "IES")]
  360. public async Task<IActionResult> getExamPoint(JsonElement request)
  361. {
  362. try
  363. {
  364. if (!request.TryGetProperty("classIds", out JsonElement classId)) return BadRequest();
  365. if (!request.TryGetProperty("school", out JsonElement code)) return BadRequest();
  366. if (!request.TryGetProperty("periodId", out JsonElement periodId)) return BadRequest();
  367. if (!request.TryGetProperty("semesterId", out JsonElement semesterId)) return BadRequest();
  368. if (!request.TryGetProperty("studyYear", out JsonElement studyYear)) return BadRequest();
  369. if (!request.TryGetProperty("studentYear", out JsonElement studentYear)) return BadRequest();
  370. var client = _azureCosmos.GetCosmosClient();
  371. List<string> ids = [];
  372. List<string> clds = classId.ToObject<List<string>>().ToList();
  373. List<string> clas = classId.ToObject<List<string>>().ToList();
  374. List<ExamSubject> subs = [];
  375. List<PaperSimple> paperSimples = [];
  376. List<(string id,string type)> source = [];
  377. List<(string id, double score)> averages = [];
  378. //获取学校基本信息
  379. School schoolBase = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(code.GetString(), new PartitionKey("Base"));
  380. var period = schoolBase.period.Find(x => x.id.Equals($"{periodId}"));
  381. var semesterData = SchoolService.GetSemester(period, time: SchoolService.GetOpensByStudyYearAndSemester(period.semesters, studyYear.GetInt32(), $"{semesterId}"));
  382. var sem = period.semesters.Find(x => x.id.Equals($"{semesterId}"));
  383. if (clds.Count == 0) {
  384. List<Class> classes = new();
  385. string sqlClassIds = $" select value(c) from c where c.periodId = '{periodId}'";
  386. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).
  387. GetItemQueryIteratorSql<Class>(queryText: sqlClassIds, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Class-{code}") }))
  388. {
  389. classes.Add(item);
  390. }
  391. foreach (var cla in classes)
  392. {
  393. if (cla.year == studentYear.GetInt32())
  394. {
  395. clds.Add(cla.id);
  396. }
  397. }
  398. if (clds.Count == 0)
  399. {
  400. return Ok(new { orderScore = Array.Empty<string>(), typeCount = Array.Empty<string>(), gradeRate = Array.Empty<string>(), pCount = 0, gradeExamAverageScore = 0, point = 0, code = 200 });
  401. }
  402. }
  403. //处理班级ID
  404. HashSet<string> strs = new HashSet<string>();
  405. if (clds.Count > 1)
  406. {
  407. foreach (string str in clds)
  408. {
  409. strs.Add($"array_contains(c.classes,'{str}')");
  410. }
  411. }
  412. else
  413. {
  414. string ssr = clds.Count > 0 ? clds[0] : "";
  415. strs.Add($"array_contains(c.classes,'{ssr}')");
  416. }
  417. string classInfos = string.Join(" or ", strs);
  418. (List<RMember> members, List<RGroupList> groups) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, clds, $"{code}");
  419. var queryExam = $"select c.id,c.subjects,c.source,c.average,c.papers from c where c.period.id = '{periodId}' and ({classInfos}) " +
  420. $"and c.qamode <> 2 and c.progress = 'finish' and c.scope = 'school' and c.startTime > {semesterData.date.ToUnixTimeMilliseconds()} and c.startTime < {semesterData.nextSemester.ToUnixTimeMilliseconds()} ";
  421. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: queryExam, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Exam-{code}") }))
  422. {
  423. using var json = await JsonDocument.ParseAsync(item.Content);
  424. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  425. {
  426. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  427. while (accounts.MoveNext())
  428. {
  429. JsonElement account = accounts.Current;
  430. ids.Add(account.GetProperty("id").GetString());
  431. if (account.TryGetProperty("subjects", out JsonElement subject))
  432. {
  433. subs.AddRange(subject.ToObject<List<ExamSubject>>());
  434. }
  435. if (account.TryGetProperty("papers", out JsonElement papers))
  436. {
  437. paperSimples.AddRange(papers.ToObject<List<PaperSimple>>());
  438. }
  439. source.Add((account.GetProperty("id").GetString(), account.GetProperty("source").GetString()));
  440. averages.Add((account.GetProperty("id").GetString(), account.GetProperty("average").GetDouble()));
  441. }
  442. }
  443. }
  444. subs = subs.Where((x, i) => subs.FindIndex(z => z.id == x.id) == i).ToList();
  445. List<ExamClassResult> classResults = new();
  446. List<ExamClassResult> results = new();
  447. var point = paperSimples.Count > 0 ? paperSimples.FirstOrDefault().point.Sum() : 0;
  448. var gradeExamAverageScore = averages.Count >0 ? Math.Round(averages.Select(c => c.score).Sum() / averages.Count,2) : 0;
  449. if (clas.Count == 0)
  450. {
  451. var queryClass = $"select value(c) from c where c.examId in ({string.Join(",", ids.Select(o => $"'{o}'"))})";
  452. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamClassResult>(queryText: queryClass, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
  453. {
  454. results.Add(item);
  455. }
  456. }
  457. else {
  458. var queryClass = $"select value(c) from c where c.info.id = '{clds[0]}'and c.examId in ({string.Join(",", ids.Select(o => $"'{o}'"))})";
  459. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamClassResult>(queryText: queryClass, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
  460. {
  461. classResults.Add(item);
  462. }
  463. }
  464. var typeCount = source.GroupBy(x => x.type).Select(z => new
  465. {
  466. z.Key,
  467. count = z.ToList().Count
  468. });
  469. //计算几次合并
  470. var examScore = classResults.GroupBy(c => c.subjectId).Select(x => new
  471. {
  472. x.Key,
  473. cc = x.ToList().Count,
  474. students = x.ToList().SelectMany(z => z.studentIds).Distinct().ToList(),
  475. classRate = x.ToList().Count > 0 ? Math.Round(x.ToList().Select(z => z.average).Sum() / x.ToList().Count,2) : 0
  476. //score = x.ToList().Select(k => k.sum).Aggregate((current, next) => current.Zip(next, (a, b) => a + b).ToList()),
  477. //gRate = Math.Round( x.ToList().SelectMany(k => k.sum).Sum() / x.ToList().Count / members.Count, 2)
  478. });
  479. List<(string sub, List<(string id, double score)> subScore,int cc,double average)> stuScore = [];
  480. foreach (var es in examScore) {
  481. List<(string id, double score)> subScore = [];
  482. foreach (var sId in es.students) {
  483. int count = classResults.Where(c => c.subjectId.Equals(es.Key) && c.studentIds.Contains(sId)).ToList().Count;
  484. var totalScore = classResults.Where(c => c.subjectId.Equals(es.Key) && c.studentIds.Contains(sId)).ToList().Select(z => z.sum[z.studentIds.IndexOf(sId)]).Sum();
  485. subScore.Add((sId, Math.Round(totalScore / count,2)));
  486. }
  487. stuScore.Add((es.Key, subScore,es.cc,es.classRate));
  488. }
  489. var examAllScore = results.GroupBy(c => c.subjectId).Select(x => new
  490. {
  491. x.Key,
  492. cc = x.ToList().Count,
  493. students = x.ToList().SelectMany(z => z.studentIds).Distinct().ToList(),
  494. classRate = x.ToList().GroupBy(z => z.info.id).Select(m => new {
  495. classId = m.Key,
  496. className = groups.Where(k => k.id.Equals(m.Key)).FirstOrDefault()?.name,
  497. rate = point > 0 ? Math.Round(m.ToList().Select(k => k.average).Sum() / m.ToList().Count / point,4) :0
  498. })
  499. //score = x.ToList().Select(k => k.sum).Aggregate((current, next) => current.Zip(next, (a, b) => a + b).ToList()),
  500. //gRate = Math.Round(x.ToList().SelectMany(k => k.sum).Sum() / x.ToList().Count / members.Count, 2)
  501. }) ;
  502. var gradeRate = examAllScore.Select(x => new
  503. {
  504. subjectId = x.Key,
  505. subjectName = subs.Where(z => z.id.Equals(x.Key)).FirstOrDefault()?.name,
  506. x.classRate
  507. //x.gRate
  508. });
  509. if (request.TryGetProperty("studentId", out JsonElement studentId) && !string.IsNullOrWhiteSpace($"{studentId}"))
  510. {
  511. var orderScore = stuScore.Select(x => new
  512. {
  513. subjectId = x.sub,
  514. subjectName = subs.Where(z => z.id.Equals(x.sub)).FirstOrDefault()?.name,
  515. classRate = point > 0 ? Math.Round(x.average / point, 4) : 0,
  516. rank = x.subScore.OrderByDescending(x => x.score).Select(z => z.id).ToList().IndexOf(studentId.GetString()) + 1,
  517. stuRate = x.subScore.OrderByDescending(x => x.score).Select(z => new
  518. {
  519. z.id,
  520. members.Where(s => s.id.Equals(z.id)).FirstOrDefault()?.name,
  521. rate = point > 0 ? Math.Round(z.score / point, 4) :0
  522. }).ToList().Take(10),
  523. sper = x.subScore.Where(c => c.id.Equals(studentId.GetString())).Select(z => new
  524. {
  525. z.id,
  526. members.Where(s => s.id.Equals(z.id)).FirstOrDefault()?.name,
  527. rate = point>0 ? Math.Round(z.score / point, 4) :0
  528. })
  529. });
  530. return Ok(new { orderScore, typeCount, gradeRate, pCount = members.Count, gradeExamAverageScore, point, code = 200 });
  531. }
  532. else
  533. {
  534. var orderScore = stuScore.Select(x => new
  535. {
  536. subjectId = x.sub,
  537. subjectName = subs.Where(z => z.id.Equals(x.sub)).FirstOrDefault()?.name,
  538. classRate = point > 0 ? Math.Round(x.average / point,4) : 0,
  539. stuRate = x.subScore.OrderByDescending(x => x.score).Select(z => new
  540. {
  541. z.id,
  542. members.Where(s => s.id.Equals(z.id)).FirstOrDefault()?.name,
  543. rate = point > 0 ? Math.Round(z.score / point, 4) : 0
  544. }).ToList().Take(10)
  545. });
  546. return Ok(new { orderScore, typeCount, gradeRate, pCount = members.Count, gradeExamAverageScore, point, code = 200 });
  547. }
  548. }
  549. catch (Exception e)
  550. {
  551. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/get-exam-point()\n{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  552. return BadRequest();
  553. }
  554. }
  555. //TODO blob 批量删除
  556. /// <summary>
  557. /// 删除
  558. /// </summary>
  559. /// <param name="request"></param>
  560. /// <returns></returns>
  561. [ProducesDefaultResponseType]
  562. [AuthToken(Roles = "teacher,admin")]
  563. [HttpPost("delete")]
  564. [Authorize(Roles = "IES")]
  565. public async Task<IActionResult> Delete(JsonElement request)
  566. {
  567. /* ResponseBuilder builder = ResponseBuilder.custom();
  568. IdPk items = await _azureCosmos.DeleteAsync<ExamInfo>(request.id, request.pk);
  569. await _azureCosmos.DeleteAll<Paper>(new Dictionary<string, object>() { { "code", request.id } });
  570. return builder.Data(items).build();*/
  571. var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
  572. try
  573. {
  574. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  575. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  576. if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  577. var client = _azureCosmos.GetCosmosClient();
  578. ExamInfo exam;
  579. var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.GetString(), new PartitionKey($"Exam-{code}"));
  580. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  581. {
  582. using var jsonExam = await JsonDocument.ParseAsync(response.Content);
  583. exam = jsonExam.ToObject<ExamInfo>();
  584. bool flag = false;
  585. //必须是本人或者这个学校的管理者才能删除
  586. if (exam.creatorId == userid)
  587. {
  588. flag = true;
  589. }
  590. else
  591. {
  592. if (exam.scope == "school" && exam.school.Equals(school))
  593. {
  594. flag = true;
  595. }
  596. }
  597. if (flag)
  598. {
  599. exam.status = 404;
  600. exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
  601. //string school_code = code.ToString().Substring(typeof(ExamClassResult).Name.Length + 1);
  602. //var response = await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Exam-{code}"));
  603. //删除blob 相关资料
  604. await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, code.ToString(), new List<string> { $"exam/{id}" });
  605. //通知评测删除信息
  606. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "delete", root = $"exam", name = $"{code}" }, _serviceBus, _configuration, _azureRedis);
  607. //删除阅卷配置
  608. var cresponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Correct-{code}"));
  609. if (cresponse.StatusCode == System.Net.HttpStatusCode.OK)
  610. {
  611. using var json = await JsonDocument.ParseAsync(cresponse.Content);
  612. Correct correct = json.ToObject<Correct>();
  613. if (correct.subs.IsNotEmpty())
  614. {
  615. foreach (var sub in correct.subs)
  616. {
  617. //List<string> correctIds = new List<string>();
  618. if (sub.markers.IsNotEmpty())
  619. {
  620. foreach (var marker in sub.markers)
  621. {
  622. await ExamService.deleteAsync(client, id.GetString(), marker.id);
  623. }
  624. }
  625. if (sub.err.Count > 0)
  626. {
  627. foreach (var tId in sub.err)
  628. {
  629. await ExamService.deleteAsync(client, id.GetString(), tId);
  630. }
  631. }
  632. if (sub.arb.Count > 0)
  633. {
  634. foreach (var tId in sub.arb)
  635. {
  636. await ExamService.deleteAsync(client, id.GetString(), tId);
  637. }
  638. }
  639. }
  640. }
  641. await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(id.GetString(), new PartitionKey($"Correct-{code}"));
  642. }
  643. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  644. 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}") }))
  645. {
  646. examClassResults.Add(item);
  647. }
  648. List<string> resultIds = new List<string>();
  649. 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}") }))
  650. {
  651. using var json = await JsonDocument.ParseAsync(item.Content);
  652. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  653. {
  654. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  655. while (accounts.MoveNext())
  656. {
  657. JsonElement account = accounts.Current;
  658. resultIds.Add(account.GetProperty("id").GetString());
  659. }
  660. }
  661. }
  662. foreach (ExamClassResult classResult in examClassResults)
  663. {
  664. await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(classResult.id, new PartitionKey($"ExamClassResult-{code}"));
  665. }
  666. await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemsStreamAsync(resultIds, $"ExamResult-{id}");
  667. }
  668. return Ok(new { id });
  669. }
  670. else
  671. {
  672. return NotFound(new { msg = "未找到对应内容" });
  673. }
  674. }
  675. catch (Exception e)
  676. {
  677. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/delete()\n{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  678. return BadRequest();
  679. }
  680. }
  681. /// <summary>
  682. /// 查询考试信息
  683. /// </summary>
  684. /// <param name="request"></param>
  685. /// <returns></returns>
  686. [ProducesDefaultResponseType]
  687. [Authorize(Roles = "IES")]
  688. [AuthToken(Roles = "teacher,admin")]
  689. [HttpPost("find")]
  690. public async Task<IActionResult> Find(JsonElement request)
  691. {
  692. try
  693. {
  694. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  695. //if (request.TryGetProperty("period", out JsonElement period)) return BadRequest();
  696. var client = _azureCosmos.GetCosmosClient();
  697. //if (!request.TryGetProperty("userId", out JsonElement userId)) return BadRequest();
  698. //if (!request.TryGetProperty("school", out JsonElement school)) return BadRequest();
  699. var (userId, _, _, school) = HttpContext.GetAuthTokenInfo();
  700. 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, c.jointExamId, c.jointVisiable from c where (c.status<>404 or IS_DEFINED(c.status) = false) and c.pk = 'Exam'");
  701. /*if (request.TryGetProperty("classIds", out JsonElement classIds))
  702. {
  703. List<string> ids = classIds.ToObject<List<string>>();
  704. HashSet<string> strs = new HashSet<string>();
  705. if (ids.Count > 1)
  706. {
  707. foreach (string id in ids)
  708. {
  709. strs.Add($"array_contains(c.classes,'{id}')");
  710. }
  711. }
  712. else
  713. {
  714. string ssr = ids.Count > 0 ? ids[0] : "";
  715. strs.Add($"array_contains(c.classes,'{ssr}')");
  716. }
  717. string ss = string.Join(" or ", strs);
  718. stringBuilder.Append($" and {ss}");
  719. };*/
  720. //开始时间,
  721. if (request.TryGetProperty("stime", out JsonElement stime))
  722. {
  723. if (long.TryParse($"{stime}", out long data))
  724. {
  725. stringBuilder.Append($" and c.createTime >= {data} ");
  726. };
  727. };
  728. //默认当前时间
  729. if (request.TryGetProperty("etime", out JsonElement etime))
  730. {
  731. if (long.TryParse($"{etime}", out long data))
  732. {
  733. stringBuilder.Append($" and c.createTime <= {data} ");
  734. };
  735. };
  736. string periodId = string.Empty;
  737. if (request.TryGetProperty("period", out JsonElement period) && !string.IsNullOrWhiteSpace($"{period}"))
  738. {
  739. stringBuilder.Append($" and (c.period.id = '{period}' or c.period.id = null)");
  740. periodId = period.GetString();
  741. }
  742. if (request.TryGetProperty("opt", out JsonElement opt))
  743. {
  744. if (opt.GetString().Equals("private"))
  745. {
  746. //针对于个人活动获取教师 任教或者助教大名单
  747. var groupList = await GroupListService.GetTeacherTeachGroupList(_coreAPIHttpService, client, _dingDing, userId, school, periodId);
  748. List<string> ids = new();
  749. foreach (var groups in groupList)
  750. {
  751. foreach (var gp in groups.groups)
  752. {
  753. ids.Add(gp.id);
  754. }
  755. }
  756. HashSet<string> strs = new HashSet<string>();
  757. if (ids.Count > 1)
  758. {
  759. foreach (string id in ids)
  760. {
  761. strs.Add($" array_contains(c.stuLists,'{id}') or array_contains(c.classes,'{id}')");
  762. }
  763. }
  764. else
  765. {
  766. string ssr = ids.Count > 0 ? ids[0] : "";
  767. strs.Add($" array_contains(c.stuLists,'{ssr}') or array_contains(c.classes,'{ssr}') ");
  768. }
  769. string ss = string.Join(" or ", strs);
  770. stringBuilder.Append($" and ({ss})");
  771. stringBuilder.Append($" and c.owner = 'teacher'");
  772. }
  773. else
  774. {
  775. stringBuilder.Append($" and c.code = 'Exam-{code}' ");
  776. }
  777. };
  778. if (request.TryGetProperty("name", out JsonElement name) && !string.IsNullOrWhiteSpace($"{name}"))
  779. {
  780. stringBuilder.Append($" and Contains( c.name , '{name}') = true ");
  781. }
  782. if (request.TryGetProperty("progress", out JsonElement progress) && !string.IsNullOrWhiteSpace($"{progress}"))
  783. {
  784. stringBuilder.Append($" and c.progress = '{progress}' ");
  785. }
  786. if (request.TryGetProperty("source", out JsonElement source) && !string.IsNullOrWhiteSpace($"{source}"))
  787. {
  788. stringBuilder.Append($" and c.source = '{source}' ");
  789. }
  790. stringBuilder.Append("order by c.createTime desc");
  791. //string token = null;
  792. string token = default;
  793. //默认不指定返回大小
  794. int? topcout = null;
  795. if (request.TryGetProperty("count", out JsonElement jcount))
  796. {
  797. if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
  798. {
  799. topcout = data;
  800. }
  801. }
  802. //是否需要进行分页查询,默认不分页
  803. bool iscontinuation = false;
  804. if (topcout != null && topcout.Value > 0)
  805. {
  806. iscontinuation = true;
  807. }
  808. //如果指定了返回大小
  809. if (request.TryGetProperty("token", out JsonElement token_1))
  810. {
  811. if (!token_1.ValueKind.Equals(JsonValueKind.Null) && token_1.ValueKind.Equals(JsonValueKind.String))
  812. {
  813. token = token_1.GetString();
  814. }
  815. }
  816. List<ExamInfo> examInfo = new List<ExamInfo>();
  817. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: stringBuilder.ToString(), continuationToken: token, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout }))
  818. {
  819. using var json = await JsonDocument.ParseAsync(item.Content);
  820. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  821. {
  822. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  823. {
  824. //obj.TryGetProperty("progress", out JsonElement progress);
  825. examInfo.Add(obj.ToObject<ExamInfo>());
  826. }
  827. }
  828. if (iscontinuation)
  829. {
  830. token = item.ContinuationToken;
  831. break;
  832. }
  833. }
  834. return Ok(new { examInfo, token = token });
  835. }
  836. catch (Exception e)
  837. {
  838. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find()\n{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
  839. return BadRequest();
  840. }
  841. }
  842. [ProducesDefaultResponseType]
  843. [AuthToken(Roles = "teacher,admin,student")]
  844. #if !DEBUG
  845. [Authorize(Roles = "IES")]
  846. #endif
  847. [HttpPost("find-by-analysis")]
  848. public async Task<IActionResult> FindByAnalysis(JsonElement request)
  849. {
  850. try
  851. {
  852. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  853. var client = _azureCosmos.GetCosmosClient();
  854. var table = _azureStorage.GetCloudTableClient().GetTableReference("SchoolYear");
  855. List<SchoolYear> years = await table.FindListByDict<SchoolYear>(new Dictionary<string, object>() { { "RowKey", code }, { "PartitionKey", "Exam" } });
  856. int year = 0;
  857. if (years.Count > 0)
  858. {
  859. year = years[0].year;
  860. if (year == 1970)
  861. {
  862. long ct = 0;
  863. 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}") }))
  864. {
  865. using var json = await JsonDocument.ParseAsync(item.Content);
  866. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  867. {
  868. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  869. while (accounts.MoveNext())
  870. {
  871. JsonElement account = accounts.Current;
  872. ct = account.GetProperty("createTime").GetInt64();
  873. }
  874. }
  875. }
  876. year = ct == 0 ? DateTimeOffset.UtcNow.Year : DateTimeOffset.FromUnixTimeMilliseconds(ct).Year;
  877. years[0].year = year;
  878. await table.SaveOrUpdate<SchoolYear>(years[0]);
  879. }
  880. }
  881. else
  882. {
  883. long ct = 0;
  884. 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}") }))
  885. {
  886. using var json = await JsonDocument.ParseAsync(item.Content);
  887. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  888. {
  889. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  890. while (accounts.MoveNext())
  891. {
  892. JsonElement account = accounts.Current;
  893. ct = account.GetProperty("createTime").GetInt64();
  894. }
  895. }
  896. }
  897. year = ct == 0 ? DateTimeOffset.UtcNow.Year : DateTimeOffset.FromUnixTimeMilliseconds(ct).Year;
  898. SchoolYear sy = new()
  899. {
  900. RowKey = code.ToString(),
  901. PartitionKey = "Exam",
  902. year = year
  903. };
  904. await table.Save<SchoolYear>(sy);
  905. }
  906. string sub = string.Empty;
  907. string subject = string.Empty;
  908. if (request.TryGetProperty("subjectId", out JsonElement subjectId) && !string.IsNullOrWhiteSpace($"{subjectId}"))
  909. {
  910. sub = $" join A0 in c.subjects ";
  911. subject = $" and A0.id = '{subjectId}'";
  912. }
  913. string grade = string.Empty;
  914. string grades = string.Empty;
  915. if (request.TryGetProperty("grades", out JsonElement gs) && !string.IsNullOrWhiteSpace($"{gs}"))
  916. {
  917. grade = $" join A1 in c.grades ";
  918. grades = $" and A1.id = '{gs}'";
  919. }
  920. 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}" +
  921. $"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}");
  922. if (request.TryGetProperty("period", out JsonElement period) && !string.IsNullOrWhiteSpace($"{period}"))
  923. {
  924. stringBuilder.Append($" and c.period.id = '{period}' ");
  925. }
  926. if (request.TryGetProperty("owner", out JsonElement owner) && !string.IsNullOrWhiteSpace($"{owner}"))
  927. {
  928. stringBuilder.Append($" and c.owner= '{owner}' ");
  929. }
  930. if (request.TryGetProperty("year", out JsonElement yy) && !string.IsNullOrWhiteSpace($"{yy}"))
  931. {
  932. int end = yy.GetInt32() + 1;
  933. long stime = DateTimeOffset.Parse($"{yy.GetInt32()}-1-1").ToUnixTimeMilliseconds();
  934. long etime = DateTimeOffset.Parse($"{end}-1-1").ToUnixTimeMilliseconds();
  935. stringBuilder.Append($" and c.startTime >= {stime} and c.startTime < {etime} ");
  936. }
  937. if (request.TryGetProperty("startTime", out JsonElement startTime) && !string.IsNullOrWhiteSpace($"{startTime}"))
  938. {
  939. stringBuilder.Append($" and c.startTime >= {startTime} ");
  940. }
  941. if (request.TryGetProperty("endTime", out JsonElement endTime) && !string.IsNullOrWhiteSpace($"{endTime}"))
  942. {
  943. stringBuilder.Append($" and c.startTime < {endTime} ");
  944. }
  945. if (request.TryGetProperty("name", out JsonElement name) && !string.IsNullOrWhiteSpace($"{name}"))
  946. {
  947. stringBuilder.Append($" and Contains( c.name , '{name}') = true ");
  948. }
  949. if (request.TryGetProperty("examType", out JsonElement examType) && !string.IsNullOrWhiteSpace($"{examType}"))
  950. {
  951. stringBuilder.Append($" and c.examType.id = '{examType}' ");
  952. }
  953. if (request.TryGetProperty("progress", out JsonElement progress) && !string.IsNullOrWhiteSpace($"{progress}"))
  954. {
  955. stringBuilder.Append($" and c.progress = '{progress}' ");
  956. }
  957. if (request.TryGetProperty("source", out JsonElement source) && !string.IsNullOrWhiteSpace($"{source}"))
  958. {
  959. stringBuilder.Append($" and c.source = '{source}' ");
  960. }
  961. if (request.TryGetProperty("creatorId", out JsonElement creatorId) && !string.IsNullOrWhiteSpace($"{creatorId}"))
  962. {
  963. stringBuilder.Append($" and c.creatorId = '{creatorId}' ");
  964. }
  965. stringBuilder.Append("order by c.createTime desc");
  966. string token = default;
  967. //是否需要进行分页查询,默认不分页
  968. bool iscontinuation = false;
  969. if (request.TryGetProperty("token", out JsonElement token_1))
  970. {
  971. token = token_1.GetString();
  972. };
  973. //默认不指定返回大小
  974. int? topcout = null;
  975. if (request.TryGetProperty("count", out JsonElement jcount))
  976. {
  977. if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
  978. {
  979. topcout = data;
  980. }
  981. }
  982. if (topcout != null && topcout.Value > 0)
  983. {
  984. iscontinuation = true;
  985. }
  986. List<ExamInfo> examInfo = new List<ExamInfo>();
  987. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: stringBuilder.ToString(), continuationToken: token, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout }))
  988. {
  989. using var json = await JsonDocument.ParseAsync(item.Content);
  990. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  991. {
  992. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  993. {
  994. //obj.TryGetProperty("progress", out JsonElement progress);
  995. examInfo.Add(obj.ToObject<ExamInfo>());
  996. }
  997. }
  998. if (iscontinuation)
  999. {
  1000. token = item.ContinuationToken;
  1001. break;
  1002. }
  1003. }
  1004. List<ExamInfo> exams = new List<ExamInfo>();
  1005. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: stringBuilder.ToString()))
  1006. {
  1007. using var json = await JsonDocument.ParseAsync(item.Content);
  1008. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1009. {
  1010. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1011. {
  1012. exams.Add(obj.ToObject<ExamInfo>());
  1013. }
  1014. }
  1015. }
  1016. School schoolBase = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(code.GetString(), new PartitionKey("Base"));
  1017. var periodInfo = schoolBase.period.Find(x => x.id.Equals($"{period}"));
  1018. List<GroupListDto> allClasses = new List<GroupListDto>();
  1019. //获取该学校某学段全部行政班级
  1020. allClasses = await GroupListService.GetGroupListByType(_azureCosmos.GetCosmosClient(), "class", schoolBase, periodInfo, 0);
  1021. var classData = allClasses.Select(x => new {
  1022. x.id,
  1023. x.name
  1024. });
  1025. 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();
  1026. return Ok(new { examInfo, token, year, count = exams.Count, groups, classData });
  1027. }
  1028. catch (Exception e)
  1029. {
  1030. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-by-analysis()\n{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1031. return BadRequest();
  1032. }
  1033. }
  1034. [ProducesDefaultResponseType]
  1035. [Authorize(Roles = "IES")]
  1036. [AuthToken(Roles = "teacher,admin")]
  1037. [HttpPost("find-summary")]
  1038. public async Task<IActionResult> FindSummary(JsonElement request)
  1039. {
  1040. try
  1041. {
  1042. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1043. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1044. var client = _azureCosmos.GetCosmosClient();
  1045. List<ExamInfoEx> examInfo = new List<ExamInfoEx>();
  1046. List<string> jointExamIds = new List<string>();
  1047. //var query = $"select value(c) from c ";
  1048. 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}") }))
  1049. {
  1050. using var json = await JsonDocument.ParseAsync(item.Content);
  1051. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1052. {
  1053. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1054. {
  1055. //obj.TryGetProperty("progress", out JsonElement progress);
  1056. ExamInfoEx exInfo = obj.ToObject<ExamInfoEx>();
  1057. examInfo.Add(exInfo);
  1058. if (!string.IsNullOrWhiteSpace(exInfo.jointExamId) && !jointExamIds.Contains(exInfo.jointExamId)) jointExamIds.Add(exInfo.jointExamId);
  1059. }
  1060. }
  1061. }
  1062. //加入統測資訊
  1063. List<JointExam> jointExams = new List<JointExam>();
  1064. if (jointExamIds.Count > 0)
  1065. {
  1066. StringBuilder stringBuilderJointEx = new($"SELECT c.id, c.name, c.code, c.jointEventId, c.jointScheduleId, c.jointGroupId, c.creatorId, c.examType, c.progress FROM c WHERE ARRAY_CONTAINS({JsonSerializer.Serialize(jointExamIds)}, c.id, true) ");
  1067. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: stringBuilderJointEx.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"JointExam") }))
  1068. {
  1069. using var json = await JsonDocument.ParseAsync(item.Content);
  1070. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1071. {
  1072. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1073. {
  1074. jointExams.Add(obj.ToObject<JointExam>());
  1075. }
  1076. }
  1077. }
  1078. }
  1079. foreach (ExamInfoEx exinfo in examInfo)
  1080. {
  1081. JointExam jointExamNow = jointExams.Where(j => !string.IsNullOrWhiteSpace(exinfo.jointExamId) && j.id.Equals(exinfo.jointExamId)).FirstOrDefault();
  1082. if (jointExamNow != null)
  1083. {
  1084. exinfo.jointExamType = jointExamNow.examType;
  1085. }
  1086. }
  1087. return Ok(new { examInfo });
  1088. }
  1089. catch (Exception e)
  1090. {
  1091. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/FindSummary()\n{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1092. return BadRequest();
  1093. }
  1094. }
  1095. /// <summary>
  1096. /// 学生回答问题
  1097. /// </summary>
  1098. /// <param name="request"></param>
  1099. /// <returns></returns>
  1100. [ProducesDefaultResponseType]
  1101. [Authorize(Roles = "IES")]
  1102. [AuthToken(Roles = "student,teacher")]
  1103. [HttpPost("upsert-record")]
  1104. public async Task<IActionResult> upsertRecord(JsonElement request)
  1105. {
  1106. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1107. //学校编码
  1108. //if (!request.TryGetProperty("school", out JsonElement school)) return BadRequest();
  1109. if (!request.TryGetProperty("answer", out JsonElement answer)) return BadRequest();
  1110. if (!request.TryGetProperty("paperAns", out JsonElement paperAns)) return BadRequest();
  1111. if (!request.TryGetProperty("point", out JsonElement point)) return BadRequest();
  1112. //if (!request.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
  1113. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  1114. if (!request.TryGetProperty("classIds", out JsonElement classId)) return BadRequest();
  1115. if (!request.TryGetProperty("multipleRule", out JsonElement multipleRule)) return BadRequest();
  1116. //if (!request.TryGetProperty("answers ", out JsonElement tandardAnswer)) return BadRequest();
  1117. //if (!request.TryGetProperty("paperId", out JsonElement paperId)) return BadRequest();
  1118. //根据不同评测的类型返回对应的编码
  1119. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1120. if (!request.TryGetProperty("scode", out JsonElement scode)) return BadRequest();
  1121. var (userId, name, picture, school) = HttpContext.GetAuthTokenInfo();
  1122. try
  1123. {
  1124. List<string> ids = new List<string>();
  1125. ids = classId.ToObject<List<string>>();
  1126. var client = _azureCosmos.GetCosmosClient();
  1127. ExamInfo info = new();
  1128. var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"{scode}"));
  1129. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  1130. {
  1131. using var cJson = await JsonDocument.ParseAsync(response.Content);
  1132. info = cJson.ToObject<ExamInfo>();
  1133. }
  1134. else
  1135. {
  1136. return Ok(new { code = 404, msg = "该活动未被找到" });
  1137. }
  1138. //ExamInfo info = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.GetString(), new PartitionKey($"{scode}"));
  1139. //确定当前学生所在班级且该班级参与该活动
  1140. //List<string> cIds = new();
  1141. if (ids.Count == 0) return Ok(new { code = 404, msg = "未找到相关班级信息" });
  1142. if (string.IsNullOrEmpty(userId)) return Ok(new { code = 404, msg = "当前用户信息未找到" });
  1143. /*foreach (string cId in ids)
  1144. {
  1145. //List<string> stus = new List<string>();
  1146. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIteratorSql(
  1147. queryText: $"select c.classId as id from c where c.classId = '{cId}' and c.id = '{userId}'",
  1148. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{info.school}") }))
  1149. {
  1150. using var json = await JsonDocument.ParseAsync(item.Content);
  1151. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1152. {
  1153. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1154. while (accounts.MoveNext())
  1155. {
  1156. JsonElement account = accounts.Current;
  1157. cIds.Add(account.GetProperty("id").GetString());
  1158. }
  1159. break;
  1160. }
  1161. }
  1162. if (info.scope.Equals("private"))
  1163. {
  1164. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIteratorSql(
  1165. queryText: $"select c.id from c join A0 in c.members where c.id = '{cId}' and A0.id = '{userId}'",
  1166. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList") }))
  1167. {
  1168. using var json = await JsonDocument.ParseAsync(item.Content);
  1169. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1170. {
  1171. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1172. while (accounts.MoveNext())
  1173. {
  1174. JsonElement account = accounts.Current;
  1175. cIds.Add(account.GetProperty("id").GetString());
  1176. }
  1177. break;
  1178. }
  1179. }
  1180. }
  1181. else
  1182. {
  1183. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIteratorSql(
  1184. queryText: $"select c.id from c join A0 in c.members where c.id = '{cId}' and A0.id = '{userId}'",
  1185. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{info.school}") }))
  1186. {
  1187. using var json = await JsonDocument.ParseAsync(item.Content);
  1188. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1189. {
  1190. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1191. while (accounts.MoveNext())
  1192. {
  1193. JsonElement account = accounts.Current;
  1194. cIds.Add(account.GetProperty("id").GetString());
  1195. }
  1196. break;
  1197. }
  1198. }
  1199. }
  1200. }*/
  1201. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  1202. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(
  1203. 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}'"))})",
  1204. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
  1205. {
  1206. using var json = await JsonDocument.ParseAsync(item.Content);
  1207. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1208. {
  1209. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1210. {
  1211. examClassResults.Add(obj.ToObject<ExamClassResult>());
  1212. }
  1213. }
  1214. }
  1215. examClassResults = examClassResults.Where(c => c.studentIds.Contains(userId)).ToList();
  1216. ExamClassResult classResult = new ExamClassResult();
  1217. /* List<PaperSimple> standerAnswers = new List<PaperSimple>();
  1218. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(
  1219. queryText: $"select A0.point,A0.answers from c join A0 in c.papers where c.id = '{id}'and A0.id = '{paperId}'",
  1220. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
  1221. {
  1222. using var json = await JsonDocument.ParseAsync(item.Content);
  1223. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1224. {
  1225. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1226. {
  1227. standerAnswers.Add(obj.ToObject<PaperSimple>());
  1228. }
  1229. }
  1230. }*/
  1231. List<List<string>> ans = answer.ToObject<List<List<string>>>();
  1232. List<List<string>> standard = paperAns.ToObject<List<List<string>>>();
  1233. List<double> points = point.ToObject<List<double>>();
  1234. int rule = int.Parse(multipleRule.ToString());
  1235. /* foreach (PaperSimple simple in standerAnswers)
  1236. {
  1237. standard = simple.answers;
  1238. points = simple.point;
  1239. }*/
  1240. List<Task<string>> tasks = new List<Task<string>>();
  1241. foreach (ExamClassResult result in examClassResults)
  1242. {
  1243. //int index = result.studentIds.IndexOf(userId.ToString());
  1244. //存放客观题作答详情
  1245. //if (result.ans.Count == 0)
  1246. //{
  1247. // foreach (string cc in result.studentIds)
  1248. // {
  1249. // List<List<string>> anc = new List<List<string>>();
  1250. // foreach (List<string> opc in standard)
  1251. // {
  1252. // anc.Add(new List<string>());
  1253. // }
  1254. // result.ans.Add(anc);
  1255. // }
  1256. //}
  1257. int newIndex = result.studentIds.IndexOf(userId.ToString());
  1258. StringBuilder builder = new();
  1259. builder.Append(result.examId).Append('/');
  1260. builder.Append(result.subjectId).Append('/');
  1261. builder.Append(userId).Append('/');
  1262. builder.Append("ans.json");
  1263. /*string FileName = result.examId + "/" + result.subjectId + "/" + studentId;
  1264. string blob = FileName + "/" + "ans.json";*/
  1265. tasks.Add(_azureStorage.GetBlobContainerClient(code.ToString()).UploadFileByContainer(ans.ToJsonString(), "exam", builder.ToString(), false));
  1266. result.studentAnswers[newIndex].Add(builder.ToString());
  1267. result.status[newIndex] = 0;
  1268. //}
  1269. //List<(int index ,string content, double count)> acount = new List<(int index,string content, double count)>();
  1270. for (int i = 0; i < ans.Count; i++)
  1271. {
  1272. var sc = standard[i].Count;
  1273. var ac = ans[i].Where(a => a.Trim().Length > 0).ToList().Count;
  1274. //算分处理
  1275. if (sc > 0)
  1276. {
  1277. /* if (ans[i].Count == 0)
  1278. {
  1279. continue;
  1280. }*/
  1281. result.ans[newIndex][i] = ans[i];
  1282. if (ac == sc && sc == 1)
  1283. {
  1284. foreach (string right in ans[i])
  1285. {
  1286. if (standard[i].Contains(right.Trim()))
  1287. {
  1288. result.studentScores[newIndex][i] = points[i];
  1289. }
  1290. else
  1291. {
  1292. result.studentScores[newIndex][i] = 0;
  1293. }
  1294. }
  1295. }
  1296. else
  1297. {
  1298. if (rule > 0)
  1299. {
  1300. int falseCount = 0;
  1301. if (ac > 0)
  1302. {
  1303. foreach (string obj in ans[i])
  1304. {
  1305. if (!standard[i].Contains(obj))
  1306. {
  1307. falseCount++;
  1308. }
  1309. }
  1310. switch (rule)
  1311. {
  1312. case 1:
  1313. if (ac == sc)
  1314. {
  1315. if (falseCount == 0)
  1316. {
  1317. result.studentScores[newIndex][i] = points[i];
  1318. }
  1319. else
  1320. {
  1321. result.studentScores[newIndex][i] = 0;
  1322. }
  1323. }
  1324. else
  1325. {
  1326. result.studentScores[newIndex][i] = 0;
  1327. }
  1328. break;
  1329. case 2:
  1330. if (falseCount > 0)
  1331. {
  1332. result.studentScores[newIndex][i] = 0;
  1333. }
  1334. else
  1335. {
  1336. if (ac == sc)
  1337. {
  1338. result.studentScores[newIndex][i] = points[i];
  1339. }
  1340. else
  1341. {
  1342. result.studentScores[newIndex][i] = points[i] / 2;
  1343. }
  1344. }
  1345. break;
  1346. case 3:
  1347. if (falseCount > 0)
  1348. {
  1349. result.studentScores[newIndex][i] = 0;
  1350. }
  1351. else
  1352. {
  1353. if (ac == sc)
  1354. {
  1355. result.studentScores[newIndex][i] = points[i];
  1356. }
  1357. else
  1358. {
  1359. result.studentScores[newIndex][i] = System.Math.Round((double)ac / sc * points[i], 1);
  1360. }
  1361. }
  1362. break;
  1363. case 4:
  1364. if (ac == sc)
  1365. {
  1366. result.studentScores[newIndex][i] = points[i];
  1367. }
  1368. else
  1369. {
  1370. double persent = (double)(sc - 2 * falseCount) / sc;
  1371. if (persent <= 0)
  1372. {
  1373. result.studentScores[newIndex][i] = 0;
  1374. }
  1375. else
  1376. {
  1377. result.studentScores[newIndex][i] = System.Math.Round(persent * points[i], 1);
  1378. }
  1379. }
  1380. break;
  1381. }
  1382. }
  1383. else
  1384. {
  1385. result.studentScores[newIndex][i] = 0;
  1386. }
  1387. }
  1388. }
  1389. }
  1390. }
  1391. /*if (result.studentScores.Contains(-1)) {
  1392. }*/
  1393. bool flag = true;
  1394. var a = result.studentScores.Where(z => z.Contains(-1));
  1395. if (a.Any())
  1396. {
  1397. flag = false;
  1398. }
  1399. //foreach (List<double> scores in result.studentScores)
  1400. //{
  1401. // foreach (double score in scores)
  1402. // {
  1403. // if (score == -1)
  1404. // {
  1405. // flag = false;
  1406. // break;
  1407. // }
  1408. // }
  1409. //}
  1410. //bool isAns = true;
  1411. bool isAns = result.studentScores[newIndex].Exists(s => s == -1);
  1412. HttpContext.Items.TryGetValue("Scope", out object scope);
  1413. int userType = $"{scope}".Equals(Constant.ScopeStudent) ? 2 : 1;
  1414. if (flag)
  1415. {
  1416. result.progress = true;
  1417. info.subjects.ForEach(s =>
  1418. {
  1419. if (s.id.Equals(subjectId.ToString()))
  1420. {
  1421. s.classCount += 1;
  1422. }
  1423. if (s.classCount > info.classes.Count)
  1424. {
  1425. s.classCount = info.classes.Count;
  1426. }
  1427. });
  1428. }
  1429. result.sum[newIndex] = result.studentScores[newIndex].Sum();
  1430. classResult = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
  1431. var target = info.scope.Equals("school") ? info.school : info.creatorId;
  1432. string _client = "web";
  1433. if (info.source.Equals("1"))
  1434. {
  1435. _client = "hiteach";
  1436. }
  1437. 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 });
  1438. if (isAns)
  1439. {
  1440. //if ($"{scope}".Equals(Constant.ScopeStudent))
  1441. //{
  1442. // StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{school}-{userId}"));
  1443. // activity.taskStatus = 0;
  1444. // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{school}-{userId}"));
  1445. //}
  1446. //if ($"{scope}".Equals(Constant.ScopeTmdUser))
  1447. //{
  1448. // StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{userId}"));
  1449. // activity.taskStatus = 0;
  1450. // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{userId}"));
  1451. //}
  1452. //if ($"{scope}".Equals(Constant.ScopeTeacher))
  1453. //{
  1454. // StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{userId}"));
  1455. // activity.taskStatus = 0;
  1456. // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{userId}"));
  1457. //}
  1458. }
  1459. else
  1460. {
  1461. if (request.TryGetProperty("artId", out JsonElement artId) && request.TryGetProperty("quotaId", out JsonElement quotaId))
  1462. {
  1463. await getArtInfoAsync(client, artId.GetString(), school, result.sum[newIndex], id.GetString(), subjectId.GetString(), quotaId.GetString(), userId, picture, name, userType, ids);
  1464. };
  1465. //if ($"{scope}".Equals(Constant.ScopeStudent))
  1466. //{
  1467. // StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{school}-{userId}"));
  1468. // activity.taskStatus = 1;
  1469. // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{school}-{userId}"));
  1470. //}
  1471. //if ($"{scope}".Equals(Constant.ScopeTmdUser))
  1472. //{
  1473. // StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{userId}"));
  1474. // activity.taskStatus = 1;
  1475. // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{userId}"));
  1476. //}
  1477. //if ($"{scope}".Equals(Constant.ScopeTeacher))
  1478. //{
  1479. // StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{userId}"));
  1480. // activity.taskStatus = 1;
  1481. // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{userId}"));
  1482. //}
  1483. }
  1484. }
  1485. //当作答班级数量与实际班级数量一致时才触发结算
  1486. var ansCount = info.subjects.Where(c => c.id.Equals(subjectId)).FirstOrDefault()?.classCount;
  1487. if (ansCount == info.classes.Count)
  1488. {
  1489. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(info, id.ToString(), new PartitionKey($"{scode}"));
  1490. }
  1491. await Task.WhenAll(tasks);
  1492. return Ok(new { classResult });
  1493. }
  1494. catch (Exception e)
  1495. {
  1496. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/upsertRecord()\n{e.Message}\n{e.StackTrace}\n\n{id.GetString()}\n{request.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1497. return BadRequest();
  1498. }
  1499. }
  1500. [ProducesDefaultResponseType]
  1501. [Authorize(Roles = "IES")]
  1502. [AuthToken(Roles = "student,teacher")]
  1503. [HttpPost("update-ans")]
  1504. public async Task<IActionResult> updateAns(JsonElement request)
  1505. {
  1506. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1507. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1508. if (!request.TryGetProperty("paperId", out JsonElement paperId)) return BadRequest();
  1509. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  1510. if (!request.TryGetProperty("paperAns", out JsonElement paperAns)) return BadRequest();
  1511. if (!request.TryGetProperty("point", out JsonElement point)) return BadRequest();
  1512. if (!request.TryGetProperty("kno", out JsonElement kno)) return BadRequest();
  1513. if (!request.TryGetProperty("multipleRule", out JsonElement multipleRule)) return BadRequest();
  1514. //根据不同评测的类型返回对应的编码
  1515. if (!request.TryGetProperty("scode", out JsonElement scode)) return BadRequest();
  1516. //var (userId, name, picture, school) = HttpContext.GetAuthTokenInfo();
  1517. try
  1518. {
  1519. var client = _azureCosmos.GetCosmosClient();
  1520. ExamInfo info = new();
  1521. var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"{scode}"));
  1522. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  1523. {
  1524. using var cJson = await JsonDocument.ParseAsync(response.Content);
  1525. info = cJson.ToObject<ExamInfo>();
  1526. }
  1527. else
  1528. {
  1529. return Ok(new { code = 404, msg = "该活动未被找到" });
  1530. }
  1531. //if (string.IsNullOrEmpty(userId)) return Ok(new { code = 404, msg = "当前用户信息未找到" });
  1532. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  1533. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(
  1534. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  1535. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
  1536. {
  1537. using var json = await JsonDocument.ParseAsync(item.Content);
  1538. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1539. {
  1540. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1541. {
  1542. examClassResults.Add(obj.ToObject<ExamClassResult>());
  1543. }
  1544. }
  1545. }
  1546. //examClassResults = examClassResults.Where(c => c.studentIds.Contains(userId)).ToList(); wo
  1547. ExamClassResult classResult = new();
  1548. List<List<string>> standard = paperAns.ToObject<List<List<string>>>();
  1549. int rule = int.Parse(multipleRule.ToString());
  1550. List<double> points = point.ToObject<List<double>>();
  1551. List<Task<string>> tasks = new List<Task<string>>();
  1552. info.papers.ForEach(c =>
  1553. {
  1554. if (c.id.Equals(paperId.GetString()))
  1555. {
  1556. c.answers = standard;
  1557. c.point = points;
  1558. }
  1559. });
  1560. foreach (ExamClassResult result in examClassResults)
  1561. {
  1562. int index = 0;
  1563. foreach (var ans in result.ans)
  1564. {
  1565. if (ans.Count == 0) continue;
  1566. for (int i = 0; i < ans.Count; i++)
  1567. {
  1568. var sc = standard[i].Count;
  1569. var ac = ans[i].Where(a => a.Trim().Length > 0).ToList().Count;
  1570. //算分处理
  1571. if (sc > 0)
  1572. {
  1573. if (ac == sc && sc == 1)
  1574. {
  1575. foreach (string right in ans[i])
  1576. {
  1577. if (standard[i].Contains(right.Trim()))
  1578. {
  1579. result.studentScores[index][i] = points[i];
  1580. }
  1581. else
  1582. {
  1583. result.studentScores[index][i] = 0;
  1584. }
  1585. }
  1586. }
  1587. else
  1588. {
  1589. if (rule > 0)
  1590. {
  1591. int falseCount = 0;
  1592. if (ac > 0)
  1593. {
  1594. foreach (string obj in ans[i])
  1595. {
  1596. if (!standard[i].Contains(obj))
  1597. {
  1598. falseCount++;
  1599. }
  1600. }
  1601. switch (rule)
  1602. {
  1603. case 1:
  1604. if (ac == sc)
  1605. {
  1606. if (falseCount == 0)
  1607. {
  1608. result.studentScores[index][i] = points[i];
  1609. }
  1610. else
  1611. {
  1612. result.studentScores[index][i] = 0;
  1613. }
  1614. }
  1615. else
  1616. {
  1617. result.studentScores[index][i] = 0;
  1618. }
  1619. break;
  1620. case 2:
  1621. if (falseCount > 0)
  1622. {
  1623. result.studentScores[index][i] = 0;
  1624. }
  1625. else
  1626. {
  1627. if (ac == sc)
  1628. {
  1629. result.studentScores[index][i] = points[i];
  1630. }
  1631. else
  1632. {
  1633. result.studentScores[index][i] = points[i] / 2;
  1634. }
  1635. }
  1636. break;
  1637. case 3:
  1638. if (falseCount > 0)
  1639. {
  1640. result.studentScores[index][i] = 0;
  1641. }
  1642. else
  1643. {
  1644. if (ac == sc)
  1645. {
  1646. result.studentScores[index][i] = points[i];
  1647. }
  1648. else
  1649. {
  1650. result.studentScores[index][i] = System.Math.Round((double)ac / sc * points[i], 1);
  1651. }
  1652. }
  1653. break;
  1654. case 4:
  1655. if (ac == sc)
  1656. {
  1657. result.studentScores[index][i] = points[i];
  1658. }
  1659. else
  1660. {
  1661. double persent = (double)(sc - 2 * falseCount) / sc;
  1662. if (persent <= 0)
  1663. {
  1664. result.studentScores[index][i] = 0;
  1665. }
  1666. else
  1667. {
  1668. result.studentScores[index][i] = System.Math.Round(persent * points[i], 1);
  1669. }
  1670. }
  1671. break;
  1672. }
  1673. }
  1674. else
  1675. {
  1676. result.studentScores[index][i] = 0;
  1677. }
  1678. }
  1679. }
  1680. }
  1681. }
  1682. result.sum[index] = result.studentScores[index].Sum();
  1683. index++;
  1684. }
  1685. classResult = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
  1686. }
  1687. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(info, id.ToString(), new PartitionKey($"{scode}"));
  1688. return Ok(new { code = 200, info });
  1689. }
  1690. catch (Exception e)
  1691. {
  1692. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/updateAns()\n{e.Message}\n{e.StackTrace}\n\n{id.GetString()}\n{request.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1693. return BadRequest();
  1694. }
  1695. }
  1696. 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)
  1697. {
  1698. var aresponse = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(artId, new PartitionKey($"Art-{school}"));
  1699. ArtEvaluation art;
  1700. StudentArtResult artResult;
  1701. string rId = string.Format("{0}{1}{2}", school, "-", userid);
  1702. if (aresponse.StatusCode == System.Net.HttpStatusCode.OK)
  1703. {
  1704. using var json = await JsonDocument.ParseAsync(aresponse.Content);
  1705. art = json.ToObject<ArtEvaluation>();
  1706. var response = await client.GetContainer("TEAMModelOS", "Student").ReadItemStreamAsync(rId, new PartitionKey($"ArtResult-{artId}"));
  1707. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  1708. {
  1709. using var json_1 = await JsonDocument.ParseAsync(response.Content);
  1710. artResult = json_1.ToObject<StudentArtResult>();
  1711. //bool flage = artResult.results.Exists(a => a.taskId == acId);
  1712. artResult.results.ForEach(a =>
  1713. {
  1714. if (a.taskId == acId)
  1715. {
  1716. a.score = score;
  1717. }
  1718. });
  1719. await client.GetContainer("TEAMModelOS", "Student").ReplaceItemAsync(artResult, artResult.id, new PartitionKey($"{artResult.code}"));
  1720. }
  1721. else
  1722. {
  1723. artResult = new StudentArtResult
  1724. {
  1725. id = rId,
  1726. pk = "ArtResult",
  1727. code = $"ArtResult-{artId}",
  1728. studentId = userid,
  1729. picture = picture,
  1730. studentName = name,
  1731. school = school,
  1732. userType = userType,
  1733. artId = artId,
  1734. classIds = cIds,
  1735. };
  1736. art.settings.ForEach(qIds =>
  1737. {
  1738. qIds.task.ForEach(task =>
  1739. {
  1740. ArtQuotaResult quotaResult = new()
  1741. {
  1742. quotaId = qIds.id,
  1743. quotaName = qIds.quotaname,
  1744. quotaType = (int)task.type,
  1745. taskId = task.acId,
  1746. subjectId = task.subject
  1747. };
  1748. if (!string.IsNullOrEmpty(quotaResult.taskId))
  1749. {
  1750. if (quotaResult.taskId.Equals(acId))
  1751. {
  1752. quotaResult.score = score;
  1753. }
  1754. }
  1755. artResult.results.Add(quotaResult);
  1756. });
  1757. });
  1758. //foreach (var qIds in art.settings)
  1759. //{
  1760. // foreach (var task in qIds.task)
  1761. // {
  1762. // ArtQuotaResult quotaResult = new()
  1763. // {
  1764. // quotaId = qIds.id,
  1765. // quotaName = qIds.quotaname,
  1766. // quotaType = (int)task.type,
  1767. // taskId = task.acId,
  1768. // subjectId = task.subject
  1769. // };
  1770. // if (!string.IsNullOrEmpty(quotaResult.taskId))
  1771. // {
  1772. // if (quotaResult.taskId.Equals(acId))
  1773. // {
  1774. // quotaResult.score = score;
  1775. // }
  1776. // }
  1777. // artResult.results.Add(quotaResult);
  1778. // }
  1779. //}
  1780. await client.GetContainer("TEAMModelOS", "Student").CreateItemAsync(artResult, new PartitionKey($"{artResult.code}"));
  1781. }
  1782. }
  1783. }
  1784. [ProducesDefaultResponseType]
  1785. [Authorize(Roles = "IES")]
  1786. [AuthToken(Roles = "teacher,admin")]
  1787. [HttpPost("upsert-record-by-teacher")]
  1788. public async Task<IActionResult> upsertRecordByTeacher(JsonElement request)
  1789. {
  1790. //ResponseBuilder builder = ResponseBuilder.custom();
  1791. try
  1792. {
  1793. var (userid, username, _, _) = HttpContext.GetAuthTokenInfo(); //取得TMID
  1794. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1795. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1796. if (!request.TryGetProperty("point", out JsonElement point)) return BadRequest();
  1797. if (!request.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
  1798. //if (!request.TryGetProperty("classId", out JsonElement classId)) return BadRequest();
  1799. //此参数表明此次操作对象为个人还是校本的评测内容
  1800. if (!request.TryGetProperty("school", out JsonElement school)) return BadRequest();
  1801. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  1802. //要先处理状态,判断卷子是否存在,并判断卷子归属的考试是否允许再次提交
  1803. //List<ExamInfo> exams = await _azureCosmos.FindByDict<ExamInfo>(new Dictionary<string, object> { { "id", request.examCode } });
  1804. List<List<double>> ans = point.ToObject<List<List<double>>>();
  1805. List<stus> sIds = studentId.ToObject<List<stus>>();
  1806. var client = _azureCosmos.GetCosmosClient();
  1807. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  1808. if (request.TryGetProperty("classId", out JsonElement classId))
  1809. {
  1810. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamClassResult>(
  1811. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.info.id = '{classId}'",
  1812. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
  1813. {
  1814. examClassResults.Add(item);
  1815. }
  1816. }
  1817. else
  1818. {
  1819. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamClassResult>(
  1820. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  1821. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
  1822. {
  1823. examClassResults.Add(item);
  1824. }
  1825. }
  1826. ExamClassResult classResult = new ExamClassResult();
  1827. //List<Task<ItemResponse<StuActivity>>> tasks = new List<Task<ItemResponse<StuActivity>>>();
  1828. foreach (ExamClassResult result in examClassResults)
  1829. {
  1830. int index_sc = 0;
  1831. foreach (stus s in sIds)
  1832. {
  1833. int index = result.studentIds.IndexOf(s.id.ToString());
  1834. for (int i = 0; i < ans[index_sc].Count; i++)
  1835. {
  1836. result.studentScores[index][i] = ans[index_sc][i];
  1837. }
  1838. result.sum[index] = result.studentScores[index].Sum();
  1839. //bool flag = result.studentScores[index].Exists(r => r == -1);
  1840. /*if (!flag)
  1841. {
  1842. if (s.type == 1)
  1843. {
  1844. try
  1845. {
  1846. //StuActivity activity = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{s.id}"));
  1847. //activity.sStatus = 1;
  1848. //tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(activity, activity.id, new PartitionKey($"{activity.code}")));
  1849. }
  1850. catch (Exception ex)
  1851. {
  1852. await _dingDing.SendBotMsg($"{_option.Location}\n{ex.Message}\n{ex.StackTrace}\n\n,id:{id},code:{s.id},school:{result?.school}", GroupNames.醍摩豆服務運維群組);
  1853. }
  1854. }
  1855. else
  1856. {
  1857. try
  1858. {
  1859. var response = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Activity-{result.school}-{s.id}"));
  1860. if (response.StatusCode==System.Net.HttpStatusCode.OK)
  1861. {
  1862. using var json = await JsonDocument.ParseAsync(response.Content);
  1863. //StuActivity activity = json.ToObject<StuActivity>();
  1864. //activity.sStatus = 1;
  1865. //tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(activity, activity.id, new PartitionKey($"{activity.code}")));
  1866. }
  1867. else
  1868. {
  1869. List<string> scode = new();
  1870. 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'"))
  1871. {
  1872. using var stuJson = await JsonDocument.ParseAsync(item.Content);
  1873. if (stuJson.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1874. {
  1875. var accounts = stuJson.RootElement.GetProperty("Documents").EnumerateArray();
  1876. while (accounts.MoveNext())
  1877. {
  1878. JsonElement account = accounts.Current;
  1879. scode.Add(account.GetProperty("schoolId").GetString());
  1880. }
  1881. }
  1882. }
  1883. foreach (var sid in scode)
  1884. {
  1885. //StuActivity activity = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{sid}-{s.id}"));
  1886. //activity.sStatus = 1;
  1887. //tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(activity, activity.id, new PartitionKey($"{activity.code}")));
  1888. }
  1889. }
  1890. }
  1891. catch (Exception ex)
  1892. {
  1893. await _dingDing.SendBotMsg($"{_option.Location}\n{ex.Message}\n{ex.StackTrace}\n\n,id:{id},code:{s.id},school:{result?.school}", GroupNames.醍摩豆服務運維群組);
  1894. }
  1895. }
  1896. }*/
  1897. index_sc++;
  1898. }
  1899. if (!result.progress)
  1900. {
  1901. bool flag = true;
  1902. foreach (List<double> scores in result.studentScores)
  1903. {
  1904. foreach (double score in scores)
  1905. {
  1906. if (score == -1)
  1907. {
  1908. flag = false;
  1909. break;
  1910. }
  1911. }
  1912. }
  1913. if (flag)
  1914. {
  1915. ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  1916. result.progress = true;
  1917. exam.subjects.ForEach(s =>
  1918. {
  1919. if (s.id.Equals(subjectId.ToString()))
  1920. {
  1921. s.classCount += 1;
  1922. }
  1923. });
  1924. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"Exam-{code}"));
  1925. //若為統測評量,紀錄修改分數內容
  1926. if (!string.IsNullOrWhiteSpace(exam.jointExamId)) await upsertExamClassResultMark(result, userid, username, sIds, ans);
  1927. }
  1928. }
  1929. else
  1930. {
  1931. ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  1932. exam.updateTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  1933. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"Exam-{code}"));
  1934. //若為統測評量,紀錄修改分數內容
  1935. if (!string.IsNullOrWhiteSpace(exam.jointExamId)) await upsertExamClassResultMark(result, userid, username, sIds, ans);
  1936. }
  1937. classResult = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
  1938. // await Task.WhenAll(tasks);
  1939. }
  1940. //检查所有成员是否完成打分
  1941. List<List<double>> ers = new List<List<double>>();
  1942. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(
  1943. queryText: $"select c.studentScores as scores from c where c.examId = '{id}'",
  1944. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
  1945. {
  1946. using var json = await JsonDocument.ParseAsync(item.Content);
  1947. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1948. {
  1949. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1950. while (accounts.MoveNext())
  1951. {
  1952. JsonElement account = accounts.Current;
  1953. List<List<double>> sc = account.GetProperty("scores").ToObject<List<List<double>>>();
  1954. ers.AddRange(sc);
  1955. }
  1956. }
  1957. }
  1958. var isScore = !ers.Exists(c => c.Contains(-1));
  1959. return Ok(new { classResult, isScore });
  1960. }
  1961. catch (Exception ex)
  1962. {
  1963. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/upsertRecordByTeacher()\n{ex.StackTrace}\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1964. return BadRequest();
  1965. }
  1966. /*if (exams.IsNotEmpty())
  1967. {
  1968. ExamInfo examInfo = exams[0];
  1969. //提交答案时间必须是状态已发布,且时间在起止时间内
  1970. if (examInfo.startTime <= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() && examInfo.status == 200 &&
  1971. examInfo.endTime >= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
  1972. {
  1973. return builder.Data(await _azureCosmos.SaveOrUpdate(request)).build();
  1974. }
  1975. else
  1976. {
  1977. return builder.Error(ResponseCode.FAILED, "请在作答时间段内提交答案!").build();
  1978. }
  1979. }
  1980. else
  1981. {
  1982. return builder.Error(ResponseCode.DATA_EXIST, "考试不存在!").build();
  1983. }*/
  1984. }
  1985. /// <summary>
  1986. /// 查询评测详细信息(教师或者学生通用)
  1987. /// </summary>
  1988. /// <param name="request"></param>
  1989. /// <returns></returns>
  1990. [ProducesDefaultResponseType]
  1991. [Authorize(Roles = "IES")]
  1992. [AuthToken(Roles = "teacher,admin")]
  1993. [HttpPost("find-summary-record")]
  1994. public async Task<IActionResult> findSummaryRecord(JsonElement request)
  1995. {
  1996. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1997. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1998. //if (!request.TryGetProperty("code", out JsonElement school_code)) return BadRequest();
  1999. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  2000. if (!request.TryGetProperty("code", out JsonElement school_code)) return BadRequest();
  2001. if (!request.TryGetProperty("classId", out JsonElement classId)) return BadRequest();
  2002. if (!request.TryGetProperty("startTime", out JsonElement startTime)) return BadRequest();
  2003. try
  2004. {
  2005. /* var data = new
  2006. {
  2007. examCode = 2001717656163218,
  2008. subjects = new List<string> {"语文"}
  2009. };
  2010. var info = await ThirdService.CreateMoofenExamResult(_httpClient, data.ToJsonString().ToObject<JsonElement>(), _dingDing);*/
  2011. // 如果只有学生id则返回学生参加过的考试 只返回相关摘要信息
  2012. var client = _azureCosmos.GetCosmosClient();
  2013. var (_, _, _, school) = HttpContext.GetAuthTokenInfo();
  2014. //string code = school_code.ToString().Substring(5);
  2015. //ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{school_code}"));
  2016. Dictionary<string, List<string>> examClassResultCodeIdDic = new Dictionary<string, List<string>>(); //examClassResult code對應ID表 ※取得閱卷變更結果用
  2017. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  2018. 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}'",
  2019. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school_code}") }))
  2020. {
  2021. examClassResults.Add(item);
  2022. }
  2023. List<string> ids = new();
  2024. //List<string> codes = new();
  2025. foreach (ExamClassResult result in examClassResults)
  2026. {
  2027. ids.AddRange(result.studentIds);
  2028. //codes.AddRange(result.scIds);
  2029. if(!examClassResultCodeIdDic.ContainsKey(result.code)) examClassResultCodeIdDic.Add(result.code, new List<string>() { result.id });
  2030. else if (!examClassResultCodeIdDic[result.code].Contains(result.id)) examClassResultCodeIdDic[result.code].Add(result.id);
  2031. }
  2032. List<string> cid = new()
  2033. {
  2034. classId.GetString()
  2035. };
  2036. (List<RMember> members, List<RGroupList> groups) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, cid, $"{school}", null, -1, startTime.GetInt64());
  2037. //await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<GroupList>(classId.GetString, new PartitionKey($"Exam-{code}"));
  2038. ///获取真实的名称
  2039. List<ufo> ufos = new();
  2040. List<string> delIds = new();
  2041. if (groups.Count > 0)
  2042. {
  2043. //string scode = groups[0].school;
  2044. if (ids.Count > 0)
  2045. {
  2046. List<string> sIds = members.Where(c => c.type == 2).Select(z => z.id).ToList();
  2047. List<string> tIds = members.Where(c => c.type == 1).Select(z => z.id).ToList();
  2048. List<string> pIds = members.Where(c => c.type == 3).Select(z => z.id).ToList(); //簡易課程名單成員
  2049. List<ufo> students = new List<ufo>();
  2050. if (tIds.Any())
  2051. {
  2052. var tmds = ids.Intersect(tIds).ToList();
  2053. delIds.AddRange(ids.Except(tIds).ToList());
  2054. if (tmds.Any())
  2055. {
  2056. var content = new StringContent(tmds.ToJsonString(), Encoding.UTF8, "application/json");
  2057. string json = await _coreAPIHttpService.GetUserInfos(content);
  2058. if (!string.IsNullOrWhiteSpace(json))
  2059. {
  2060. try
  2061. {
  2062. List<ufo> tmdInfos = json.ToObject<List<ufo>>();
  2063. if (tmdInfos.IsNotEmpty())
  2064. {
  2065. foreach (ufo fo in tmdInfos)
  2066. {
  2067. fo.type = 1;
  2068. }
  2069. ufos.AddRange(tmdInfos);
  2070. }
  2071. }
  2072. catch (Exception ex)
  2073. {
  2074. await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.location}用户转换失败:{_coreAPIHttpService.options.coreUrl}{json}\n ", GroupNames.醍摩豆服務運維群組);
  2075. }
  2076. }
  2077. }
  2078. }
  2079. if (sIds.Any())
  2080. {
  2081. var stus = ids.Intersect(sIds).ToList();
  2082. delIds.AddRange(ids.Except(sIds).ToList());
  2083. if (stus.Any())
  2084. {
  2085. 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'",
  2086. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{school}") }))
  2087. {
  2088. using var stuJson = await JsonDocument.ParseAsync(item.Content);
  2089. if (stuJson.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2090. {
  2091. var accounts = stuJson.RootElement.GetProperty("Documents").EnumerateArray();
  2092. while (accounts.MoveNext())
  2093. {
  2094. JsonElement account = accounts.Current;
  2095. ufo fo = new()
  2096. {
  2097. id = account.GetProperty("id").GetString(),
  2098. name = account.GetProperty("name").GetString(),
  2099. //schoolId = account.GetProperty("schoolId").GetString(),
  2100. type = 2
  2101. };
  2102. students.Add(fo);
  2103. }
  2104. }
  2105. }
  2106. ufos.AddRange(students);
  2107. }
  2108. }
  2109. if (pIds.Any()) //簡易課程名單處理
  2110. {
  2111. var ptus = ids.Intersect(pIds).ToList();
  2112. if (ptus.Any())
  2113. {
  2114. List<RMember> simples = members.Where(c => ptus.Contains(c.id)).ToList();
  2115. foreach(RMember simple in simples)
  2116. {
  2117. ufos.Add(new ufo()
  2118. {
  2119. id = simple.id,
  2120. name = (!string.IsNullOrWhiteSpace(simple.name)) ? simple.name : (!string.IsNullOrWhiteSpace(simple.nickname)) ? simple.nickname : "",
  2121. type = simple.type
  2122. });
  2123. }
  2124. }
  2125. }
  2126. }
  2127. }
  2128. //List<ufo> students = new List<ufo>();
  2129. /*if (StringHelper.getKeyCount(request) == 1 && request.TryGetProperty("code", out JsonElement code))
  2130. {
  2131. List<object> props = new List<object>();
  2132. 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}") }))
  2133. {
  2134. using var json = await JsonDocument.ParseAsync(item.Content);
  2135. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2136. {
  2137. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  2138. {
  2139. props.Add(obj.ToObject<object>());
  2140. }
  2141. }
  2142. }
  2143. return Ok(new { props });
  2144. }
  2145. else
  2146. {
  2147. if (request.TryGetProperty("examCode", out JsonElement _))
  2148. {
  2149. //List<string> props = new List<string> { "id", "code", "examCode", "status", "mark", "score" };
  2150. //List<ExamRecord> examRecords = await _azureCosmos.FindByDict<ExamRecord>(request, props);
  2151. //return builder.Data(examRecords).Extend(new Dictionary<string, object> { { "props", props } }).build();
  2152. List<object> props = new List<object>();
  2153. 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}") }))
  2154. {
  2155. using var json = await JsonDocument.ParseAsync(item.Content);
  2156. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2157. {
  2158. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  2159. {
  2160. props.Add(obj.ToObject<object>());
  2161. }
  2162. }
  2163. }
  2164. return Ok(new { props });
  2165. }
  2166. }*/
  2167. //取得教師批改紀錄 ※目前只有統測評量有紀錄
  2168. List<ExamClassResultMark> markResult = new List<ExamClassResultMark>();
  2169. foreach(KeyValuePair<string, List<string>> seed in examClassResultCodeIdDic) {
  2170. string code = seed.Key.Replace("ExamClassResult", "ExamClassResultMark");
  2171. List<string> idList = seed.Value;
  2172. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Common).GetItemQueryStreamIteratorSql(queryText: $"SELECT * FROM c where c.id in ({string.Join(",", idList.Select(o => $"'{o}'"))}) and c.pk = 'ExamClassResultMark'",
  2173. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
  2174. {
  2175. using var json = await JsonDocument.ParseAsync(item.Content);
  2176. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2177. {
  2178. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  2179. {
  2180. markResult.Add(obj.ToObject<ExamClassResultMark>());
  2181. }
  2182. }
  2183. }
  2184. }
  2185. return Ok(new { examClassResults, ufos, delIds, markResult });
  2186. }
  2187. catch (Exception ex)
  2188. {
  2189. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findSummaryRecord()\n{ex.Message}\n{ex.StackTrace}\n\n{id.GetString()}", GroupNames.醍摩豆服務運維群組);
  2190. return BadRequest();
  2191. }
  2192. }
  2193. /// <summary>
  2194. /// 查询複數评测详细信息(教师用)
  2195. /// </summary>
  2196. /// <param name="request"></param>
  2197. /// <returns></returns>
  2198. [ProducesDefaultResponseType]
  2199. [Authorize(Roles = "IES")]
  2200. [AuthToken(Roles = "teacher,admin")]
  2201. [HttpPost("find-summary-records")]
  2202. public async Task<IActionResult> findSummaryRecords(JsonElement request)
  2203. {
  2204. try
  2205. {
  2206. if (!request.TryGetProperty("data", out JsonElement data)) return BadRequest();
  2207. List<FindExamClassResultsReqParam> requestParams = data.ToObject<List<FindExamClassResultsReqParam>>();
  2208. StringBuilder sqlClassResult = new StringBuilder($"SELECT c.id,c.subjectId,c.code,c.scIds,c.info,c.studentIds,c.studentAnswers,c.studentScores,c.mark,c.status FROM c WHERE ");
  2209. StringBuilder sqlClassResultWhere = new StringBuilder();
  2210. foreach (FindExamClassResultsReqParam param in requestParams)
  2211. {
  2212. if(!sqlClassResultWhere.Length.Equals(0))
  2213. {
  2214. sqlClassResultWhere.Append(" OR ");
  2215. }
  2216. sqlClassResultWhere.Append($"( c.code = 'ExamClassResult-{param.creatorId}' ");
  2217. sqlClassResultWhere.Append($" AND c.examId = '{param.examId}' ");
  2218. sqlClassResultWhere.Append($" AND c.subjectId = '{param.subjectId}' ");
  2219. sqlClassResultWhere.Append($" AND c.info.id = '{param.groupListId}' )");
  2220. }
  2221. sqlClassResult.Append(sqlClassResultWhere);
  2222. var client = _azureCosmos.GetCosmosClient();
  2223. List<string> ids = new(); //學生ID
  2224. Dictionary<string, List<string>> examClassResultSchoolGroupDic = new Dictionary<string, List<string>>(); //examClassResult 學校ID=>班級ID對應表 ※成員訊息用
  2225. Dictionary<string, List<string>> examClassResultCodeIdDic = new Dictionary<string, List<string>>(); //examClassResult code對應ID表 ※取得閱卷變更結果用
  2226. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  2227. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamClassResult>(queryText: sqlClassResult.ToString(), requestOptions: null ))
  2228. {
  2229. examClassResults.Add(item);
  2230. ids.AddRange(item.studentIds);
  2231. //code =>ID 對應表
  2232. if (!examClassResultCodeIdDic.ContainsKey(item.code)) examClassResultCodeIdDic.Add(item.code, new List<string>() { item.id });
  2233. else if (!examClassResultCodeIdDic[item.code].Contains(item.id)) examClassResultCodeIdDic[item.code].Add(item.id);
  2234. //學校ID=>班級ID對應表
  2235. string sid = (!string.IsNullOrWhiteSpace(item.school)) ? item.school : string.Empty;
  2236. if (!examClassResultSchoolGroupDic.ContainsKey(sid)) examClassResultSchoolGroupDic.Add(sid, new List<string>() { item.info.id });
  2237. else if (!examClassResultSchoolGroupDic[sid].Contains(item.info.id)) examClassResultSchoolGroupDic[sid].Add(item.info.id);
  2238. }
  2239. //取得成員名單
  2240. List<RMember> members = new List<RMember>();
  2241. List<RGroupList> groups = new List<RGroupList>();
  2242. foreach (KeyValuePair<string, List<string>> item in examClassResultSchoolGroupDic)
  2243. {
  2244. string schId = item.Key;
  2245. List<string> cids = item.Value;
  2246. (List<RMember> member, List<RGroupList> group) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, cids, $"{schId}", null);
  2247. members.AddRange(member);
  2248. groups.AddRange(group);
  2249. }
  2250. members = members.Distinct().ToList();
  2251. groups = groups.Distinct().ToList();
  2252. ///获取真实的名称
  2253. List<ufo> ufos = new();
  2254. List<string> delIds = new();
  2255. if (groups.Count > 0)
  2256. {
  2257. if (ids.Count > 0)
  2258. {
  2259. var sSchIds = members.Where(c => c.type == 2).Select(z => new { z.id, z.schoolId }).ToList();
  2260. Dictionary<string, List<string>> SchIdDic = new Dictionary<string, List<string>>(); //學校ID => TMID 字典
  2261. foreach(var schId in sSchIds)
  2262. {
  2263. string sch = schId.schoolId;
  2264. string tmid = schId.id;
  2265. if(SchIdDic.ContainsKey(sch))
  2266. {
  2267. if (!SchIdDic[sch].Contains(tmid))
  2268. {
  2269. SchIdDic[sch].Add(tmid);
  2270. }
  2271. }
  2272. else
  2273. {
  2274. SchIdDic.Add(sch, new List<string>() { tmid });
  2275. }
  2276. }
  2277. List<string> sIds = sSchIds.Select(z => z.id).ToList();
  2278. List<string> tIds = members.Where(c => c.type == 1).Select(z => z.id).ToList();
  2279. List<string> pIds = members.Where(c => c.type == 3).Select(z => z.id).ToList(); //簡易課程名單成員
  2280. List<ufo> students = new List<ufo>();
  2281. if (tIds.Any())
  2282. {
  2283. var tmds = ids.Intersect(tIds).ToList();
  2284. if (tmds.Any())
  2285. {
  2286. var content = new StringContent(tmds.ToJsonString(), Encoding.UTF8, "application/json");
  2287. string json = await _coreAPIHttpService.GetUserInfos(content);
  2288. if (!string.IsNullOrWhiteSpace(json))
  2289. {
  2290. try
  2291. {
  2292. List<ufo> tmdInfos = json.ToObject<List<ufo>>();
  2293. if (tmdInfos.IsNotEmpty())
  2294. {
  2295. foreach (ufo fo in tmdInfos)
  2296. {
  2297. fo.type = 1;
  2298. }
  2299. ufos.AddRange(tmdInfos);
  2300. }
  2301. }
  2302. catch (Exception ex)
  2303. {
  2304. //await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.location}用户转换失败:{_coreAPIHttpService.options.coreUrl}{json}\n ", GroupNames.醍摩豆服務運維群組);
  2305. }
  2306. }
  2307. }
  2308. }
  2309. if (sIds.Any())
  2310. {
  2311. var stus = ids.Intersect(sIds).ToList();
  2312. if (stus.Any())
  2313. {
  2314. foreach(KeyValuePair<string, List<string>> ipare in SchIdDic)
  2315. {
  2316. string schId = ipare.Key;
  2317. List<string> stuIds = ipare.Value;
  2318. 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(",", stuIds.Select(o => $"'{o}'"))}) and c.pk = 'Base'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schId}") }))
  2319. {
  2320. using var stuJson = await JsonDocument.ParseAsync(item.Content);
  2321. if (stuJson.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2322. {
  2323. var accounts = stuJson.RootElement.GetProperty("Documents").EnumerateArray();
  2324. while (accounts.MoveNext())
  2325. {
  2326. JsonElement account = accounts.Current;
  2327. ufo fo = new()
  2328. {
  2329. id = account.GetProperty("id").GetString(),
  2330. name = account.GetProperty("name").GetString(),
  2331. //schoolId = account.GetProperty("schoolId").GetString(),
  2332. type = 2
  2333. };
  2334. students.Add(fo);
  2335. }
  2336. }
  2337. }
  2338. }
  2339. ufos.AddRange(students);
  2340. }
  2341. }
  2342. if (pIds.Any()) //簡易課程名單處理
  2343. {
  2344. var ptus = ids.Intersect(pIds).ToList();
  2345. if (ptus.Any())
  2346. {
  2347. List<RMember> simples = members.Where(c => ptus.Contains(c.id)).ToList();
  2348. foreach (RMember simple in simples)
  2349. {
  2350. ufos.Add(new ufo()
  2351. {
  2352. id = simple.id,
  2353. name = (!string.IsNullOrWhiteSpace(simple.name)) ? simple.name : (!string.IsNullOrWhiteSpace(simple.nickname)) ? simple.nickname : "",
  2354. type = simple.type
  2355. });
  2356. }
  2357. }
  2358. }
  2359. }
  2360. }
  2361. //取得教師批改紀錄 ※目前只有統測評量有紀錄
  2362. List<ExamClassResultMark> markResult = new List<ExamClassResultMark>();
  2363. foreach (KeyValuePair<string, List<string>> seed in examClassResultCodeIdDic)
  2364. {
  2365. string code = seed.Key.Replace("ExamClassResult", "ExamClassResultMark");
  2366. List<string> idList = seed.Value;
  2367. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Common).GetItemQueryStreamIteratorSql(queryText: $"SELECT * FROM c where c.id in ({string.Join(",", idList.Select(o => $"'{o}'"))}) and c.pk = 'ExamClassResultMark'",
  2368. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
  2369. {
  2370. using var json = await JsonDocument.ParseAsync(item.Content);
  2371. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2372. {
  2373. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  2374. {
  2375. markResult.Add(obj.ToObject<ExamClassResultMark>());
  2376. }
  2377. }
  2378. }
  2379. }
  2380. return Ok(new { examClassResults, ufos, delIds, markResult });
  2381. }
  2382. catch (Exception ex)
  2383. {
  2384. //await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findSummaryRecord()\n{ex.Message}\n{ex.StackTrace}\n\n{id.GetString()}", GroupNames.醍摩豆服務運維群組);
  2385. return BadRequest();
  2386. }
  2387. }
  2388. //学生端查询评测列表
  2389. [ProducesDefaultResponseType]
  2390. [Authorize(Roles = "IES")]
  2391. [AuthToken(Roles = "student,teacher,admin")]
  2392. [HttpPost("find-summary-by-student")]
  2393. public async Task<IActionResult> findSummaryStudent(JsonElement request)
  2394. {
  2395. //ResponseBuilder builder = ResponseBuilder.custom();
  2396. //var (id, school) = HttpContext.GetAuthTokenInfo();
  2397. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  2398. if (!request.TryGetProperty("cIds", out JsonElement cIds)) return BadRequest();
  2399. if (!request.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
  2400. if (!request.TryGetProperty("code", out JsonElement school)) return BadRequest();
  2401. if (!request.TryGetProperty("scode", out JsonElement scode)) return BadRequest();
  2402. try
  2403. {
  2404. var client = _azureCosmos.GetCosmosClient();
  2405. //var query = $"select value(c) where c.id ='{id}'";
  2406. //List<ExamInfo> exams = new List<ExamInfo>();
  2407. List<object> subjects = new List<object>();
  2408. List<string> classIds = new List<string>();
  2409. //List<string> stus = new List<string>();
  2410. //存放当前学生所在班级ID或者名单ID
  2411. /*HashSet<string> resultIds = new();
  2412. //List<string> ids = new List<string>();
  2413. //处理班级人数(公共部分的校本名单)
  2414. //List<Student> students = new List<Student>();
  2415. 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}") }))
  2416. {
  2417. using var json = await JsonDocument.ParseAsync(item.Content);
  2418. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2419. {
  2420. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  2421. while (accounts.MoveNext())
  2422. {
  2423. JsonElement account = accounts.Current;
  2424. resultIds.Add(account.GetProperty("id").GetString());
  2425. }
  2426. }
  2427. }
  2428. //获取自定义名单信息
  2429. List<GroupList> stuLists = new List<GroupList>();
  2430. 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}'",
  2431. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList") }))
  2432. {
  2433. stuLists.Add(item);
  2434. }
  2435. 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}'",
  2436. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
  2437. {
  2438. stuLists.Add(item);
  2439. }
  2440. if (stuLists.Count > 0)
  2441. {
  2442. foreach (GroupList stuList in stuLists)
  2443. {
  2444. resultIds.Add(stuList.id);
  2445. }
  2446. }
  2447. var queryClassId = $"select c.classes id,c.stuLists stus from c where c.id ='{id}'";
  2448. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: queryClassId, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
  2449. {
  2450. using var json = await JsonDocument.ParseAsync(item.Content);
  2451. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2452. {
  2453. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  2454. {
  2455. classIds.AddRange(obj.GetProperty("id").ToObject<List<string>>());
  2456. classIds.AddRange(obj.GetProperty("stus").ToObject<List<string>>());
  2457. //classIds = obj.ToObject<List<string>>();
  2458. }
  2459. }
  2460. }
  2461. //存放该学生所在班级参与当前评测的ID
  2462. List<string> infoIds = new List<string>();
  2463. foreach (string ids in resultIds)
  2464. {
  2465. if (classIds.Contains(ids))
  2466. {
  2467. infoIds.Add(ids);
  2468. }
  2469. }*/
  2470. //List<string> infoIds = cIds.ToObject<List<string>>();
  2471. List<string> infoIds = new();
  2472. ExamInfo info = new();
  2473. var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"{scode}"));
  2474. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  2475. {
  2476. using var cJson = await JsonDocument.ParseAsync(response.Content);
  2477. info = cJson.ToObject<ExamInfo>();
  2478. }
  2479. /*await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamInfo>(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
  2480. {
  2481. exams.Add(item);
  2482. }*/
  2483. var querySubject = $"select A0.id,A0.name from c join A0 in c.subjects where c.id ='{id}'";
  2484. //List<object> props = new List<object>();
  2485. List<string> subId = new();
  2486. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: querySubject, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
  2487. {
  2488. using var json = await JsonDocument.ParseAsync(item.Content);
  2489. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2490. {
  2491. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  2492. {
  2493. subjects.Add(obj.ToObject<object>());
  2494. subId.Add(obj.GetProperty("id").GetString());
  2495. }
  2496. }
  2497. }
  2498. 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' ";
  2499. List<ExamClassResult> answers = new List<ExamClassResult>();
  2500. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: queryAnswers,
  2501. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
  2502. {
  2503. using var json = await JsonDocument.ParseAsync(item.Content);
  2504. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2505. {
  2506. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  2507. {
  2508. answers.Add(obj.ToObject<ExamClassResult>());
  2509. infoIds.Add(obj.GetProperty("cId").GetString());
  2510. }
  2511. }
  2512. }
  2513. 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' ";
  2514. List<ExamClassResult> classResults = new List<ExamClassResult>();
  2515. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamClassResult>(queryText: queryResult,
  2516. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
  2517. {
  2518. classResults.Add(item);
  2519. }
  2520. //查询结果
  2521. List<ExamResult> results = new();
  2522. 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}") }))
  2523. {
  2524. results.Add(item);
  2525. }
  2526. List<List<string>> stuAns = new();
  2527. List<List<double>> stuScore = new();
  2528. List<List<List<Details>>> mark = new();
  2529. List<List<double>> total = new();
  2530. List<double> average = new();
  2531. if (answers.Count > 0)
  2532. {
  2533. foreach (ExamClassResult result in answers)
  2534. {
  2535. List<double> sTotal = new();
  2536. int index = result.studentIds.IndexOf(studentId.ToString());
  2537. if (index == -1)
  2538. {
  2539. break;
  2540. }
  2541. stuAns.Add(result.studentAnswers[index]);
  2542. stuScore.Add(result.studentScores[index]);
  2543. mark.Add(result.mark[index]);
  2544. average.Add(result.average);
  2545. sTotal.Add(result.sum.Where(s => s <= 59).Count());
  2546. sTotal.Add(result.sum.Where(s => s > 59 && s <= 70).Count());
  2547. sTotal.Add(result.sum.Where(s => s > 70 && s <= 80).Count());
  2548. sTotal.Add(result.sum.Where(s => s > 80 && s <= 90).Count());
  2549. sTotal.Add(result.sum.Where(s => s > 90 && s <= 100).Count());
  2550. total.Add(sTotal);
  2551. }
  2552. }
  2553. List<(List<string> kn, List<double> kps, List<double> ckps, List<double> akps)> know = new();
  2554. List<(List<int> fs, List<double> fps, List<double> cfps, List<double> afps)> fp = new();
  2555. List<List<double>> wno = new();
  2556. List<KeyValuePair<string, List<KeyValuePair<string, Dictionary<string, string>>>>> subjectScatter = new();
  2557. if (!string.IsNullOrEmpty(info.progress) && info.progress.Equals("finish"))
  2558. {
  2559. (List<RMember> members, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, infoIds, info.school, null, -1, info.startTime);
  2560. await foreach (var s in stuTask(subId, info.papers, answers, classResults, studentId.GetString()))
  2561. {
  2562. know = s.know;
  2563. fp = s.filed;
  2564. }
  2565. foreach (ExamResult exam in results)
  2566. {
  2567. subjectScatter.Add(DoSubjectScatter(exam, members));
  2568. //确定当前循环科目索引位置
  2569. int index = subId.IndexOf(exam.subjectId);
  2570. //根据索引找到试卷分数
  2571. List<double> points = info.papers[index].point;
  2572. List<double> wn = await getWrongNum(exam, points, infoIds);
  2573. wno.Add(wn);
  2574. }
  2575. if (info.papers.IsNotEmpty())
  2576. {
  2577. var knowledge = know.Select(k => new { k.kn, k.kps, k.ckps, k.akps });
  2578. var filed = fp.Select(k => new { k.fs, k.fps, k.cfps, k.afps });
  2579. //papers = papers
  2580. return Ok(new { info.cloudas, info.papers, subjects, stuScore, stuAns, mark, total, claId = infoIds, knowledge, filed, average, wno, subjectScatter, status = 200 });
  2581. }
  2582. }
  2583. 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 });
  2584. }
  2585. catch (Exception ex)
  2586. {
  2587. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-summary-by-student()\n{ex.Message}\n{ex.StackTrace}\n\n{id.GetString()}", GroupNames.醍摩豆服務運維群組);
  2588. return Ok(new { status = 500 });
  2589. }
  2590. }
  2591. 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)
  2592. {
  2593. 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)>();
  2594. 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)>();
  2595. int no = 0;
  2596. foreach (string sub in subjectIds)
  2597. {
  2598. List<double> kp = new();
  2599. List<double> akp = new();
  2600. List<double> fp = new();
  2601. List<double> afp = new();
  2602. List<double> ckp = new();
  2603. List<double> cfp = new();
  2604. List<int> fields = new() { 1, 2, 3, 4, 5, 6 };
  2605. //获取该试卷所有知识点和认知层次分布
  2606. List<List<string>> kones = papers[no].knowledge;
  2607. List<int> fs = papers[no].field;
  2608. List<double> point = papers[no].point;
  2609. //去重知识点
  2610. HashSet<string> knowles = new();
  2611. List<string> knowledges = new();
  2612. if (kones.Count > 0)
  2613. {
  2614. knowles = new HashSet<string>(kones.SelectMany(z => z));
  2615. }
  2616. knowledges.AddRange(knowles.Where(z => !string.IsNullOrWhiteSpace(z)));
  2617. List<ExamClassResult> classResults = answers.Where(result => !string.IsNullOrWhiteSpace(result?.subjectId) && result.subjectId.Equals(sub)).ToList();
  2618. List<ExamClassResult> allResults = results.Where(result => !string.IsNullOrWhiteSpace(result?.subjectId) && result.subjectId.Equals(sub)).ToList();
  2619. foreach (ExamClassResult result in classResults)
  2620. {
  2621. int index = result.studentIds.IndexOf(stuId.ToString());
  2622. //处理知识点
  2623. foreach (string k in knowledges)
  2624. {
  2625. //初始化单个知识点得分
  2626. double score = 0;
  2627. double allScore = 0;
  2628. int n = 0;
  2629. foreach (List<string> str in kones)
  2630. {
  2631. if (str.Contains(k))
  2632. {
  2633. var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
  2634. allScore += point.Count > 0 ? point[n] * itemPersent : 0;
  2635. if (result.studentScores.Count > 0)
  2636. {
  2637. if (result.studentScores[index].Count > 0)
  2638. {
  2639. score += result.studentScores[index][n] == -1 ? 0 : result.studentScores[index][n] * itemPersent;
  2640. }
  2641. }
  2642. }
  2643. n++;
  2644. }
  2645. kp.Add(allScore > 0 ? Math.Round(score / allScore, 2) : 0);
  2646. }
  2647. //处理认知层次
  2648. foreach (int k in fields)
  2649. {
  2650. //初始化认知层次得分
  2651. double score = 0;
  2652. double allScore = 0;
  2653. int n = 0;
  2654. foreach (int str in fs)
  2655. {
  2656. if (str == k)
  2657. {
  2658. var itemPersent = 1;
  2659. allScore += point.Count > 0 ? point[n] * itemPersent : 0;
  2660. if (result.studentScores.Count > 0)
  2661. {
  2662. if (result.studentScores[index].Count > 0)
  2663. {
  2664. score += result.studentScores[index][n] == -1 ? 0 : result.studentScores[index][n];
  2665. }
  2666. }
  2667. }
  2668. n++;
  2669. }
  2670. fp.Add(allScore > 0 ? Math.Round(score / allScore, 2) : 0);
  2671. }
  2672. ckp = result.krate;
  2673. cfp = result.frate;
  2674. }
  2675. foreach (string k in knowledges)
  2676. {
  2677. double score = 0;
  2678. double allScore = 0;
  2679. int count = 0;
  2680. foreach (ExamClassResult result in allResults)
  2681. {
  2682. int n = 0;
  2683. foreach (List<string> str in kones)
  2684. {
  2685. if (str.Contains(k))
  2686. {
  2687. var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
  2688. allScore += point.Count > 0 ? point[n] * itemPersent : 0;
  2689. if (result.studentScores.Count > 0)
  2690. {
  2691. /*score += result.studentScores.ForEach(r => r[n]) * itemPersent;*/
  2692. foreach (List<double> sc in result.studentScores)
  2693. {
  2694. double tsc = sc[n] == -1 ? 0 : sc[n];
  2695. score += tsc * itemPersent;
  2696. }
  2697. }
  2698. }
  2699. n++;
  2700. }
  2701. count += result.studentIds.Count;
  2702. }
  2703. double per = count > 0 ? Math.Round(score / count, 2) : 0;
  2704. akp.Add(allScore > 0 ? Math.Round(per / allScore, 2) : 0);
  2705. }
  2706. //处理认知层次
  2707. foreach (int k in fields)
  2708. {
  2709. //初始化认知层次得分
  2710. double score = 0;
  2711. double allScore = 0;
  2712. int count = 0;
  2713. foreach (ExamClassResult result in allResults)
  2714. {
  2715. if (result.subjectId.Equals(sub))
  2716. {
  2717. int n = 0;
  2718. foreach (int str in fs)
  2719. {
  2720. if (str == k)
  2721. {
  2722. var itemPersent = 1;
  2723. allScore += point.Count > 0 ? point[n] * itemPersent : 0;
  2724. if (result.studentScores.Count > 0)
  2725. {
  2726. foreach (List<double> sc in result.studentScores)
  2727. {
  2728. double tsc = sc[n] == -1 ? 0 : sc[n];
  2729. score += tsc * itemPersent;
  2730. }
  2731. }
  2732. }
  2733. n++;
  2734. }
  2735. count += result.studentIds.Count;
  2736. }
  2737. }
  2738. double per = count > 0 ? Math.Round(score / count, 2) : 0;
  2739. afp.Add(allScore > 0 ? Math.Round(per / allScore, 2) : 0);
  2740. }
  2741. know.Add((knowledges, kp, ckp, akp));
  2742. filed.Add((fields, fp, cfp, afp));
  2743. no++;
  2744. }
  2745. yield return (know, filed);
  2746. }
  2747. private KeyValuePair<string, List<KeyValuePair<string, Dictionary<string, string>>>> DoSubjectScatter(ExamResult e, List<RMember> members)
  2748. {
  2749. List<KeyValuePair<string, Dictionary<string, string>>> datas = new();
  2750. double[] point = StringHelper.ListTodouble(e.paper.point);
  2751. double[,] result = StringHelper.ListToDouble(e.studentScores);
  2752. List<string> scatterKey = new List<string>
  2753. {
  2754. "name",
  2755. "className",
  2756. "x",
  2757. "y",
  2758. "memberId",
  2759. "score",
  2760. "trueNum",
  2761. "falseNum",
  2762. "hardList",
  2763. "carefulList",
  2764. "scatter"
  2765. };
  2766. try
  2767. {
  2768. var cdm = new ClouDASMatrix(result, point);
  2769. //学生通过率
  2770. List<double> pass = cdm.ScoringRate;
  2771. //学生稳定度
  2772. List<double> sta = cdm.StabilityRate;
  2773. //落点区域
  2774. List<string> stu = cdm.StuFallArea;
  2775. //需努力的题型
  2776. List<int[]> strive = cdm.StriveTopic;
  2777. //需小心的题型
  2778. List<int[]> careful = cdm.CarefulTopic;
  2779. int i = 0;
  2780. for (int k = e.studentIds.Count - 1; k >= 0; k--)
  2781. {
  2782. if (e.studentIds[k].Equals("0"))
  2783. {
  2784. e.studentIds.Remove(e.studentIds[k]);
  2785. }
  2786. }
  2787. e.studentIds.ForEach(s =>
  2788. {
  2789. List<string> info = new()
  2790. {
  2791. members.Where(c => c.id.Equals(s)).FirstOrDefault()?.name,
  2792. "-",
  2793. sta[i] > 1 ? "1": sta[i].ToString(),
  2794. pass[i].ToString(),
  2795. i + 1 + "",
  2796. Math.Round(e.studentScores[i].Sum(),2).ToString()
  2797. };
  2798. int right = 0;
  2799. int wrong = 0;
  2800. foreach (double p in e.studentScores[i])
  2801. {
  2802. if (p > 0)
  2803. {
  2804. right++;
  2805. }
  2806. else
  2807. {
  2808. wrong++;
  2809. }
  2810. }
  2811. info.Add(right + "");
  2812. info.Add(wrong + "");
  2813. int[] str = strive[i];
  2814. string striveAll = "";
  2815. foreach (int n in str)
  2816. {
  2817. striveAll += n.ToString() + ",";
  2818. }
  2819. int[] care = careful[i];
  2820. string careAll = "";
  2821. foreach (int n in care)
  2822. {
  2823. careAll += n.ToString() + ",";
  2824. }
  2825. if (string.IsNullOrEmpty(striveAll))
  2826. {
  2827. info.Add("-");
  2828. }
  2829. else
  2830. {
  2831. info.Add(striveAll.Substring(0, striveAll.Length - 1));
  2832. }
  2833. if (string.IsNullOrEmpty(careAll))
  2834. {
  2835. info.Add("-");
  2836. }
  2837. else
  2838. {
  2839. info.Add(careAll.Substring(0, careAll.Length - 1)); ;
  2840. }
  2841. info.Add(stu[i].ToString());
  2842. int m = 0;
  2843. Dictionary<string, string> scatter = new();
  2844. foreach (string key in info)
  2845. {
  2846. scatter.Add(scatterKey[m], key);
  2847. m++;
  2848. }
  2849. KeyValuePair<string, Dictionary<string, string>> keyValue = new(s, scatter);
  2850. datas.Add(keyValue);
  2851. //}
  2852. i++;
  2853. });
  2854. return new KeyValuePair<string, List<KeyValuePair<string, Dictionary<string, string>>>>(e.subjectId, datas);
  2855. }
  2856. catch (Exception ex)
  2857. {
  2858. BadRequest(ex.Message + ex.StackTrace);
  2859. }
  2860. return default;
  2861. }
  2862. //查询学生活动列表
  2863. [ProducesDefaultResponseType]
  2864. [Authorize(Roles = "IES")]
  2865. [AuthToken(Roles = "student")]
  2866. [HttpPost("find-all-by-student")]
  2867. public async Task<IActionResult> findAllStudent(JsonElement request)
  2868. {
  2869. //ResponseBuilder builder = ResponseBuilder.custom();
  2870. //var (id, school) = HttpContext.GetAuthTokenInfo();
  2871. try
  2872. {
  2873. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  2874. if (!request.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
  2875. List<string> resultIds = new List<string>();
  2876. var client = _azureCosmos.GetCosmosClient();
  2877. //查询校本班级ID
  2878. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIteratorSql(
  2879. queryText: $"select c.id from c join A0 in c.students where A0.id = '{studentId}' and c.pk = 'Class' "))
  2880. {
  2881. using var json = await JsonDocument.ParseAsync(item.Content);
  2882. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2883. {
  2884. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  2885. while (accounts.MoveNext())
  2886. {
  2887. JsonElement account = accounts.Current;
  2888. resultIds.Add(account.GetProperty("id").GetString());
  2889. }
  2890. }
  2891. }
  2892. //查询私人班级ID
  2893. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIteratorSql(
  2894. queryText: $"select c.id from c join A0 in c.students where A0.id = '{studentId}' and c.pk = 'Class' "))
  2895. {
  2896. using var json = await JsonDocument.ParseAsync(item.Content);
  2897. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2898. {
  2899. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  2900. while (accounts.MoveNext())
  2901. {
  2902. JsonElement account = accounts.Current;
  2903. resultIds.Add(account.GetProperty("id").GetString());
  2904. }
  2905. }
  2906. }
  2907. //StringBuilder builder = new StringBuilder();
  2908. HashSet<string> strs = new HashSet<string>();
  2909. if (resultIds.Count > 1)
  2910. {
  2911. foreach (string str in resultIds)
  2912. {
  2913. strs.Add($"array_contains(c.classes,'{str}')");
  2914. //builder.Append($"array_contains(c.targetClassIds,'{str}')").Append("or");
  2915. }
  2916. //builder.ToString().Substring(0, builder.ToString().Length - 2);
  2917. }
  2918. else
  2919. {
  2920. string ssr = resultIds.Count > 0 ? resultIds[0] : "";
  2921. strs.Add($"array_contains(c.classes,'{ssr}')");
  2922. //builder.Append($" array_contains(c.targetClassIds,'{ssr}')");
  2923. }
  2924. string ss = string.Join(" or ", strs);
  2925. //if (!request.TryGetProperty("school", out JsonElement school)) return BadRequest();
  2926. 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' ";
  2927. List<object> props = new List<object>();
  2928. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: query))
  2929. {
  2930. using var json = await JsonDocument.ParseAsync(item.Content);
  2931. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2932. {
  2933. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  2934. {
  2935. props.Add(obj.ToObject<object>());
  2936. }
  2937. }
  2938. }
  2939. 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'";
  2940. List<ExamClassResult> Classes = new List<ExamClassResult>();
  2941. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: queryClass))
  2942. {
  2943. using var json = await JsonDocument.ParseAsync(item.Content);
  2944. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2945. {
  2946. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  2947. {
  2948. Classes.Add(obj.ToObject<ExamClassResult>());
  2949. }
  2950. }
  2951. }
  2952. List<ExamClassResult> result = new List<ExamClassResult>();
  2953. foreach (ExamClassResult classResult in Classes)
  2954. {
  2955. int index = classResult.studentIds.IndexOf(studentId.ToString());
  2956. ExamClassResult result1 = new ExamClassResult();
  2957. result1.examId = classResult.examId;
  2958. result1.subjectId = classResult.subjectId;
  2959. result1.studentAnswers.Add(classResult.studentAnswers[index]);
  2960. result1.studentScores.Add(classResult.studentScores[index]);
  2961. result.Add(result1);
  2962. }
  2963. return Ok(new { props, result });
  2964. }
  2965. catch (Exception ex)
  2966. {
  2967. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findAllStudent\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2968. return Ok(new { status = 500 });
  2969. }
  2970. }
  2971. //查询学生活动列表
  2972. [ProducesDefaultResponseType]
  2973. [Authorize(Roles = "IES")]
  2974. [AuthToken(Roles = "student")]
  2975. [HttpPost("find-score-by-student")]
  2976. public async Task<IActionResult> findScoreByStudent(JsonElement request)
  2977. {
  2978. //ResponseBuilder builder = ResponseBuilder.custom();
  2979. //var (id, school) = HttpContext.GetAuthTokenInfo();
  2980. try
  2981. {
  2982. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  2983. //if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  2984. var client = _azureCosmos.GetCosmosClient();
  2985. var query = $"select c.examId,c.subjectId,c.studentScores from c where array_contains(c.studentIds,'{id}') ";
  2986. List<object> props = new List<object>();
  2987. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: query))
  2988. {
  2989. using var json = await JsonDocument.ParseAsync(item.Content);
  2990. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2991. {
  2992. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  2993. {
  2994. props.Add(obj.ToObject<object>());
  2995. }
  2996. }
  2997. }
  2998. return Ok(props);
  2999. }
  3000. catch (Exception ex)
  3001. {
  3002. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findAllStudent\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  3003. return Ok(new { status = 500 });
  3004. }
  3005. }
  3006. //查询学生活动列表
  3007. [ProducesDefaultResponseType]
  3008. [Authorize(Roles = "IES")]
  3009. [AuthToken(Roles = "teacher,admin")]
  3010. [HttpPost("finish")]
  3011. public async Task<IActionResult> finish(JsonElement request)
  3012. {
  3013. //ResponseBuilder builder = ResponseBuilder.custom();
  3014. //var (id, school) = HttpContext.GetAuthTokenInfo();
  3015. try
  3016. {
  3017. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  3018. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  3019. var client = _azureCosmos.GetCosmosClient();
  3020. ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  3021. info.progress = "finish";
  3022. info.endTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  3023. List<ExamClassResult> classResults = new();
  3024. if (info.scope.Equals("school"))
  3025. {
  3026. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamClassResult>(
  3027. queryText: $"select value(c) from c where c.examId = '{id}'",
  3028. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.school}") }))
  3029. {
  3030. classResults.Add(item);
  3031. }
  3032. }
  3033. else
  3034. {
  3035. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamClassResult>(
  3036. queryText: $"select value(c) from c where c.examId = '{id}'",
  3037. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.creatorId}") }))
  3038. {
  3039. classResults.Add(item);
  3040. }
  3041. }
  3042. foreach (ExamClassResult examClass in classResults)
  3043. {
  3044. examClass.progress = true;
  3045. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(examClass, examClass.id, new PartitionKey($"{examClass.code}"));
  3046. }
  3047. info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(info, info.id, new PartitionKey($"Exam-{code}"));
  3048. return Ok(info);
  3049. }
  3050. catch (Exception ex)
  3051. {
  3052. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/finish\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  3053. return Ok(new { status = 500 });
  3054. }
  3055. }
  3056. /*//查询任务列表
  3057. [ProducesDefaultResponseType]
  3058. //[AuthToken(Roles = "Student")]
  3059. [HttpPost("scoring")]
  3060. public async Task<IActionResult> Scoring(JsonElement request)
  3061. {
  3062. //ResponseBuilder builder = ResponseBuilder.custom();
  3063. //var (id, school) = HttpContext.GetAuthTokenInfo();
  3064. try
  3065. {
  3066. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  3067. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  3068. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  3069. var client = _azureCosmos.GetCosmosClient();
  3070. ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  3071. int index = 0;
  3072. foreach (ExamSubject subject in info.subjects) {
  3073. if (!subject.id.Equals(subjectId.ToString()))
  3074. {
  3075. index++;
  3076. }
  3077. else {
  3078. break;
  3079. }
  3080. }
  3081. List<string> stuAns = new();
  3082. Dictionary<string, List<List<double>>> keyValues = new();
  3083. List<ExamClassResult> classResults = new();
  3084. if (info.scope.Equals("school"))
  3085. {
  3086. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamClassResult>(
  3087. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  3088. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.school}") }))
  3089. {
  3090. classResults.Add(item);
  3091. }
  3092. }
  3093. else
  3094. {
  3095. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamClassResult>(
  3096. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  3097. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.creatorId}") }))
  3098. {
  3099. classResults.Add(item);
  3100. }
  3101. }
  3102. List<List<double>> itemScore = new();
  3103. for (int i = 0; i < info.papers[index].point.Count; i++)
  3104. {
  3105. List<double> score = new();
  3106. foreach (ExamClassResult examClass in classResults)
  3107. {
  3108. foreach (List<double> sc in examClass.studentScores)
  3109. {
  3110. score.Add(sc[i]);
  3111. }
  3112. }
  3113. itemScore.Add(score);
  3114. }
  3115. foreach (ExamClassResult examClass in classResults)
  3116. {
  3117. foreach (List<string> ans in examClass.studentAnswers)
  3118. {
  3119. if (ans.Count > 0)
  3120. {
  3121. stuAns.Add(ans[0]);
  3122. }
  3123. else
  3124. {
  3125. stuAns.Add("");
  3126. }
  3127. }
  3128. }
  3129. //info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(info, info.id, new PartitionKey($"Exam-{code}"));
  3130. return Ok(new { score = itemScore , stuAns, paper = info.papers });
  3131. }
  3132. catch (Exception ex)
  3133. {
  3134. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/scoring\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  3135. return BadRequest();
  3136. }
  3137. }*/
  3138. [ProducesDefaultResponseType]
  3139. [Authorize(Roles = "IES")]
  3140. [AuthToken(Roles = "teacher,admin")]
  3141. [HttpPost("scoring")]
  3142. public async Task<IActionResult> scoring(JsonElement request)
  3143. {
  3144. //ResponseBuilder builder = ResponseBuilder.custom();
  3145. //var (id, school) = HttpContext.GetAuthTokenInfo();
  3146. try
  3147. {
  3148. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  3149. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  3150. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  3151. //if (!request.TryGetProperty("type", out JsonElement type)) return BadRequest();
  3152. if (!request.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  3153. if (!request.TryGetProperty("count", out JsonElement scount)) return BadRequest();
  3154. var client = _azureCosmos.GetCosmosClient();
  3155. //var redisClient = _azureRedis.GetRedisClient(8);
  3156. ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  3157. List<ExamClassResult> classResults = new();
  3158. List<SDK.Models.Cosmos.Common.Scoring> attr = new List<SDK.Models.Cosmos.Common.Scoring>();
  3159. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.Common.Scoring>(
  3160. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and array_contains(c.tIds,'{tId}') ",
  3161. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  3162. {
  3163. attr.Add(item);
  3164. }
  3165. List<SDK.Models.Cosmos.Common.Scoring> attrSc = new List<SDK.Models.Cosmos.Common.Scoring>();
  3166. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.Common.Scoring>(
  3167. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  3168. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  3169. {
  3170. attrSc.Add(item);
  3171. }
  3172. int index = 0;
  3173. foreach (ExamSubject subject in info.subjects)
  3174. {
  3175. if (!subject.id.Equals(subjectId.ToString()))
  3176. {
  3177. index++;
  3178. }
  3179. else
  3180. {
  3181. break;
  3182. }
  3183. }
  3184. List<dynamic> objs = new List<dynamic>();
  3185. List<dynamic> wobjs = new List<dynamic>();
  3186. /*if (type.GetInt32() != 1) {
  3187. return Ok(new { attr, paper = info.papers[index].blob });
  3188. }*/
  3189. //List<SDK.Models.Cosmos.Common.Scoring> errs = new();
  3190. //List<SDK.Models.Cosmos.Common.Scoring> arbs = new();
  3191. Correct correct = null;
  3192. var cResponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Correct-{code}"));
  3193. if (cResponse.StatusCode == System.Net.HttpStatusCode.OK)
  3194. {
  3195. using var cJson = await JsonDocument.ParseAsync(cResponse.Content);
  3196. correct = cJson.ToObject<Correct>();
  3197. }
  3198. int finishCount = 0;
  3199. attrSc = [.. attrSc.OrderBy(c => c.stuId)];
  3200. foreach (SDK.Models.Cosmos.Common.Scoring ss in attrSc)
  3201. {
  3202. for (int i = 0; i < correct.num; i++)
  3203. {
  3204. List<double> tsc = new List<double>();
  3205. foreach (Item item in ss.items)
  3206. {
  3207. if (item.scores.Count > 0)
  3208. {
  3209. if (i >= item.scores.Count)
  3210. {
  3211. break;
  3212. }
  3213. else
  3214. {
  3215. tsc.Add(item.scores[i].sc);
  3216. }
  3217. }
  3218. }
  3219. bool flag = tsc.Exists(s => s == -1);
  3220. if (!flag && tsc.Count > 0)
  3221. {
  3222. finishCount++;
  3223. }
  3224. }
  3225. }
  3226. if (attr.Count > 0)
  3227. {
  3228. attr = [.. attr.OrderBy(c => c.stuId)];
  3229. foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
  3230. {
  3231. //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});
  3232. List<dynamic> sc = new List<dynamic>();
  3233. List<dynamic> allSc = new List<dynamic>();
  3234. ss.qs = ss.qs.Where(s => !string.IsNullOrEmpty(s.tId)).ToList();
  3235. int indexScore = 0;
  3236. (string ansBlob, List<double> scores) = await getMoreStuInfo(client, ss.stuId, ss.examId, ss.subjectId, code.GetString());
  3237. foreach (Item item in ss.items)
  3238. {
  3239. var count = item.scores.GroupBy(i => new { i.tmdId, i.sc }).Select(c => c.Key.sc).ToList();
  3240. allSc.Add(count.FirstOrDefault());
  3241. List<double> scc = item.scores.Where(x => x.tmdId.Equals(tId.GetString())).Select(c => c.sc).ToList();
  3242. List<string> blob = item.scores.Where(x => x.tmdId.Equals(tId.GetString())).Select(c => c.mark).ToList();
  3243. //item.scores.Where(x => x.tmdId.Equals(tId.GetString())).SelectMany(p => p.sc, (p, d) => new { });
  3244. if (scc.Count > 0)
  3245. {
  3246. sc.Add(new { sc = scc.FirstOrDefault(), blob = blob.FirstOrDefault(), item.ssc });
  3247. }
  3248. else
  3249. {
  3250. ss.scores = scores;
  3251. sc.Add(new { sc = ss.scores[indexScore], blob = "", item.ssc });
  3252. }
  3253. indexScore++;
  3254. }
  3255. 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 };
  3256. objs.Add(obj);
  3257. }
  3258. }
  3259. else
  3260. {
  3261. if (request.TryGetProperty("stuId", out JsonElement stuId))
  3262. {
  3263. objs = await Review(attrSc, id.GetString(), code.GetString(), subjectId.GetString(), scount.GetInt32(), tId.GetString(), stuId.GetString());
  3264. }
  3265. else
  3266. {
  3267. objs = await Review(attrSc, id.GetString(), code.GetString(), subjectId.GetString(), scount.GetInt32(), tId.GetString(), "");
  3268. }
  3269. }
  3270. var fp = attr.Count > 0 ? Math.Round(finishCount * 1.0 / (attrSc.Count * correct.num), 2) : 0;
  3271. return Ok(new { objs, paper = info.papers[index].blob, fp });
  3272. }
  3273. catch (Exception ex)
  3274. {
  3275. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/scoring\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  3276. return Ok(new { status = 500 });
  3277. }
  3278. }
  3279. //查找异常卷
  3280. [ProducesDefaultResponseType]
  3281. [Authorize(Roles = "IES")]
  3282. [AuthToken(Roles = "teacher,admin")]
  3283. [HttpPost("find-err")]
  3284. public async Task<IActionResult> findErr(JsonElement request)
  3285. {
  3286. //ResponseBuilder builder = ResponseBuilder.custom();
  3287. //var (id, school) = HttpContext.GetAuthTokenInfo();
  3288. try
  3289. {
  3290. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  3291. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  3292. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  3293. //if (!request.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  3294. var client = _azureCosmos.GetCosmosClient();
  3295. var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Exam-{code}"));
  3296. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  3297. {
  3298. using var json = await JsonDocument.ParseAsync(response.Content);
  3299. ExamInfo info = json.ToObject<ExamInfo>();
  3300. //ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  3301. List<ExamClassResult> classResults = new();
  3302. List<SDK.Models.Cosmos.Common.Scoring> attr = new List<SDK.Models.Cosmos.Common.Scoring>();
  3303. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.Common.Scoring>(
  3304. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  3305. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  3306. {
  3307. attr.Add(item);
  3308. }
  3309. int index = 0;
  3310. foreach (ExamSubject subject in info.subjects)
  3311. {
  3312. if (!subject.id.Equals(subjectId.ToString()))
  3313. {
  3314. index++;
  3315. }
  3316. else
  3317. {
  3318. break;
  3319. }
  3320. }
  3321. List<dynamic> objs = new List<dynamic>();
  3322. List<SDK.Models.Cosmos.Common.Scoring> errs = new();
  3323. foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
  3324. {
  3325. List<Qs> qs = ss.qs.Where(s => !string.IsNullOrEmpty(s.err)).ToList();
  3326. if (qs.Count > 0)
  3327. {
  3328. ss.qs = qs;
  3329. errs.Add(ss);
  3330. }
  3331. }
  3332. return Ok(new { errs, paper = info.papers[index].blob });
  3333. }
  3334. else
  3335. {
  3336. return Ok(new { status = response.StatusCode });
  3337. }
  3338. }
  3339. catch (Exception ex)
  3340. {
  3341. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-err\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  3342. return Ok(new { status = 500 });
  3343. }
  3344. }
  3345. [ProducesDefaultResponseType]
  3346. [AuthToken(Roles = "teacher,admin")]
  3347. [HttpPost("find-arb")]
  3348. [Authorize(Roles = "IES")]
  3349. public async Task<IActionResult> findArb(JsonElement request)
  3350. {
  3351. //ResponseBuilder builder = ResponseBuilder.custom();
  3352. //var (id, school) = HttpContext.GetAuthTokenInfo();
  3353. try
  3354. {
  3355. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  3356. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  3357. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  3358. if (!request.TryGetProperty("et", out JsonElement et)) return BadRequest();
  3359. //if (!request.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  3360. var client = _azureCosmos.GetCosmosClient();
  3361. long time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  3362. if (et.GetInt64() > time)
  3363. {
  3364. return Ok(new { msg = "还在进行中", code = 202 });
  3365. }
  3366. ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  3367. List<ExamClassResult> classResults = new();
  3368. List<SDK.Models.Cosmos.Common.Scoring> attr = new List<SDK.Models.Cosmos.Common.Scoring>();
  3369. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.Common.Scoring>(
  3370. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  3371. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  3372. {
  3373. attr.Add(item);
  3374. }
  3375. int index = 0;
  3376. foreach (ExamSubject subject in info.subjects)
  3377. {
  3378. if (!subject.id.Equals(subjectId.ToString()))
  3379. {
  3380. index++;
  3381. }
  3382. else
  3383. {
  3384. break;
  3385. }
  3386. }
  3387. List<dynamic> objs = new List<dynamic>();
  3388. /*if (type.GetInt32() != 1) {
  3389. return Ok(new { attr, paper = info.papers[index].blob });
  3390. }*/
  3391. //List<SDK.Models.Cosmos.Common.Scoring> errs = new();
  3392. List<SDK.Models.Cosmos.Common.Scoring> arbs = new();
  3393. //List<(string id,List<double>)> osc = new List<(string id, List<double>)>();
  3394. foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
  3395. {
  3396. //List<double> original = new List<double>();
  3397. List<Item> arb = ss.items.Where(s => s.flag == false).ToList();
  3398. (string ansBlob, List<double> scores) = await getMoreStuInfo(client, ss.stuId, ss.examId, ss.subjectId, code.GetString());
  3399. ss.blob = ansBlob;
  3400. ss.scores = scores;
  3401. if (arb.Count > 0)
  3402. {
  3403. ss.items = arb;
  3404. arbs.Add(ss);
  3405. }
  3406. }
  3407. 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 });
  3408. }
  3409. catch (Exception ex)
  3410. {
  3411. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-arb\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  3412. return Ok(new { status = 500 });
  3413. }
  3414. }
  3415. //批阅,给老师随机分配阅卷数据,以及查询改老师已有的阅卷数据
  3416. 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)
  3417. {
  3418. //ResponseBuilder builder = ResponseBuilder.custom();
  3419. //var (id, school) = HttpContext.GetAuthTokenInfo();
  3420. try
  3421. {
  3422. var client = _azureCosmos.GetCosmosClient();
  3423. //var redisClient = _azureRedis.GetRedisClient(8);
  3424. List<ExamClassResult> classResults = new();
  3425. List<SDK.Models.Cosmos.Common.Scoring> recs = new();
  3426. List<SDK.Models.Cosmos.Common.Scoring> all = new();
  3427. //List<SDK.Models.Cosmos.Common.Scoring> attr = new();
  3428. /*await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.Common.Scoring>(
  3429. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' ",
  3430. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  3431. {
  3432. attr.Add(item);
  3433. }*/
  3434. foreach (SDK.Models.Cosmos.Common.Scoring scoring in attr)
  3435. {
  3436. if (scoring.tIds.Contains(tId.ToString()))
  3437. {
  3438. recs.Add(scoring);
  3439. }
  3440. else if (scoring.tIds.Count < scoring.count * scoring.model)
  3441. {
  3442. all.Add(scoring);
  3443. }
  3444. }
  3445. if (!string.IsNullOrEmpty(stuId))
  3446. {
  3447. List<SDK.Models.Cosmos.Common.Scoring> value = new();
  3448. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.Common.Scoring>(
  3449. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.stuId = '{stuId}' ",
  3450. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  3451. {
  3452. value.Add(item);
  3453. }
  3454. if (value.Count > 0)
  3455. {
  3456. foreach (SDK.Models.Cosmos.Common.Scoring scoring in value)
  3457. {
  3458. if (scoring.tIds.Contains(tId.ToString()))
  3459. {
  3460. break;
  3461. }
  3462. else
  3463. {
  3464. scoring.tIds.Add(tId.ToString());
  3465. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey(scoring.code));
  3466. }
  3467. }
  3468. }
  3469. List<dynamic> objs = new List<dynamic>();
  3470. List<SDK.Models.Cosmos.Common.Scoring> val = new List<SDK.Models.Cosmos.Common.Scoring>();
  3471. foreach (SDK.Models.Cosmos.Common.Scoring ss in value)
  3472. {
  3473. //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 });
  3474. List<dynamic> sc = new List<dynamic>();
  3475. int indexScore = 0;
  3476. ss.qs = ss.qs.Where(s => !string.IsNullOrEmpty(s.tId)).ToList();
  3477. (string ansBlob, List<double> scores) = await getMoreStuInfo(client, ss.stuId, ss.examId, ss.subjectId, code);
  3478. foreach (Item item in ss.items)
  3479. {
  3480. List<double> scc = item.scores.Where(x => x.tmdId.Equals(tId)).Select(c => c.sc).ToList();
  3481. //item.scores.Where(x => x.tmdId.Equals(tId.GetString())).SelectMany(p => p.sc, (p, d) => new { });
  3482. if (scc.Count > 0)
  3483. {
  3484. sc.Add(new { sc = scc.FirstOrDefault(), item.ssc });
  3485. }
  3486. else
  3487. {
  3488. ss.scores = scores;
  3489. sc.Add(new { sc = ss.scores[indexScore], item.ssc });
  3490. }
  3491. indexScore++;
  3492. }
  3493. 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 };
  3494. objs.Add(obj);
  3495. }
  3496. return objs;
  3497. }
  3498. else
  3499. {
  3500. List<SDK.Models.Cosmos.Common.Scoring> notYet = new();
  3501. notYet = all.Where(x => x.tIds.Count < x.count * x.model - 1).ToList();
  3502. List<dynamic> objs = new List<dynamic>();
  3503. for (int i = 0; i < count; i++)
  3504. {
  3505. Random random = new Random();
  3506. SDK.Models.Cosmos.Common.Scoring item = new();
  3507. if (notYet.Count > 0)
  3508. {
  3509. int index = random.Next(notYet.Count);
  3510. item = notYet[index];
  3511. notYet.RemoveAt(index);
  3512. }
  3513. else
  3514. {
  3515. int index = random.Next(all.Count);
  3516. item = all[index];
  3517. all.RemoveAt(index);
  3518. }
  3519. if (!item.tIds.Contains(tId.ToString()))
  3520. {
  3521. item.tIds.Add(tId.ToString());
  3522. }
  3523. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
  3524. List<dynamic> sc = new List<dynamic>();
  3525. (string ansBlob, List<double> scores) = await getMoreStuInfo(client, item.stuId, item.examId, item.subjectId, code);
  3526. int indexScore = 0;
  3527. item.qs = item.qs.Where(s => !string.IsNullOrEmpty(s.tId)).ToList();
  3528. foreach (Item its in item.items)
  3529. {
  3530. List<double> ssc = its.scores.Where(x => x.tmdId.Equals(tId)).Select(c => c.sc).ToList();
  3531. if (ssc.Count > 0)
  3532. {
  3533. sc.Add(new { sc = ssc.FirstOrDefault(), its.ssc });
  3534. }
  3535. else
  3536. {
  3537. item.scores = scores;
  3538. sc.Add(new { sc = item.scores[indexScore], its.ssc });
  3539. }
  3540. indexScore++;
  3541. }
  3542. 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 };
  3543. objs.Add(obj);
  3544. }
  3545. return objs;
  3546. /*if (recs.Count == count.GetInt32())
  3547. {
  3548. return Ok(new { msg = "分配人数已到上限" });
  3549. }
  3550. else
  3551. {
  3552. if (all.Count == 0)
  3553. {
  3554. return Ok(new { msg = "暂无可选学生" });
  3555. }
  3556. //随机选取一名学生打分
  3557. Random random = new Random();
  3558. SDK.Models.Cosmos.Common.Scoring item = new();
  3559. List<SDK.Models.Cosmos.Common.Scoring> notYet = new();
  3560. notYet = all.Where(x => x.tIds.Count < x.count * x.model - 1).ToList();
  3561. if (notYet.Count > 0)
  3562. {
  3563. item = notYet[random.Next(notYet.Count)];
  3564. }
  3565. else
  3566. {
  3567. item = all[random.Next(all.Count)];
  3568. }
  3569. if (!item.tIds.Contains(tId.ToString()))
  3570. {
  3571. item.tIds.Add(tId.ToString());
  3572. }
  3573. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
  3574. List<dynamic> sc = new List<dynamic>();
  3575. (string ansBlob, List<double> scores) = await getMoreStuInfo(client, item.stuId, item.examId, item.subjectId, code.GetString());
  3576. int indexScore = 0;
  3577. foreach (Item its in item.items)
  3578. {
  3579. List<double> ssc = its.scores.Where(x => x.tmdId.Equals(tId.GetString())).Select(c => c.sc).ToList();
  3580. if (ssc.Count > 0)
  3581. {
  3582. sc.Add(new { sc = ssc.FirstOrDefault(), its.ssc });
  3583. }
  3584. else
  3585. {
  3586. item.scores = scores;
  3587. sc.Add(new { sc = item.scores[indexScore], its.ssc });
  3588. }
  3589. indexScore++;
  3590. }
  3591. 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 };
  3592. return Ok(obj);
  3593. }*/
  3594. }
  3595. }
  3596. catch (Exception ex)
  3597. {
  3598. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/review\n", GroupNames.醍摩豆服務運維群組);
  3599. return new List<dynamic>() { new { code = 404, msg = "分配任务异常" } };
  3600. }
  3601. }
  3602. //批阅 提交分数
  3603. [ProducesDefaultResponseType]
  3604. [AuthToken(Roles = "teacher,admin")]
  3605. [HttpPost("sub-result")]
  3606. [Authorize(Roles = "IES")]
  3607. public async Task<IActionResult> SubResult(JsonElement request)
  3608. {
  3609. //ResponseBuilder builder = ResponseBuilder.custom();
  3610. //var (id, school) = HttpContext.GetAuthTokenInfo();
  3611. try
  3612. {
  3613. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  3614. if (!request.TryGetProperty("stuId", out JsonElement sId)) return BadRequest();
  3615. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  3616. if (!request.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  3617. if (!request.TryGetProperty("score", out JsonElement score)) return BadRequest();
  3618. if (!request.TryGetProperty("count", out JsonElement count)) return BadRequest();
  3619. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  3620. request.TryGetProperty("mark", out JsonElement mark);
  3621. var client = _azureCosmos.GetCosmosClient();
  3622. var (userid, name, _, school) = HttpContext.GetAuthTokenInfo();
  3623. //取得学校基本信息
  3624. var schresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(school.ToString(), new PartitionKey("Base"));
  3625. string schname = string.Empty;
  3626. if (schresponse.StatusCode == System.Net.HttpStatusCode.OK)
  3627. {
  3628. using var schjson = await JsonDocument.ParseAsync(schresponse.Content);
  3629. schjson.RootElement.TryGetProperty("name", out JsonElement jsonschname);
  3630. schname = jsonschname.ToString();
  3631. }
  3632. List<ExamClassResult> classResults = new();
  3633. List<SDK.Models.Cosmos.Common.Scoring> attr = new();
  3634. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.Common.Scoring>(
  3635. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.stuId = '{sId}' and array_contains(c.tIds,'{tId}') ",
  3636. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  3637. {
  3638. attr.Add(item);
  3639. }
  3640. List<double> ssc = score.ToObject<List<double>>();
  3641. List<string> marks = mark.ToObject<List<string>>();
  3642. StringBuilder builder = new();
  3643. if (attr.Count > 0)
  3644. {
  3645. foreach (SDK.Models.Cosmos.Common.Scoring scoring in attr)
  3646. {
  3647. int itemIndex = 0;
  3648. //int tIdIndex = scoring.tIds.IndexOf(tId.GetString());
  3649. if (request.TryGetProperty("qu", out JsonElement qu))
  3650. {
  3651. List<int> nos = qu.ToObject<List<int>>();
  3652. foreach (int number in nos)
  3653. {
  3654. List<Info> items = scoring.items[number].scores.Where(x => x.tmdId.Equals(tId.GetString())).ToList();
  3655. if (items.Count > 0)
  3656. {
  3657. foreach (Info info in items)
  3658. {
  3659. info.sc = ssc[number];
  3660. info.mark = marks.Count > 0 ? marks[number] : "";
  3661. }
  3662. }
  3663. else
  3664. {
  3665. Info info = new();
  3666. info.sc = ssc[number];
  3667. info.tmdId = tId.GetString();
  3668. info.mark = marks.Count > 0 ? marks[number] : "";
  3669. info.index = number;
  3670. scoring.items[number].scores.Add(info);
  3671. }
  3672. }
  3673. }
  3674. else
  3675. {
  3676. foreach (Item item in scoring.items)
  3677. {
  3678. List<Info> items = item.scores.Where(x => x.tmdId.Equals(tId.GetString())).ToList();
  3679. if (items.Count > 0)
  3680. {
  3681. foreach (Info info in items)
  3682. {
  3683. info.sc = ssc[itemIndex];
  3684. info.mark = marks.Count > 0 ? marks[itemIndex] : "";
  3685. }
  3686. }
  3687. else
  3688. {
  3689. if (ssc[itemIndex] >= 0)
  3690. {
  3691. Info info = new();
  3692. info.sc = ssc[itemIndex];
  3693. info.tmdId = tId.GetString();
  3694. info.mark = marks.Count > 0 ? marks[itemIndex] : "";
  3695. info.index = itemIndex;
  3696. item.scores.Add(info);
  3697. }
  3698. }
  3699. itemIndex++;
  3700. }
  3701. }
  3702. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey(scoring.code));
  3703. }
  3704. }
  3705. else
  3706. {
  3707. return BadRequest();
  3708. }
  3709. Correct correct = null;
  3710. var cResponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Correct-{code}"));
  3711. if (cResponse.StatusCode == System.Net.HttpStatusCode.OK)
  3712. {
  3713. using var cJson = await JsonDocument.ParseAsync(cResponse.Content);
  3714. correct = cJson.ToObject<Correct>();
  3715. }
  3716. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamClassResult>(
  3717. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  3718. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
  3719. {
  3720. classResults.Add(item);
  3721. }
  3722. bool isFinish = false;
  3723. int scount = attr.Select(a => a.items[0].scores).ToList().Count;
  3724. foreach (SDK.Models.Cosmos.Common.Scoring sc in attr)
  3725. {
  3726. foreach (var item in sc.items)
  3727. {
  3728. if (item.scores.Count == 0)
  3729. {
  3730. isFinish = false;
  3731. break;
  3732. }
  3733. else
  3734. {
  3735. if (item.scores.Count != correct.num)
  3736. {
  3737. isFinish = false;
  3738. break;
  3739. }
  3740. else
  3741. {
  3742. isFinish = true;
  3743. }
  3744. }
  3745. }
  3746. }
  3747. if (isFinish)
  3748. {
  3749. foreach (ExamClassResult exam in classResults)
  3750. {
  3751. foreach (SDK.Models.Cosmos.Common.Scoring scoring in attr)
  3752. {
  3753. int index = exam.studentIds.IndexOf(scoring.stuId);
  3754. if (index != -1)
  3755. {
  3756. int itemIndex = 0;
  3757. foreach (Item item in scoring.items)
  3758. {
  3759. var ace = item.scores.Where(x => string.IsNullOrEmpty(x.tmdId)).ToList();
  3760. if (ace.Count > 0)
  3761. {
  3762. return Ok(new { code = 1, msg = "用户信息未找到" });
  3763. }
  3764. //判定是否仲裁卷
  3765. if (!item.flag)
  3766. {
  3767. item.isArb = 0;
  3768. string bizcode = "scoring-arb";
  3769. List<string> ids = new List<string>();
  3770. foreach (CorSub sub in correct.subs)
  3771. {
  3772. ids = sub.arb;
  3773. }
  3774. //request.subs.Select(r => r.markers).ToList();
  3775. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey(scoring.code));
  3776. string sql = $"select c.id, c.name ,c.lang as code from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))})";
  3777. List<IdNameCode> idNameCodes = new List<IdNameCode>();
  3778. await foreach (var idNameCode in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  3779. .GetItemQueryIteratorSql<IdNameCode>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  3780. {
  3781. idNameCodes.Add(idNameCode);
  3782. }
  3783. _coreAPIHttpService.PushNotify(idNameCodes, $"{bizcode}_school", Constant.NotifyType_IES5_Task,
  3784. new Dictionary<string, object> { { "tmdname", name }, { "schoolName", schname }, { "schoolId", $"{school}" }, { "tmdid", userid } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
  3785. return Ok(new { msg = "需要仲裁", code = 2 });
  3786. }
  3787. if (item.scores.Count > 0)
  3788. {
  3789. double sc = item.scores.Select(x => x.sc).ToList().Aggregate((i, j) => (i + j) / item.scores.Count);
  3790. scoring.scores[itemIndex] = sc;
  3791. }
  3792. string tmdId = tId.GetString();
  3793. //定位老师是几阅
  3794. int indexOfSc = 0;
  3795. foreach (Info info in item.scores)
  3796. {
  3797. if (info.tmdId.Equals(tmdId))
  3798. {
  3799. break;
  3800. }
  3801. else
  3802. {
  3803. indexOfSc++;
  3804. }
  3805. }
  3806. //判定是否已经存在对应的批注信息
  3807. bool flag = exam.mark[index][itemIndex].Exists(x => x.tmdId.Equals(tmdId));
  3808. if (flag)
  3809. {
  3810. //重复打分更新部分值
  3811. exam.mark[index][itemIndex].Where(x => x.tmdId.Equals(tmdId)).ToList().ForEach(score =>
  3812. {
  3813. score.sc = item.scores[indexOfSc].sc;
  3814. score.mark = item.scores[indexOfSc].mark;
  3815. });
  3816. }
  3817. else
  3818. {
  3819. Details dt = new()
  3820. {
  3821. index = item.scores[indexOfSc].index,
  3822. sc = item.scores[indexOfSc].sc,
  3823. tmdId = item.scores[indexOfSc].tmdId,
  3824. mark = item.scores[indexOfSc].mark,
  3825. identity = item.scores[indexOfSc].identity
  3826. };
  3827. exam.mark[index][itemIndex].Add(dt);
  3828. }
  3829. itemIndex++;
  3830. }
  3831. exam.studentScores[index] = scoring.scores;
  3832. exam.sum[index] = exam.studentScores[index].Sum();
  3833. }
  3834. }
  3835. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
  3836. }
  3837. }
  3838. return Ok(new { code = 200 });
  3839. }
  3840. catch (Exception ex)
  3841. {
  3842. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/sub-result\n", GroupNames.醍摩豆服務運維群組);
  3843. return Ok(new { status = 500 });
  3844. }
  3845. }
  3846. //查询阅卷类型数据
  3847. [ProducesDefaultResponseType]
  3848. [Authorize(Roles = "IES")]
  3849. [AuthToken(Roles = "teacher,admin")]
  3850. [HttpPost("find-scoring")]
  3851. public async Task<IActionResult> findScoring(JsonElement request)
  3852. {
  3853. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  3854. if (!request.TryGetProperty("stuId", out JsonElement sId)) return BadRequest();
  3855. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  3856. if (!request.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  3857. if (!request.TryGetProperty("type", out JsonElement type)) return BadRequest();
  3858. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  3859. var client = _azureCosmos.GetCosmosClient();
  3860. List<SDK.Models.Cosmos.Common.Scoring> attr = new();
  3861. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.Common.Scoring>(
  3862. 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}') ",
  3863. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  3864. {
  3865. attr.Add(item);
  3866. }
  3867. return Ok(attr);
  3868. }
  3869. //申报异常卷内容
  3870. [ProducesDefaultResponseType]
  3871. [AuthToken(Roles = "teacher,admin")]
  3872. [HttpPost("save-err")]
  3873. [Authorize(Roles = "IES")]
  3874. public async Task<IActionResult> saveErr(JsonElement request)
  3875. {
  3876. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  3877. if (!request.TryGetProperty("err", out JsonElement err)) return BadRequest();
  3878. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  3879. if (!request.TryGetProperty("index", out JsonElement index)) return BadRequest();
  3880. if (!request.TryGetProperty("tId", out JsonElement tId)) return BadRequest();
  3881. var client = _azureCosmos.GetCosmosClient();
  3882. var (userid, name, _, school) = HttpContext.GetAuthTokenInfo();
  3883. //取得学校基本信息
  3884. var schresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(school.ToString(), new PartitionKey("Base"));
  3885. string schname = string.Empty;
  3886. if (schresponse.StatusCode == System.Net.HttpStatusCode.OK)
  3887. {
  3888. using var schjson = await JsonDocument.ParseAsync(schresponse.Content);
  3889. schjson.RootElement.TryGetProperty("name", out JsonElement jsonschname);
  3890. schname = jsonschname.ToString();
  3891. }
  3892. SDK.Models.Cosmos.Common.Scoring scoring = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<SDK.Models.Cosmos.Common.Scoring>(id.GetString(), new PartitionKey($"Scoring-{code}"));
  3893. if (null != scoring)
  3894. {
  3895. Correct correct = null;
  3896. var cResponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(scoring.examId, new PartitionKey($"Correct-{code}"));
  3897. if (cResponse.StatusCode == System.Net.HttpStatusCode.OK)
  3898. {
  3899. using var cJson = await JsonDocument.ParseAsync(cResponse.Content);
  3900. correct = cJson.ToObject<Correct>();
  3901. }
  3902. if (string.IsNullOrEmpty(scoring.qs[index.GetInt32()].tId))
  3903. {
  3904. scoring.qs[index.GetInt32()].err = err.GetString();
  3905. scoring.qs[index.GetInt32()].tId = tId.GetString();
  3906. scoring.qs[index.GetInt32()].index = index.GetInt32();
  3907. }
  3908. else
  3909. {
  3910. return Ok(new { msg = "改题已经被申报", code = 404 });
  3911. }
  3912. string bizcode = "scoring-err";
  3913. List<string> ids = new List<string>();
  3914. foreach (CorSub sub in correct.subs)
  3915. {
  3916. ids = sub.err;
  3917. }
  3918. //request.subs.Select(r => r.markers).ToList();
  3919. string sql = $"select c.id, c.name ,c.lang as code from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))})";
  3920. List<IdNameCode> idNameCodes = new List<IdNameCode>();
  3921. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  3922. .GetItemQueryIteratorSql<IdNameCode>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  3923. {
  3924. idNameCodes.Add(item);
  3925. }
  3926. _coreAPIHttpService.PushNotify(idNameCodes, $"{bizcode}_school", Constant.NotifyType_IES5_Task,
  3927. new Dictionary<string, object> { { "tmdname", name }, { "schoolName", schname }, { "schoolId", $"{school}" }, { "tmdid", userid } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
  3928. /* scoring.type = 2;
  3929. scoring.err = err.GetString();*/
  3930. }
  3931. else
  3932. {
  3933. return Ok(new { code = 404 });
  3934. }
  3935. var sc = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey($"{scoring.code}"));
  3936. return Ok(new { sc });
  3937. }
  3938. //处理异常卷内容
  3939. [ProducesDefaultResponseType]
  3940. [Authorize(Roles = "IES")]
  3941. [AuthToken(Roles = "teacher,admin")]
  3942. [HttpPost("fd-err")]
  3943. public async Task<IActionResult> fdErr(JsonElement request)
  3944. {
  3945. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  3946. if (!request.TryGetProperty("improve", out JsonElement improve)) return BadRequest();
  3947. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  3948. if (!request.TryGetProperty("index", out JsonElement index)) return BadRequest();
  3949. //if (!request.TryGetProperty("tId", out JsonElement tId)) return BadRequest();
  3950. var client = _azureCosmos.GetCosmosClient();
  3951. SDK.Models.Cosmos.Common.Scoring scoring = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<SDK.Models.Cosmos.Common.Scoring>(id.GetString(), new PartitionKey($"Scoring-{code}"));
  3952. if (null != scoring)
  3953. {
  3954. if (string.IsNullOrEmpty(scoring.qs[index.GetInt32()].improve))
  3955. {
  3956. scoring.qs[index.GetInt32()].improve = improve.GetString();
  3957. //scoring.qs[index.GetInt32()].tId = tId.GetString();
  3958. //scoring.qs[index.GetInt32()].index = index.GetInt32();
  3959. }
  3960. else
  3961. {
  3962. return Ok(new { msg = "改题已经被处理", code = 404 });
  3963. }
  3964. /* scoring.type = 2;
  3965. scoring.err = err.GetString();*/
  3966. }
  3967. else
  3968. {
  3969. return Ok(new { code = 404 });
  3970. }
  3971. var sc = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey($"{scoring.code}"));
  3972. return Ok(new { sc });
  3973. }
  3974. //处理仲裁卷内容
  3975. [ProducesDefaultResponseType]
  3976. [AuthToken(Roles = "teacher,admin")]
  3977. [HttpPost("save-arb")]
  3978. [Authorize(Roles = "IES")]
  3979. public async Task<IActionResult> saveArb(JsonElement request)
  3980. {
  3981. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  3982. if (!request.TryGetProperty("score", out JsonElement score)) return BadRequest();
  3983. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  3984. if (!request.TryGetProperty("index", out JsonElement indexScore)) return BadRequest();
  3985. var client = _azureCosmos.GetCosmosClient();
  3986. //List<double> scs = score.ToObject<List<double>>();
  3987. List<ExamClassResult> classResults = new();
  3988. int sin = indexScore.GetInt32();
  3989. SDK.Models.Cosmos.Common.Scoring scoring = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<SDK.Models.Cosmos.Common.Scoring>(id.GetString(), new PartitionKey($"Scoring-{code}"));
  3990. if (null != scoring)
  3991. {
  3992. scoring.scores[sin] = score.GetDouble();
  3993. scoring.items[sin].isArb = 1;
  3994. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamClassResult>(
  3995. queryText: $"select value(c) from c where c.examId = '{scoring.examId}' and c.subjectId = '{scoring.subjectId}'",
  3996. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
  3997. {
  3998. classResults.Add(item);
  3999. }
  4000. foreach (ExamClassResult exam in classResults)
  4001. {
  4002. int index = exam.studentIds.IndexOf(scoring.stuId);
  4003. if (index != -1)
  4004. {
  4005. exam.studentScores[index][sin] = score.GetDouble();
  4006. //exam.mark[index] = scoring.marks;
  4007. }
  4008. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
  4009. }
  4010. }
  4011. else
  4012. {
  4013. return Ok(new { code = 404 });
  4014. }
  4015. var sc = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey($"{scoring.code}"));
  4016. return Ok(new { sc });
  4017. }
  4018. [ProducesDefaultResponseType]
  4019. [AuthToken(Roles = "teacher,admin,student")]
  4020. [HttpPost("score")]
  4021. [Authorize(Roles = "IES")]
  4022. public async Task<IActionResult> score(JsonElement request)
  4023. {
  4024. if (!request.TryGetProperty("courseId", out JsonElement courseId)) return BadRequest();
  4025. if (!request.TryGetProperty("cId", out JsonElement cId)) return BadRequest();
  4026. //if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  4027. var client = _azureCosmos.GetCosmosClient();
  4028. List<(string eId, string cId, string cname, List<string> sIds, List<double> sum)> classResults = new();
  4029. List<string> eIds = new();
  4030. List<string> cIds = cId.ToObject<List<string>>();
  4031. string soc = courseId.GetString();
  4032. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(
  4033. 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}'"))})"))
  4034. {
  4035. using var json = await JsonDocument.ParseAsync(item.Content);
  4036. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  4037. {
  4038. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  4039. while (accounts.MoveNext())
  4040. {
  4041. JsonElement account = accounts.Current;
  4042. List<string> sIds = account.GetProperty("studentIds").ToObject<List<string>>();
  4043. List<double> sum = account.GetProperty("sum").ToObject<List<double>>();
  4044. eIds.Add(account.GetProperty("eId").GetString());
  4045. List<double> nsum = new();
  4046. foreach (double s in sum)
  4047. {
  4048. double ns = 0;
  4049. if (s < 0)
  4050. {
  4051. ns = 0;
  4052. }
  4053. else
  4054. {
  4055. ns = s;
  4056. }
  4057. nsum.Add(ns);
  4058. }
  4059. classResults.Add((account.GetProperty("eId").GetString(), account.GetProperty("cId").GetString(), account.GetProperty("cName").GetString(), sIds, nsum));
  4060. }
  4061. }
  4062. }
  4063. string sub = string.Empty;
  4064. if (request.TryGetProperty("subjectId", out JsonElement subjectId))
  4065. {
  4066. sub = subjectId.GetString();
  4067. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(
  4068. 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}'"))})"))
  4069. {
  4070. using var json = await JsonDocument.ParseAsync(item.Content);
  4071. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  4072. {
  4073. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  4074. while (accounts.MoveNext())
  4075. {
  4076. JsonElement account = accounts.Current;
  4077. List<string> sIds = account.GetProperty("studentIds").ToObject<List<string>>();
  4078. List<double> sum = account.GetProperty("sum").ToObject<List<double>>();
  4079. List<double> nsum = new();
  4080. foreach (double s in sum)
  4081. {
  4082. double ns = 0;
  4083. if (s < 0)
  4084. {
  4085. ns = 0;
  4086. }
  4087. else
  4088. {
  4089. ns = s;
  4090. }
  4091. nsum.Add(ns);
  4092. }
  4093. eIds.Add(account.GetProperty("eId").GetString());
  4094. classResults.Add((account.GetProperty("eId").GetString(), account.GetProperty("cId").GetString(), account.GetProperty("cName").GetString(), sIds, nsum));
  4095. }
  4096. }
  4097. }
  4098. }
  4099. 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();
  4100. if (eIds.Count == 0)
  4101. {
  4102. return Ok(new { code = 404 });
  4103. }
  4104. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(
  4105. 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}'"))})"))
  4106. {
  4107. using var json = await JsonDocument.ParseAsync(item.Content);
  4108. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  4109. {
  4110. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  4111. while (accounts.MoveNext())
  4112. {
  4113. JsonElement account = accounts.Current;
  4114. SDK.Models.Custom eType = new();
  4115. List<ExamSubject> subs = new();
  4116. List<PaperSimple> ps = new();
  4117. if (account.TryGetProperty("examType", out JsonElement examType))
  4118. {
  4119. eType = examType.ToObject<SDK.Models.Custom>();
  4120. }
  4121. if (account.TryGetProperty("papers", out JsonElement papers))
  4122. {
  4123. ps = papers.ToObject<List<PaperSimple>>();
  4124. }
  4125. if (account.TryGetProperty("subjects", out JsonElement subject))
  4126. {
  4127. subs = subject.ToObject<List<ExamSubject>>();
  4128. }
  4129. exam.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString(), eType, account.GetProperty("scope").GetString(),
  4130. account.GetProperty("owner").GetString(), account.GetProperty("createTime").GetInt64(), ps, subs, account.GetProperty("source").GetString()));
  4131. }
  4132. }
  4133. }
  4134. var scores = classResults.Select(x => new
  4135. {
  4136. examId = x.eId,
  4137. examName = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().name,
  4138. scope = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().scope,
  4139. eType = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().eType,
  4140. classId = x.cId,
  4141. cname = x.cname,
  4142. studentIds = x.sIds,
  4143. source = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().source,
  4144. owner = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().owner,
  4145. createTime = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().ctime,
  4146. subject = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().subject,
  4147. papers = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().points,
  4148. sum = x.sum
  4149. });
  4150. if (request.TryGetProperty("stuId", out JsonElement stuId))
  4151. {
  4152. var info = scores.Where(x => !string.IsNullOrEmpty(x.examName) && x.studentIds.Contains(stuId.GetString())).Select(x => new
  4153. {
  4154. x.examId,
  4155. x.examName,
  4156. x.cname,
  4157. studentId = stuId.GetString(),
  4158. x.owner,
  4159. x.createTime,
  4160. x.eType,
  4161. x.source,
  4162. point = x.papers.Select(p => p.point),
  4163. x.subject,
  4164. sum = x.sum.ToList()[x.studentIds.IndexOf(stuId.GetString())]
  4165. });
  4166. return Ok(new { info });
  4167. }
  4168. else
  4169. {
  4170. var info = scores.Where(x => !string.IsNullOrEmpty(x.examName)).Select(x => new
  4171. {
  4172. x.examId,
  4173. x.examName,
  4174. x.cname,
  4175. x.studentIds,
  4176. x.owner,
  4177. x.createTime,
  4178. x.eType,
  4179. x.source,
  4180. point = x.papers.Select(p => p.point),
  4181. x.subject,
  4182. x.sum
  4183. });
  4184. return Ok(new { info });
  4185. };
  4186. }
  4187. [ProducesDefaultResponseType]
  4188. [Authorize(Roles = "IES")]
  4189. [AuthToken(Roles = "teacher,admin,student")]
  4190. [HttpPost("get-error-item")]
  4191. public async Task<IActionResult> getErrorItems(JsonElement request)
  4192. {
  4193. //stuId
  4194. if (!request.TryGetProperty("stuId", out JsonElement stuId)) return BadRequest();
  4195. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  4196. StringBuilder stringBuilder = new($"select value(c) from c where c.stuId = '{stuId}' and c.subjectId = '{subjectId}'");
  4197. /*if (request.TryGetProperty("period", out JsonElement period) && !string.IsNullOrWhiteSpace($"{period}"))
  4198. {
  4199. stringBuilder.Append($" and c.period.id = '{period}' ");
  4200. }
  4201. if (request.TryGetProperty("name", out JsonElement name) && !string.IsNullOrWhiteSpace($"{name}"))
  4202. {
  4203. stringBuilder.Append($" and Contains( c.name , '{name}') = true ");
  4204. }
  4205. if (request.TryGetProperty("progress", out JsonElement progress) && !string.IsNullOrWhiteSpace($"{progress}"))
  4206. {
  4207. stringBuilder.Append($" and c.progress = '{progress}' ");
  4208. }
  4209. if (request.TryGetProperty("source", out JsonElement source) && !string.IsNullOrWhiteSpace($"{source}"))
  4210. {
  4211. stringBuilder.Append($" and c.source = '{source}' ");
  4212. }*/
  4213. string pk = "ErrorItems";
  4214. if (request.TryGetProperty("code", out JsonElement code) && !string.IsNullOrWhiteSpace($"{code}"))
  4215. {
  4216. stringBuilder.Append($" and c.school = '{code}' ");
  4217. pk = $"ErrorItems-{code}";
  4218. };
  4219. stringBuilder.Append("order by c._ts desc");
  4220. //string token = null;
  4221. string token = default;
  4222. //默认不指定返回大小
  4223. int? topcout = null;
  4224. if (request.TryGetProperty("count", out JsonElement jcount))
  4225. {
  4226. if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
  4227. {
  4228. topcout = data;
  4229. }
  4230. }
  4231. //是否需要进行分页查询,默认不分页
  4232. bool iscontinuation = false;
  4233. if (topcout != null && topcout.Value > 0)
  4234. {
  4235. iscontinuation = true;
  4236. }
  4237. //如果指定了返回大小
  4238. if (request.TryGetProperty("token", out JsonElement token_1))
  4239. {
  4240. if (!token_1.ValueKind.Equals(JsonValueKind.Null) && token_1.ValueKind.Equals(JsonValueKind.String))
  4241. {
  4242. token = token_1.GetString();
  4243. }
  4244. }
  4245. try
  4246. {
  4247. var client = _azureCosmos.GetCosmosClient();
  4248. //var queryTeacher = $"select value(c) from c where c.stuId = '{stuId}' and c.school = '{code}' and c.subjectId = '{subjectId}'";
  4249. List<ErrorItems> errorItems = new();
  4250. List<string> ids = new();
  4251. 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}") }))
  4252. {
  4253. using var json = await JsonDocument.ParseAsync(item.Content);
  4254. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  4255. {
  4256. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  4257. {
  4258. ids.Add(obj.GetProperty("id").ToString());
  4259. }
  4260. }
  4261. }
  4262. 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}") }))
  4263. {
  4264. using var json = await JsonDocument.ParseAsync(item.Content);
  4265. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  4266. {
  4267. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  4268. {
  4269. errorItems.Add(obj.ToObject<ErrorItems>());
  4270. }
  4271. }
  4272. if (iscontinuation)
  4273. {
  4274. token = item.ContinuationToken;
  4275. break;
  4276. }
  4277. }
  4278. errorItems = errorItems.Where((x, i) => errorItems.FindIndex(z => z.id == x.id) == i).ToList();
  4279. return Ok(new { errorItems, token, ids.Count });
  4280. }
  4281. catch (Exception ex)
  4282. {
  4283. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/get-error-item()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  4284. return BadRequest(new { code = 500 });
  4285. }
  4286. }
  4287. //取得錯題庫前日錯題數及現在錯題數
  4288. [ProducesDefaultResponseType]
  4289. [Authorize(Roles = "IES")]
  4290. [AuthToken(Roles = "teacher,admin,student")]
  4291. [HttpPost("get-error-item-cnt")]
  4292. public async Task<IActionResult> getErrorItemsCount(JsonElement request)
  4293. {
  4294. //輸入值
  4295. if (!request.TryGetProperty("stuId", out JsonElement stuId)) return BadRequest();
  4296. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  4297. string code = (request.TryGetProperty("code", out JsonElement codeJobj)) ? codeJobj.GetString() : string.Empty;
  4298. string schCode = (!string.IsNullOrWhiteSpace(code)) ? code : "noschoolid";
  4299. string teacherid = (request.TryGetProperty("teacherId", out JsonElement teacherId)) ? teacherId.GetString() : string.Empty;
  4300. //取得Redis該學生該科目的錯題數 [算法變更,昨日錯題總數不再計入redis]
  4301. int record = 0; //昨日取得的錯題數
  4302. //var redisClient = _azureRedis.GetRedisClient(8);
  4303. //string hkey = $"ErrorItems:{schCode}";
  4304. //string hval = await redisClient.HashGetAsync(hkey, $"{stuId}");
  4305. //List<stuErrorItemCnt> stuErrCntList = (hval != null) ? JsonSerializer.Deserialize<List<stuErrorItemCnt>>(hval) : new List<stuErrorItemCnt>();
  4306. //stuErrorItemCnt stuErrCnt = stuErrCntList.Where(s => s.subjectId.Equals($"{subjectId}")).FirstOrDefault();
  4307. //if (stuErrCnt != null)
  4308. //{
  4309. // record = stuErrCnt.number;
  4310. //}
  4311. //取得CosmosDB該學生該科目現在錯題數
  4312. HashSet<string> avaliableQidList = new HashSet<string>(); //最終去重後可取得的錯題ID
  4313. List<string> itemIdList = new List<string>();
  4314. var client = _azureCosmos.GetCosmosClient();
  4315. string qryAdd = (!string.IsNullOrWhiteSpace(code)) ? $" AND c.school = '{code}' " : string.Empty;
  4316. //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";
  4317. string pk = "ErrorItems";
  4318. //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 " +
  4319. // $"c.stuId = '{stuId}' AND c.subjectId = '{subjectId}'{qryAdd} ";
  4320. 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 " +
  4321. $" c.stuId = '{stuId}' AND c.subjectId = '{subjectId}' {qryAdd} ";
  4322. if (!string.IsNullOrWhiteSpace(code))
  4323. {
  4324. //qry += $"AND c.school = '{code}' ";
  4325. pk = $"ErrorItems-{code}";
  4326. };
  4327. Dictionary<string, List<string>> dict = new();
  4328. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIteratorSql(queryText: qry, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{pk}") }))
  4329. {
  4330. using var json = await JsonDocument.ParseAsync(item.Content);
  4331. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  4332. {
  4333. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  4334. {
  4335. if (dict.ContainsKey(obj.GetProperty("id").ToString()))
  4336. {
  4337. if (!dict[obj.GetProperty("id").ToString()].Contains(obj.GetProperty("blob").ToString()))
  4338. {
  4339. dict[obj.GetProperty("id").ToString()].Add(obj.GetProperty("blob").ToString());
  4340. }
  4341. }
  4342. else
  4343. {
  4344. dict.Add(obj.GetProperty("id").ToString(), new List<string> { obj.GetProperty("blob").ToString() });
  4345. }
  4346. }
  4347. }
  4348. }
  4349. foreach (var obj in dict)
  4350. {
  4351. if (schCode != null && schCode != "noschoolid")
  4352. {
  4353. string qid = obj.Key;
  4354. List<string> blobs = obj.Value;
  4355. foreach (string blob in blobs)
  4356. {
  4357. if (_azureStorage.GetBlobContainerClient(schCode).GetBlobClient($"{blob}/{qid}.json").Exists())
  4358. {// 去除blob不存在項目
  4359. avaliableQidList.Add(qid);
  4360. }
  4361. }
  4362. }
  4363. else if (!string.IsNullOrWhiteSpace(teacherid))
  4364. {
  4365. string qid = obj.Key;
  4366. List<string> blobs = obj.Value;
  4367. foreach (string blob in blobs)
  4368. {
  4369. if (_azureStorage.GetBlobContainerClient(teacherid).GetBlobClient($"{blob}/{qid}.json").Exists())
  4370. {
  4371. avaliableQidList.Add(qid);
  4372. }
  4373. }
  4374. }
  4375. }
  4376. return Ok(new { record, avaliable = avaliableQidList.Count });
  4377. }
  4378. //取得錯題庫新增數
  4379. [ProducesDefaultResponseType]
  4380. [Authorize(Roles = "IES")]
  4381. [AuthToken(Roles = "teacher,admin,student")]
  4382. [HttpPost("get-error-item-today-cnt")]
  4383. public async Task<IActionResult> getErrorItemsTodayCount(JsonElement request)
  4384. {
  4385. //輸入值
  4386. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest(); //科目ID
  4387. if (!request.TryGetProperty("stuId", out JsonElement _stuId)) return BadRequest(); //學生ID 或 TMID
  4388. string stuId = _stuId.GetString();
  4389. string schoolid = (request.TryGetProperty("code", out JsonElement codeJobj)) ? codeJobj.GetString() : string.Empty; //學校簡碼,TMID時為空
  4390. string tmdid = string.Empty;
  4391. if (string.IsNullOrWhiteSpace(schoolid)) tmdid = stuId;
  4392. string maLearnCode = string.Empty;
  4393. //檢查參數 必須有 teammodelId 或是同時有學校id及學號
  4394. if (!string.IsNullOrWhiteSpace(tmdid + ""))
  4395. {
  4396. maLearnCode = $"MaLearn-{tmdid}";
  4397. }
  4398. else if (!string.IsNullOrWhiteSpace(schoolid + "") && !string.IsNullOrWhiteSpace(stuId + ""))
  4399. {
  4400. maLearnCode = $"MaLearn-{schoolid}-{stuId}";
  4401. }
  4402. else { return BadRequest(); }
  4403. DateTime nowDate = DateTime.Now;
  4404. DateTime beforeDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
  4405. 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)}";
  4406. 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)} ";
  4407. var client = _azureCosmos.GetCosmosClient();
  4408. int avaliable = 0;
  4409. int allNum = 0;
  4410. int berforeNum = 0;
  4411. // 取全部錯題數量
  4412. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIteratorSql(queryText: qry_All, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{maLearnCode}") }))
  4413. {
  4414. using var json = await JsonDocument.ParseAsync(item.Content);
  4415. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  4416. {
  4417. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  4418. {
  4419. if (obj.TryGetProperty("num", out JsonElement num))
  4420. {
  4421. allNum = num.GetInt32();
  4422. }
  4423. }
  4424. }
  4425. }
  4426. // 取今天之前錯題的數量
  4427. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIteratorSql(queryText: qry_before, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{maLearnCode}") }))
  4428. {
  4429. using var json = await JsonDocument.ParseAsync(item.Content);
  4430. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  4431. {
  4432. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  4433. {
  4434. if (obj.TryGetProperty("num", out JsonElement num))
  4435. {
  4436. berforeNum = num.GetInt32();
  4437. }
  4438. }
  4439. }
  4440. }
  4441. avaliable = allNum - berforeNum;
  4442. return Ok(new { avaliable });
  4443. }
  4444. //阅卷信息统计
  4445. [ProducesDefaultResponseType]
  4446. [Authorize(Roles = "IES")]
  4447. [AuthToken(Roles = "teacher,admin")]
  4448. [HttpPost("analysis-scoring")]
  4449. public async Task<IActionResult> Analysis(JsonElement request)
  4450. {
  4451. try
  4452. {
  4453. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  4454. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  4455. //if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  4456. //if (!request.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  4457. var client = _azureCosmos.GetCosmosClient();
  4458. var queryTeacher = $"select c.id,c.name from c ";
  4459. //List<object> props = new List<object>();
  4460. List<(string id, string name)> tInfos = new();
  4461. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIteratorSql(queryText: queryTeacher, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  4462. {
  4463. using var json = await JsonDocument.ParseAsync(item.Content);
  4464. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  4465. {
  4466. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  4467. {
  4468. tInfos.Add((obj.GetProperty("id").GetString(), obj.GetProperty("name").GetString()));
  4469. }
  4470. }
  4471. }
  4472. var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Exam-{code}"));
  4473. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  4474. {
  4475. using var json = await JsonDocument.ParseAsync(response.Content);
  4476. ExamInfo info = json.ToObject<ExamInfo>();
  4477. List<ExamClassResult> classResults = new();
  4478. List<SDK.Models.Cosmos.Common.Scoring> attr = new List<SDK.Models.Cosmos.Common.Scoring>();
  4479. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.Common.Scoring>(
  4480. queryText: $"select value(c) from c where c.examId = '{id}' ",
  4481. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  4482. {
  4483. attr.Add(item);
  4484. }
  4485. List<SDK.Models.Cosmos.Common.Scoring> errs = new();
  4486. List<(string subjectId, int count)> ps = new List<(string subjectId, int count)>();
  4487. List<(string subjectId, int count)> tps = new List<(string subjectId, int count)>();
  4488. List<(string subjectId, int count)> arbs = new List<(string subjectId, int count)>();
  4489. List<(string subjectId, int count)> tarbs = new List<(string subjectId, int count)>();
  4490. List<(string subjectId, int count)> cs = new List<(string subjectId, int count)>();
  4491. foreach (ExamSubject subject in info.subjects)
  4492. {
  4493. int qsCount = 0;
  4494. int tqsCount = 0;
  4495. int arbCount = 0;
  4496. int tarbCount = 0;
  4497. int csCount = 0;
  4498. foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
  4499. {
  4500. if (subject.id.Equals(ss.subjectId))
  4501. {
  4502. List<Qs> qs = ss.qs.Where(s => !string.IsNullOrEmpty(s.err)).ToList();
  4503. if (qs.Count > 0)
  4504. {
  4505. qsCount++;
  4506. }
  4507. List<Qs> tqs = ss.qs.Where(s => !string.IsNullOrEmpty(s.improve)).ToList();
  4508. if (tqs.Count > 0)
  4509. {
  4510. tqsCount++;
  4511. }
  4512. List<Item> arb = ss.items.Where(s => s.flag == false).ToList();
  4513. if (arb.Count > 0)
  4514. {
  4515. arbCount++;
  4516. }
  4517. List<Item> tarb = ss.items.Where(s => s.isArb == 1 && s.flag == false).ToList();
  4518. if (tarb.Count > 0)
  4519. {
  4520. tarbCount++;
  4521. }
  4522. bool flag = ss.scores.Exists(s => s == -1);
  4523. if (!flag) csCount++;
  4524. }
  4525. }
  4526. ps.Add((subject.id, qsCount));
  4527. tps.Add((subject.id, tqsCount));
  4528. arbs.Add((subject.id, arbCount));
  4529. tarbs.Add((subject.id, tarbCount));
  4530. cs.Add((subject.id, csCount));
  4531. }
  4532. //阅卷老师
  4533. List<object> teachers = new();
  4534. Correct correct = null;
  4535. List<(string sub, List<string> ids)> errIds = new();
  4536. List<(string sub, List<string> ids)> arbIds = new();
  4537. var cResponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Correct-{code}"));
  4538. if (cResponse.StatusCode == System.Net.HttpStatusCode.OK)
  4539. {
  4540. using var cJson = await JsonDocument.ParseAsync(cResponse.Content);
  4541. correct = cJson.ToObject<Correct>();
  4542. foreach (CorSub corSub in correct.subs)
  4543. {
  4544. List<string> eName = new();
  4545. List<string> aName = new();
  4546. foreach (string s in corSub.err)
  4547. {
  4548. eName.Add(tInfos.Where(t => t.id.Equals(s)).Select(s => s.name).First());
  4549. }
  4550. foreach (string s in corSub.arb)
  4551. {
  4552. aName.Add(tInfos.Where(t => t.id.Equals(s)).Select(s => s.name).First());
  4553. }
  4554. errIds.Add((corSub.id, eName));
  4555. arbIds.Add((corSub.id, aName));
  4556. foreach (CorTmd corTmd in corSub.markers)
  4557. {
  4558. int qus = 0;
  4559. int quf = 0;
  4560. int tArbs = 0;
  4561. int fArbs = 0;
  4562. int sCount = 0;
  4563. int fCount = 0;
  4564. foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
  4565. {
  4566. if (ss.subjectId.Equals(corSub.id))
  4567. {
  4568. foreach (Qs qs in ss.qs)
  4569. {
  4570. if (!string.IsNullOrEmpty(qs.err) && qs.tId.Equals(corTmd.id))
  4571. {
  4572. qus++;
  4573. }
  4574. if (!string.IsNullOrEmpty(qs.improve) && qs.tId.Equals(corTmd.id))
  4575. {
  4576. quf++;
  4577. }
  4578. }
  4579. List<double> sigles = new();
  4580. foreach (Item item in ss.items)
  4581. {
  4582. if (item.scores.Exists(sc => sc.tmdId.Equals(corTmd.id)) && item.isArb == 1)
  4583. {
  4584. tArbs++;
  4585. }
  4586. if (item.flag == true && item.isArb == 1)
  4587. {
  4588. fArbs++;
  4589. }
  4590. var tsc = item.scores.Where(t => t.tmdId.Equals(corTmd.id)).Select(s => s.sc).ToList();
  4591. sigles.AddRange(tsc);
  4592. }
  4593. bool flag = sigles.Exists(s => s == -1);
  4594. if (!flag && sigles.Count == ss.items.Count)
  4595. {
  4596. fCount++;
  4597. }
  4598. sCount = corTmd.count;
  4599. }
  4600. }
  4601. var obj = new
  4602. {
  4603. sId = corSub.id,
  4604. sName = corSub.name,
  4605. name = corTmd.name,
  4606. qus,
  4607. quf,
  4608. tArbs,
  4609. fArbs,
  4610. fCount,
  4611. sCount,
  4612. };
  4613. teachers.Add(obj);
  4614. }
  4615. }
  4616. }
  4617. var sc = info.subjects.Select(s => new
  4618. {
  4619. s.name,
  4620. count = info.stuCount,
  4621. num = info.stuCount * correct.num,
  4622. tqs = tps.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First(),
  4623. qs = ps.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First(),
  4624. errName = errIds.Where(q => q.sub.Equals(s.id)).Select(c => c.ids).FirstOrDefault(),
  4625. tarbs = tarbs.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First(),
  4626. arbs = arbs.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First(),
  4627. arbName = arbIds.Where(q => q.sub.Equals(s.id)).Select(c => c.ids).FirstOrDefault(),
  4628. cs = cs.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First()
  4629. }); ;
  4630. return Ok(new { sc, teachers });
  4631. }
  4632. else
  4633. {
  4634. return Ok(new { status = response.StatusCode });
  4635. }
  4636. }
  4637. catch (Exception ex)
  4638. {
  4639. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/analysis-scoring\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  4640. return Ok(new { status = 500 });
  4641. }
  4642. }
  4643. /*private async Task deleteAsync(CosmosClient client, string id, string tId)
  4644. {
  4645. List<string> correctIds = new List<string>();
  4646. 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}") }))
  4647. {
  4648. using var jsonTask = await JsonDocument.ParseAsync(item.Content);
  4649. if (jsonTask.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  4650. {
  4651. var accounts = jsonTask.RootElement.GetProperty("Documents").EnumerateArray();
  4652. while (accounts.MoveNext())
  4653. {
  4654. JsonElement account = accounts.Current;
  4655. correctIds.Add(account.GetProperty("id").GetString());
  4656. }
  4657. }
  4658. }
  4659. if (correctIds.Count > 0)
  4660. {
  4661. await client.GetContainer(Constant.TEAMModelOS, "Teacher").DeleteItemsStreamAsync(correctIds, $"CorrectTask-{tId}");
  4662. }
  4663. }*/
  4664. private async Task<(string blob, List<double>)> getMoreStuInfo(CosmosClient client, string stuId, string examId, string subjectId, string code)
  4665. {
  4666. 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}'";
  4667. List<List<string>> ans = new List<List<string>>();
  4668. List<string> ids = new List<string>();
  4669. List<List<double>> scs = new List<List<double>>();
  4670. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: queryClass, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
  4671. {
  4672. using var json = await JsonDocument.ParseAsync(item.Content);
  4673. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  4674. {
  4675. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  4676. while (accounts.MoveNext())
  4677. {
  4678. JsonElement account = accounts.Current;
  4679. ans = account.GetProperty("studentAnswers").ToObject<List<List<string>>>();
  4680. ids = account.GetProperty("studentIds").ToObject<List<string>>();
  4681. scs = account.GetProperty("studentScores").ToObject<List<List<double>>>();
  4682. }
  4683. }
  4684. }
  4685. int num = ids.IndexOf(stuId);
  4686. string ansBlob = "";
  4687. List<double> scores = new List<double>();
  4688. if (num >= 0)
  4689. {
  4690. if (ans[num].Count > 0)
  4691. {
  4692. ansBlob = ans[num].First();
  4693. }
  4694. scores = scs[num];
  4695. }
  4696. return (ansBlob, scores);
  4697. }
  4698. private Task<List<double>> getWrongNum(ExamResult result, List<double> points, List<string> infoIds)
  4699. {
  4700. int num = 0;
  4701. List<double> wn = new List<double>();
  4702. foreach (var point in points)
  4703. {
  4704. int wnum = 0;
  4705. double p = point * 0.8;
  4706. foreach (ClassRange range in result.classes)
  4707. {
  4708. if (!infoIds.Contains(range.id)) continue;
  4709. for (int i = range.range[0]; i <= range.range[1]; i++)
  4710. {
  4711. //判断推送的数据中,学生正常得分数据
  4712. if (result.studentScores[i].Count > 0)
  4713. {
  4714. if (result.studentScores[i][num] < point)
  4715. {
  4716. if (result.studentScores[i][num] < p)
  4717. {
  4718. wnum++;
  4719. }
  4720. else
  4721. {
  4722. continue;
  4723. }
  4724. }
  4725. else
  4726. {
  4727. continue;
  4728. }
  4729. }
  4730. else
  4731. {
  4732. wnum++;
  4733. }
  4734. }
  4735. }
  4736. wn.Add(wnum);
  4737. num++;
  4738. }
  4739. return Task.FromResult(wn);
  4740. }
  4741. //获取题目信息
  4742. [ProducesDefaultResponseType]
  4743. //[AuthToken(Roles = "teacher,admin,student")]
  4744. [HttpPost("get-item")]
  4745. //[Authorize(Roles = "IES")]
  4746. public async Task<IActionResult> getItemInfo(JsonElement request)
  4747. {
  4748. if (!request.TryGetProperty("errorItems", out JsonElement items)) return BadRequest();
  4749. List<errorItemInfo> errors = items.ToObject<List<errorItemInfo>>();
  4750. var client = _azureCosmos.GetCosmosClient();
  4751. List<string> ids = errors.Select(c => c.activityId).Distinct().ToList();
  4752. var queryClass = $"select value(c) from c where c.id in ({string.Join(",", ids.Select(o => $"'{o}'"))}) and c.pk = 'Exam'";
  4753. List<ExamInfo> exams = new();
  4754. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamInfo>(queryText: queryClass))
  4755. {
  4756. exams.Add(item);
  4757. }
  4758. List<(JsonElement items, List<string> attachments, int qamode)> elements = new();
  4759. if (exams.Count > 0)
  4760. {
  4761. foreach (errorItemInfo itemInfo in errors)
  4762. {
  4763. ExamInfo info = exams.Where(c => c.id.Equals(itemInfo.activityId)).FirstOrDefault();
  4764. if (info == null) continue; //[Jeff]無法取得評量紀錄報錯bug修正
  4765. List<ExamSubject> subjects = info.subjects;
  4766. int index = 0;
  4767. foreach (ExamSubject subject in subjects)
  4768. {
  4769. if (subject.id.Equals(itemInfo.unitId))
  4770. {
  4771. continue;
  4772. }
  4773. else
  4774. {
  4775. index++;
  4776. }
  4777. }
  4778. List<PaperSimple> simples = info.papers;
  4779. string blob = simples[index].blob;
  4780. try
  4781. {
  4782. List<string> attachments = new();
  4783. int qamode = info.qamode;
  4784. BlobDownloadResult index_json;
  4785. if (info.scope.Equals("school"))
  4786. {
  4787. index_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{blob}/index.json").DownloadContentAsync();
  4788. }
  4789. else
  4790. {
  4791. index_json = await _azureStorage.GetBlobContainerClient($"{info.creatorId}").GetBlobClient($"{blob}/index.json").DownloadContentAsync();
  4792. }
  4793. JsonElement RecordingJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(index_json.Content.ToString()))).RootElement;
  4794. if (RecordingJson.TryGetProperty("attachments", out JsonElement _attachments))
  4795. {
  4796. attachments = _attachments.ToObject<List<string>>();
  4797. }
  4798. //attachments = RecordingJson.GetProperty("attachments").ToObject<List<string>>();
  4799. if (RecordingJson.TryGetProperty("qamode", out JsonElement element))
  4800. {
  4801. qamode = element.GetInt32();
  4802. }
  4803. BlobDownloadResult index_item_json;
  4804. if (info.scope.Equals("school"))
  4805. {
  4806. index_item_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{blob}/{itemInfo.qId}.json").DownloadContentAsync();
  4807. }
  4808. else
  4809. {
  4810. index_item_json = await _azureStorage.GetBlobContainerClient($"{info.creatorId}").GetBlobClient($"{blob}/{itemInfo.qId}.json").DownloadContentAsync();
  4811. }
  4812. JsonElement itemJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(index_item_json.Content.ToString()))).RootElement;
  4813. elements.Add((itemJson, attachments, qamode));
  4814. if (itemJson.TryGetProperty("pid", out JsonElement pid))
  4815. {
  4816. if (!string.IsNullOrEmpty(pid.ToString()))
  4817. {
  4818. BlobDownloadResult index_pid_item_json;
  4819. if (info.scope.Equals("school"))
  4820. {
  4821. index_pid_item_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{blob}/{pid}.json").DownloadContentAsync();
  4822. }
  4823. else
  4824. {
  4825. index_pid_item_json = await _azureStorage.GetBlobContainerClient($"{info.creatorId}").GetBlobClient($"{blob}/{pid}.json").DownloadContentAsync();
  4826. }
  4827. JsonElement pidJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(index_pid_item_json.Content.ToString()))).RootElement;
  4828. elements.Add((pidJson, attachments, qamode));
  4829. }
  4830. }
  4831. }
  4832. catch (Exception e)
  4833. {
  4834. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/get-item\n{e.Message}\n{e.StackTrace}\n{info.id}", GroupNames.成都开发測試群組);
  4835. continue;
  4836. //return BadRequest(new { msg = "blob 文件读取异常" });
  4837. }
  4838. }
  4839. }
  4840. else
  4841. {
  4842. var values = elements.Select(c => new
  4843. {
  4844. c.items,
  4845. c.attachments,
  4846. c.qamode
  4847. });
  4848. return Ok(new { error = values });
  4849. }
  4850. var error = elements.Select(c => new
  4851. {
  4852. c.items,
  4853. c.attachments,
  4854. c.qamode
  4855. });
  4856. return Ok(new { error });
  4857. }
  4858. //記入班級評量結果批改結果 ※目前只套用統測結果批改ReadItemAsync
  4859. private async Task upsertExamClassResultMark(ExamClassResult examClassResult, string userId, string userName, List<stus> students, List<List<double>> points)
  4860. {
  4861. var client = _azureCosmos.GetCosmosClient();
  4862. ExamClassResultMark exMark = new ExamClassResultMark();
  4863. String code = examClassResult.code.Replace("ExamClassResult", "ExamClassResultMark");
  4864. string id = examClassResult.id;
  4865. try
  4866. {
  4867. exMark = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamClassResultMark>(id, new PartitionKey($"{code}"));
  4868. }
  4869. catch (Exception ex)
  4870. {
  4871. exMark.id = id;
  4872. exMark.code = code;
  4873. }
  4874. exMark.markerId = userId;
  4875. exMark.markerName = userName;
  4876. exMark.studentIds = examClassResult.studentIds;
  4877. //學生ID對應index字典
  4878. Dictionary<string, int> stuIndexDic = new Dictionary<string, int>();
  4879. foreach (var item in exMark.studentIds.Select((value, i) => new { i, value }))
  4880. {
  4881. string studentId = item.value;
  4882. int index = item.i;
  4883. stuIndexDic.Add(studentId, index);
  4884. }
  4885. //points內容數不足對應
  4886. while (exMark.studentIds.Count - exMark.points.Count > 0)
  4887. {
  4888. exMark.points.Add(new List<double>());
  4889. }
  4890. //points分數記入
  4891. foreach (var stu in students.Select((value, i) => new { i, value }))
  4892. {
  4893. List<double> point = points[stu.i];
  4894. if (stuIndexDic.ContainsKey(stu.value.id))
  4895. {
  4896. int index = stuIndexDic[stu.value.id];
  4897. exMark.points[index] = point;
  4898. }
  4899. }
  4900. await client.GetContainer(Constant.TEAMModelOS, Constant.Common).UpsertItemAsync<ExamClassResultMark>(exMark, new PartitionKey(code));
  4901. }
  4902. }
  4903. public class stus
  4904. {
  4905. public string id { get; set; }
  4906. public int type { get; set; }
  4907. }
  4908. public class ufo
  4909. {
  4910. public string id { get; set; }
  4911. public string name { get; set; }
  4912. public int type { get; set; }
  4913. }
  4914. public class stuErrorItemCnt
  4915. {
  4916. public string subjectId { get; set; }
  4917. public int number { get; set; }
  4918. }
  4919. public class errorItemInfo
  4920. {
  4921. public string activityId { get; set; }
  4922. public string qId { get; set; }
  4923. public string unitId { get; set; }
  4924. }
  4925. //延伸ExamInfo 追加額外顯示欄位 (目前只有find使用)
  4926. public class ExamInfoEx : ExamInfo
  4927. {
  4928. public string jointExamType { get; set; }
  4929. }
  4930. //取得複數學生作答成績 Request參數
  4931. public class FindExamClassResultsReqParam
  4932. {
  4933. public string creatorId { get; set; }
  4934. public string examId { get; set; }
  4935. public string subjectId { get; set; }
  4936. public string groupListId { get; set; }
  4937. }
  4938. }