ExamController.cs 247 KB

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