ExamController.cs 204 KB

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