TriggerExam.cs 120 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196
  1. using Azure.Cosmos;
  2. using Azure.Messaging.ServiceBus;
  3. using TEAMModelOS.SDK.DI;
  4. using TEAMModelOS.SDK.Extension;
  5. using TEAMModelOS.SDK;
  6. using TEAMModelOS.SDK.Models;
  7. using TEAMModelOS.SDK.Models.Service;
  8. using HTEXLib.COMM.Helpers;
  9. using ClouDASLibx;
  10. using System.Text.Json;
  11. using System.Collections.Generic;
  12. using System.Threading.Tasks;
  13. using System;
  14. using System.Linq;
  15. using TEAMModelOS.SDK.Models.Service.BI;
  16. using Azure.Storage.Blobs.Models;
  17. using System.IO;
  18. using System.Text;
  19. using System.Text.Json.Nodes;
  20. using TEAMModelOS.SDK.Helper.Common.JsonHelper.JsonPath;
  21. using Newtonsoft.Json.Linq;
  22. using TEAMModelOS.SDK.Models.Cosmos.Student;
  23. using HTEXLib.Helpers.ShapeHelpers;
  24. using TEAMModelOS.Models.Dto;
  25. using TEAMModelOS.SDK.Models.Cosmos.Common;
  26. using DocumentFormat.OpenXml.Office2010.Excel;
  27. using DocumentFormat.OpenXml.Drawing.Charts;
  28. using DocumentFormat.OpenXml.Vml;
  29. using System.Net.Http;
  30. using Newtonsoft.Json;
  31. using System.Net;
  32. using System.Security.Policy;
  33. using Microsoft.Extensions.Configuration;
  34. using DocumentFormat.OpenXml.EMMA;
  35. using Microsoft.Extensions.Options;
  36. using TEAMModelOS.Models;
  37. using Microsoft.AspNetCore.Razor.TagHelpers;
  38. using HtmlAgilityPack;
  39. using Azure.Storage.Blobs;
  40. namespace TEAMModelOS.FunctionV4
  41. {
  42. public class TriggerExam
  43. {
  44. public static async Task Trigger(CoreAPIHttpService _coreAPIHttpService, AzureCosmosFactory _azureCosmos, AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
  45. CosmosClient client, JsonElement input, TriggerData data, IHttpClientFactory _httpClient, IConfiguration _configuration, HttpTrigger _httpTrigger)
  46. {
  47. List<ExamClassResult> examClassResults = new();
  48. List<ExamSubject> examSubjects = new();
  49. try
  50. {
  51. if ((data.status != null && data.status.Value == 404))
  52. {
  53. await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(data.id, new PartitionKey(data.code));
  54. ActivityList activity = input.ToObject<ActivityList>();
  55. await IESActivityService.DeleteActivity(_coreAPIHttpService, client, _dingDing, activity);
  56. var table_cancel = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  57. List<ChangeRecord> records = await table_cancel.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", data.id } });
  58. foreach (var record in records)
  59. {
  60. try
  61. {
  62. await table_cancel.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  63. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  64. }
  65. catch (Exception)
  66. {
  67. continue;
  68. }
  69. }
  70. await BIStats.SetTypeAddStats(client, _dingDing, data.school, "Exam", -1, careDate: data.startTime);//BI统计增/减量
  71. return;
  72. }
  73. ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(data.id, new Azure.Cosmos.PartitionKey($"{data.code}"));
  74. if (info != null)
  75. {
  76. if (info.scope.Equals("teacher", StringComparison.OrdinalIgnoreCase) || info.scope.Equals("private", StringComparison.OrdinalIgnoreCase))
  77. {
  78. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: $"select value(c) from c where c.examId = '{info.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamClassResult-{info.creatorId}") }))
  79. {
  80. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  81. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  82. {
  83. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  84. {
  85. examClassResults.Add(obj.ToObject<ExamClassResult>());
  86. }
  87. }
  88. }
  89. }
  90. else
  91. {
  92. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: $"select value(c) from c where c.examId = '{info.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamClassResult-{data.school}") }))
  93. {
  94. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  95. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  96. {
  97. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  98. {
  99. examClassResults.Add(obj.ToObject<ExamClassResult>());
  100. }
  101. }
  102. }
  103. }
  104. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  105. string PartitionKey = string.Format("{0}{1}{2}", info.code, "-", info.progress);
  106. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", data.id }, { "PartitionKey", PartitionKey } });
  107. //处理科目信息
  108. List<string> sub = new List<string>();
  109. School sc = new();
  110. if (!string.IsNullOrEmpty(info.school) && !info.school.Equals("SYSTEM_NO_SCHOOL"))
  111. {
  112. sc = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(info.school, new Azure.Cosmos.PartitionKey("Base"));
  113. }
  114. foreach (ExamSubject subject in info.subjects)
  115. {
  116. sub.Add(subject.id);
  117. }
  118. //整合名单
  119. List<string> classes = ExamService.getClasses(info.classes, info.stuLists);
  120. //ChangeRecord record = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ChangeRecord>(input.Id, new Azure.Cosmos.PartitionKey($"{info.progress}"));
  121. switch (info.progress)
  122. {
  123. case "pending":
  124. var message = new ServiceBusMessage(new { id = data.id, progress = "going", code = data.code }.ToJsonString());
  125. message.ApplicationProperties.Add("name", "Exam");
  126. if (records.Count > 0)
  127. {
  128. try
  129. {
  130. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), records[0].sequenceNumber);
  131. }
  132. catch (Exception)
  133. {
  134. }
  135. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(data.startTime));
  136. records[0].sequenceNumber = start;
  137. await table.SaveOrUpdate<ChangeRecord>(records[0]);
  138. //await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(record, record.id, new Azure.Cosmos.PartitionKey($"{record.code}"));
  139. }
  140. else
  141. {
  142. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(data.startTime));
  143. //string pk = String.Format("{0}{1}{2}", info.code, "-", "pending");
  144. ChangeRecord changeRecord = new ChangeRecord
  145. {
  146. RowKey = data.id,
  147. PartitionKey = PartitionKey,
  148. sequenceNumber = start,
  149. msgId = message.MessageId
  150. };
  151. await table.Save<ChangeRecord>(changeRecord);
  152. //await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  153. }
  154. break;
  155. case "going":
  156. try
  157. {
  158. //向学生或醍摩豆账号发起通知
  159. #region
  160. //Notice notice = new Notice()
  161. //{
  162. // msgId = info.id,
  163. // creation = info.startTime,
  164. // expire = info.endTime,
  165. // creatorId = info.creatorId,
  166. // stuids = studentss,
  167. // tmdids = tmdids,
  168. // type = "notice",//评测参加通知
  169. // priority = "normal",
  170. // school = info.school,
  171. // scope = info.scope,
  172. // //data = new { }.ToJsonString()
  173. // body = new Body { sid = info.id, scode = info.code, spk = info.pk, biztype = "exam-join" }
  174. //};
  175. //var messageBlob = new ServiceBusMessage(notice.ToJsonString());
  176. //messageBlob.ApplicationProperties.Add("name", "Notice");
  177. //await _serviceBus.GetServiceBusClient().SendMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageBlob);
  178. #endregion
  179. //List<string> classes = new List<string>();
  180. //处理活动中间件
  181. List<RGroupList> members = await Activity(_coreAPIHttpService, info, classes, client, _dingDing, sub, examClassResults);
  182. if (examClassResults.Count == 0)
  183. {
  184. foreach (string cla in classes)
  185. {
  186. int m = 0;
  187. RGroupList rGroup = new();
  188. rGroup = members.Where(m => m.id.Equals(cla)).FirstOrDefault();
  189. foreach (ExamSubject subject in info.subjects)
  190. {
  191. string classCode = string.Empty;
  192. string cname = string.Empty;
  193. if (string.IsNullOrEmpty(info.school) || !info.scope.Equals("school", StringComparison.OrdinalIgnoreCase))
  194. {
  195. classCode = "ExamClassResult-" + info.creatorId;
  196. }
  197. else
  198. {
  199. classCode = "ExamClassResult-" + info.school;
  200. }
  201. cname = members.Where(m => m.id.Equals(cla)).FirstOrDefault()?.name;
  202. // 预处理活动中间件信息
  203. ExamClassResult result = new()
  204. {
  205. code = classCode,
  206. examId = info.id,
  207. id = Guid.NewGuid().ToString(),
  208. subjectId = subject.id,
  209. year = info.year,
  210. scope = info.scope
  211. };
  212. result.info.id = cla;
  213. result.info.name = cname;
  214. List<string> ans = new();
  215. List<List<string>> anses = new();
  216. List<List<Details>> marks = new();
  217. List<double> ansPoint = new();
  218. List<(string sId, string scode)> ids = new();
  219. foreach (double p in info.papers[m].point)
  220. {
  221. //Details details = new Details();
  222. //ans.Add(new List<string>());
  223. anses.Add(new List<string>());
  224. marks.Add(new List<Details>());
  225. ansPoint.Add(-1);
  226. }
  227. var sresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"Class-{info.school}"));
  228. if (sresponse.Status == 200)
  229. {
  230. using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
  231. Class classroom = json.ToObject<Class>();
  232. foreach (SDK.Models.Period period in sc.period)
  233. {
  234. if (period.id.Equals(classroom.periodId))
  235. {
  236. foreach (Semester semester in period.semesters)
  237. {
  238. if (semester.start == 1)
  239. {
  240. int year = DateTimeOffset.UtcNow.Year;
  241. int month = DateTimeOffset.UtcNow.Month;
  242. int day = DateTimeOffset.UtcNow.Day;
  243. int time = 0;
  244. if (month == semester.month)
  245. {
  246. time = day >= semester.day ? 0 : 1;
  247. }
  248. else
  249. {
  250. time = month > semester.month ? 0 : 1;
  251. }
  252. int eyear = year - time;
  253. result.gradeId = (eyear - classroom.year).ToString();
  254. }
  255. }
  256. }
  257. }
  258. //result.info.id = classroom.id;
  259. //result.info.name = classroom.name;
  260. //result.gradeId = classroom.year.ToString();
  261. //处理班级人数
  262. /* await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: $"select c.id from c where c.classId = '{classroom.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{info.school}") }))
  263. {
  264. using var json_stu = await JsonDocument.ParseAsync(item.ContentStream);
  265. if (json_stu.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  266. {
  267. var accounts = json_stu.RootElement.GetProperty("Documents").EnumerateArray();
  268. while (accounts.MoveNext())
  269. {
  270. JsonElement account = accounts.Current;
  271. ids.Add(account.GetProperty("id").GetString());
  272. }
  273. }
  274. }*/
  275. }
  276. /*if (info.scope.Equals("private", StringComparison.OrdinalIgnoreCase))
  277. {
  278. var stuResponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"GroupList"));
  279. if (stuResponse.Status == 200)
  280. {
  281. using var json = await JsonDocument.ParseAsync(stuResponse.ContentStream);
  282. GroupList stuList = json.ToObject<GroupList>();
  283. //result.info.id = stuList.id;
  284. result.info.name = stuList.name;
  285. //处理发布对象为自选名单(个人)
  286. foreach (Member stus in stuList.members)
  287. {
  288. if (!ids.Contains(stus.id))
  289. {
  290. ids.Add(stus.id);
  291. }
  292. }
  293. }
  294. }
  295. else
  296. {
  297. var stuResponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"GroupList-{info.school}"));
  298. if (stuResponse.Status == 200)
  299. {
  300. using var json = await JsonDocument.ParseAsync(stuResponse.ContentStream);
  301. GroupList stuList = json.ToObject<GroupList>();
  302. //result.info.id = stuList.id;
  303. result.info.name = stuList.name;
  304. //处理发布对象为自选名单(校本)
  305. foreach (Member stus in stuList.members)
  306. {
  307. if (!ids.Contains(stus.id))
  308. {
  309. ids.Add(stus.id);
  310. }
  311. }
  312. }
  313. }*/
  314. foreach (RMember member in rGroup.members)
  315. {
  316. ids.Add((member.id, member.code));
  317. }
  318. //ids = members.Where(c => c.id.Equals(cla)).SelectMany(m => m.members).Select(g => g.id).ToList();
  319. List<string> blobs = new();
  320. if (info.qamode == 2) {
  321. blobs = info.papers.Where(c => c.subjectId.Equals(subject.id)).Select(c => c.blob).ToList();
  322. }
  323. foreach (var (sId, scode) in ids)
  324. {
  325. result.mark.Add(marks);
  326. result.studentIds.Add(sId);
  327. //result.scIds.Add(scode ?? "");
  328. result.studentAnswers.Add(ans);
  329. result.studentScores.Add(ansPoint);
  330. result.ans.Add(anses);
  331. result.sum.Add(0);
  332. result.status.Add(1);
  333. if (info.qamode == 2) {
  334. result.paper.Add(blobs[new Random().Next(blobs.Count)]);
  335. }
  336. }
  337. //result.progress = info.progress;
  338. result.school = info.school;
  339. m++;
  340. await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(result, new Azure.Cosmos.PartitionKey($"{result.code}"));
  341. }
  342. }
  343. }
  344. else
  345. {
  346. //处理单科结算时科目与试卷信息匹配的问题
  347. int gno = 0;
  348. foreach (ExamSubject subject in info.subjects)
  349. {
  350. if (subject.classCount == classes.Count)
  351. {
  352. await createClassResultAsync(info, examClassResults, subject, gno, _azureCosmos, _dingDing, _azureStorage, _httpClient, _configuration);
  353. }
  354. gno++;
  355. }
  356. var isScore = examClassResults.SelectMany(e => e.studentScores).ToList().Exists(c => c.Contains(-1));
  357. int newStatus = 0;
  358. if (!isScore)
  359. {
  360. newStatus = 1;
  361. }
  362. Settlement settlement = await getMore(client, info);
  363. long nowTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  364. //判断评分状态是否发生变化,便于实时的更新评测基本信息
  365. if (info.average != settlement.score || info.sStatus != newStatus)
  366. {
  367. info.sRate = settlement.rate;
  368. info.sStatus = newStatus;
  369. info.updateTime = nowTime;
  370. info.average = settlement.score;
  371. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ExamInfo>(info, info.id, new PartitionKey(info.code));
  372. }
  373. }
  374. }
  375. catch (Exception e)
  376. {
  377. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测going状态异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  378. }
  379. finally
  380. {
  381. // 发送信息通知
  382. var messageEnd = new ServiceBusMessage(new { id = data.id, progress = "finish", code = data.code }.ToJsonString());
  383. messageEnd.ApplicationProperties.Add("name", "Exam");
  384. if (records.Count > 0)
  385. {
  386. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(data.endTime));
  387. try
  388. {
  389. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), records[0].sequenceNumber);
  390. }
  391. catch (Exception)
  392. {
  393. }
  394. records[0].sequenceNumber = end;
  395. await table.SaveOrUpdate<ChangeRecord>(records[0]);
  396. //await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(record, record.id, new Azure.Cosmos.PartitionKey($"{record.code}"));
  397. }
  398. else
  399. {
  400. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(data.endTime));
  401. //string pk = String.Format("{0}{1}{2}", info.code, "-", "going");
  402. ChangeRecord changeRecord = new ChangeRecord
  403. {
  404. RowKey = data.id,
  405. PartitionKey = PartitionKey,
  406. sequenceNumber = end,
  407. msgId = messageEnd.MessageId
  408. };
  409. await table.Save<ChangeRecord>(changeRecord);
  410. //await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  411. }
  412. }
  413. break;
  414. case "finish":
  415. int fno = 0;
  416. try
  417. {
  418. SetLearnRecordContent(info, data, _azureStorage, _azureCosmos);
  419. //用来判定是否完成评分
  420. //bool isScore = true;
  421. await resultStatus(client, examClassResults);
  422. await Activity(_coreAPIHttpService, info, classes, client, _dingDing, sub, examClassResults);
  423. foreach (ExamSubject subject in info.subjects)
  424. {
  425. await createClassResultAsync(info, examClassResults, subject, fno, _azureCosmos, _dingDing, _azureStorage, _httpClient, _configuration);
  426. fno++;
  427. }
  428. Settlement settlement = await getMore(client, info);
  429. var isScore = examClassResults.SelectMany(e => e.studentScores).ToList().Exists(c => c.Contains(-1));
  430. int newStatus = 0;
  431. if (!isScore)
  432. {
  433. newStatus = 1;
  434. }
  435. //判断均分是否发生变化,便于实时的更新评测基本信息
  436. if (info.sRate != settlement.rate || info.average != settlement.score || info.sStatus != newStatus || info.qRate != settlement.qrate)
  437. {
  438. info.sRate = settlement.rate;
  439. info.average = settlement.score;
  440. info.sStatus = newStatus;
  441. info.lostStu = settlement.stus;
  442. info.stuCount = settlement.total;
  443. info.qRate = settlement.qrate;
  444. //新增数据推送 obj => Portrait
  445. Portrait portrait = new()
  446. {
  447. schoolCode = info.school,
  448. periodId = info.period.id,
  449. subjectId = "subject_intelligence"
  450. };
  451. //作答合格率
  452. var sta = examClassResults.SelectMany(x => x.status).ToList();
  453. /* var stus = examClassResults.SelectMany(x => x.studentIds).ToList();
  454. var stuScores = examClassResults.SelectMany(x => x.studentScores).ToList();*/
  455. var ansCount = sta.Where(x => x == 0).ToList();
  456. var persent = ansCount.Count * 1.0 / sta.Count * 100;
  457. var period = sc.period.Where(x => x.id.Equals(info.period.id)).FirstOrDefault();
  458. List<string> subjects = info.subjects.Select(x => x.id).ToList();
  459. //获取学期信息
  460. if (null != period && persent >= 60 && !subjects.Contains("subject_painting") && !subjects.Contains("subject_music"))
  461. {
  462. var (currSemester, studyYear, currSemesterDate, date, nextSemester) = SchoolService.GetSemester(period, info.startTime);
  463. //获取学生信息
  464. (List<RMember> rmembers, List<RGroupList> groups) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, info.classes, info.school);
  465. foreach (var member in rmembers)
  466. {
  467. if (info.lostStu.Contains(member.id))
  468. {
  469. continue;
  470. }
  471. PortraitStudent student = new()
  472. {
  473. studentId = member.id,
  474. name = member.name,
  475. classId = member.classId
  476. };
  477. var ec = examClassResults.Where(c => c.studentIds.Contains(member.id)).ToList();
  478. double scores = 0;
  479. List<(string subjectId, double score)> subScore = new();
  480. foreach (var eclass in ec)
  481. {
  482. int index_stu = eclass.studentIds.IndexOf(member.id);
  483. scores += eclass.sum[index_stu];
  484. subScore.Add((eclass.subjectId, eclass.sum[index_stu]));
  485. }
  486. SemesterData semesterData = new()
  487. {
  488. examName = info.name,
  489. examId = info.id,
  490. examDate = info.startTime,
  491. examType = info.examType?.name,
  492. year = info.year,
  493. semesterId = currSemester.id,
  494. totalScore = info.papers.SelectMany(x => x.point).Sum(),
  495. sumScore = scores,
  496. excellenceRate = 0,
  497. passRate = 0,
  498. };
  499. int index = 0;
  500. foreach (var sj in info.subjects)
  501. {
  502. ItemScore item = new()
  503. {
  504. id = sj.id,
  505. name = sj.name,
  506. score = subScore.Where(c => c.subjectId.Equals(sj.id)).FirstOrDefault().score,
  507. time = info.startTime,
  508. totalScore = info.papers[index].point.Sum(),
  509. type = sj.id
  510. };
  511. index++;
  512. semesterData.itemScore.Add(item);
  513. }
  514. student.semesterData.Add(semesterData);
  515. portrait.students.Add(student);
  516. }
  517. string location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
  518. var (status, json) = await _httpTrigger.RequestHttpTrigger(portrait, location, "upsert-student-portrait");
  519. }
  520. //PortraitStudent student = new();
  521. //处理试卷活动结束统计账户信息
  522. List<FMember> idList = await GroupListService.GetFinishMemberInfo(_coreAPIHttpService, client, _dingDing, info.school, info.classes, info.stuLists, null);
  523. info.staffIds = idList;
  524. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ExamInfo>(info, info.id, new Azure.Cosmos.PartitionKey(info.code));
  525. }
  526. //SetLearnRecordContent(info, data, _azureStorage);
  527. }
  528. catch (Exception e)
  529. {
  530. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测finish状态异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  531. }
  532. break;
  533. }
  534. }
  535. }
  536. catch (CosmosException e)
  537. {
  538. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.Status}", GroupNames.醍摩豆服務運維群組);
  539. }
  540. catch (Exception e)
  541. {
  542. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-评测结算异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  543. }
  544. }
  545. private static async Task SetLearnRecordContent(ExamInfo info, TriggerData data, AzureStorageFactory _azureStorage, AzureCosmosFactory _azureCosmos)
  546. {
  547. try
  548. {
  549. if (info.papers.Count > 0)
  550. {
  551. // debug用
  552. //if (info.id == "d1dc1417-eeb0-4b4c-b1b3-7e9f99c95087")
  553. //{
  554. //}
  555. for (int i = 0; i < info.papers.Count; i++)
  556. {// 每一個科目的試卷
  557. string rootName = "";
  558. //if (info.school == "SYSTEM_NO_SCHOOL")
  559. if (info.scope == "private")
  560. {// 未入校老師的評量
  561. rootName = info.creatorId;
  562. }
  563. else
  564. {// 如果有學校代碼
  565. rootName = info.school;
  566. }
  567. if (_azureStorage.GetBlobContainerClient(rootName).GetBlobClient($"{info.papers[i].blob}/index.json").Exists())
  568. {// 如果試卷的blob存在,再開始
  569. BlobDownloadResult paperblobDownload = await _azureStorage.GetBlobContainerClient(rootName).GetBlobClient($"{info.papers[i].blob}/index.json").DownloadContentAsync();
  570. PaperIndex paperIndex = paperblobDownload.Content.ToObjectFromJson<PaperIndex>();
  571. List<LearnRecordItem> learnRecordItems = new();
  572. StringBuilder sbsql = new StringBuilder($" SELECT * FROM c WHERE c.examId = '{info.id}' and c.pk = 'ExamClassResult' and c.subjectId = '{info.subjects[i].id}' ");
  573. #region === 開始拼裝資料 ===
  574. if (info.classes.Count > 0 || info.stuLists.Count > 0)
  575. {
  576. // 組合SQL
  577. if (info.classes.Count > 0)
  578. {// 按照classes取ans.json
  579. sbsql.Append($" and ARRAY_CONTAINS({System.Text.Json.JsonSerializer.Serialize(info.classes)}, c.info.id)");
  580. //sbsql.Append($" and c.info.id in (");
  581. //foreach (var classes in info.classes)
  582. //{// 組合所有classesid
  583. // if (classes == info.classes[info.classes.Count - 1])
  584. // {
  585. // sbsql.Append($"'{classes}' )");
  586. // }
  587. // else
  588. // {
  589. // sbsql.Append($"'{classes}',");
  590. // }
  591. //}
  592. }
  593. else if (info.stuLists.Count > 0)
  594. {
  595. sbsql.Append($" and ARRAY_CONTAINS({System.Text.Json.JsonSerializer.Serialize(info.stuLists)}, c.info.id)");
  596. //sbsql.Append($" and c.info.id in (");
  597. //foreach (var stuLists in info.stuLists)
  598. //{// 組合所有stuListsid
  599. // if (stuLists == info.stuLists[info.stuLists.Count - 1])
  600. // {
  601. // sbsql.Append($"'{stuLists}' )");
  602. // }
  603. // else
  604. // {
  605. // sbsql.Append($"'{stuLists}',");
  606. // }
  607. //}
  608. }
  609. // 取學生答案及學生名單
  610. var client = _azureCosmos.GetCosmosClient();
  611. Dictionary<string, List<string>> stuDic = new Dictionary<string, List<string>>();
  612. if (!string.IsNullOrWhiteSpace(info.school) && !stuDic.ContainsKey(info.school))
  613. {
  614. stuDic.Add(info.school, new List<string>());
  615. }
  616. List<StudentAnswers> studentAnswersList = new List<StudentAnswers>();
  617. List<string> stuListForSql = new List<string>();
  618. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Common).GetItemQueryIterator<StudentAnswers>(queryText: sbsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{rootName}") }))
  619. {
  620. studentAnswersList.Add(item);
  621. stuListForSql.Union(item.studentIds);
  622. }
  623. //取得學校的學生名單
  624. if(!string.IsNullOrWhiteSpace(info.school))
  625. {
  626. StringBuilder stusql = new StringBuilder($" SELECT c.id FROM c WHERE c.pk = 'Base' AND ARRAY_CONTAINS({System.Text.Json.JsonSerializer.Serialize(stuListForSql)}, c.id)");
  627. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Student).GetItemQueryIterator<string>(queryText: stusql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{info.school}") }))
  628. {
  629. stuDic[info.school].Add(item);
  630. }
  631. }
  632. // 按照取出的學生答案blob 對答案 組合資料
  633. foreach (var studentAnswers in studentAnswersList)
  634. {// 每一個班級
  635. foreach (var studentAnswersBlob in studentAnswers.studentAnswers)
  636. {// 每一個學生
  637. if (studentAnswersBlob.Count > 0)
  638. {// 有學生的答案才開始
  639. if (_azureStorage.GetBlobContainerClient(rootName).GetBlobClient($"/exam/{studentAnswersBlob[0]}").Exists())
  640. {// 如果blob存在才開始
  641. BlobDownloadResult ansblobDownload = await _azureStorage.GetBlobContainerClient(rootName).GetBlobClient($"/exam/{studentAnswersBlob[0]}").DownloadContentAsync();
  642. List<List<string>> ansList = JsonConvert.DeserializeObject<List<List<string>>>(ansblobDownload.Content.ToString());
  643. // 從blob路徑取出學生id
  644. string[] arr = studentAnswersBlob[0].Split('/');
  645. string stuid = arr[arr.Length - 2];
  646. #region ===StartExam 開始課堂===
  647. LearnRecordItem LRItem_StartExam = new();
  648. LRItem_StartExam.verb = "StartExam";
  649. LRItem_StartExam.actor = getStuId(info.school, stuid, stuDic);
  650. LRItem_StartExam.time = info.createTime;
  651. LRItem_StartExam.ID = info.id;
  652. LRItem_StartExam.Desc = info.name;
  653. LRItem_StartExam.Correct = null;
  654. LRItem_StartExam.Choices = null;
  655. LRItem_StartExam.ExamQuesQty = info.papers[i].point.Count;
  656. LRItem_StartExam.TotalScore = 0;
  657. foreach (var pointItem in info.papers[i].point)
  658. {
  659. LRItem_StartExam.TotalScore = LRItem_StartExam.TotalScore + pointItem;
  660. }
  661. LRItem_StartExam.Success = null;
  662. learnRecordItems.Add(LRItem_StartExam);
  663. #endregion
  664. #region ===評量題目===
  665. for (int j = 0; j < ansList.Count; j++)
  666. {
  667. #region === 判斷題型 ===
  668. // 這五種題型才記錄
  669. if (paperIndex.slides[j].type == "single" ||
  670. paperIndex.slides[j].type == "multiple" ||
  671. paperIndex.slides[j].type == "judge" ||
  672. paperIndex.slides[j].type == "complete" ||
  673. paperIndex.slides[j].type == "subjective")
  674. {
  675. LearnRecordItem learnRecordItem = new();
  676. // 單選
  677. if (paperIndex.slides[j].type == "single") { learnRecordItem.verb = "AnsSingle"; }
  678. // 複選
  679. if (paperIndex.slides[j].type == "multiple") { learnRecordItem.verb = "AnsMultiple"; }
  680. // 是非
  681. if (paperIndex.slides[j].type == "judge") { learnRecordItem.verb = "AnsJudge"; }
  682. // 填充
  683. if (paperIndex.slides[j].type == "complete") { learnRecordItem.verb = "AnsComplete"; }
  684. // 問答
  685. if (paperIndex.slides[j].type == "subjective") { learnRecordItem.verb = "AnsSubjective"; }
  686. learnRecordItem.actor = getStuId(info.school, stuid, stuDic);
  687. learnRecordItem.time = data.endTime;
  688. string[] arrurlsingle = paperIndex.slides[j].url.Split('.');
  689. learnRecordItem.ID = arrurlsingle[0];
  690. #region === 設定Correct Choices Desc===
  691. if (_azureStorage.GetBlobContainerClient(rootName).GetBlobClient($"{info.papers[i].blob}/{paperIndex.slides[j].url}").Exists())
  692. {
  693. BlobDownloadResult itemblobDownload = await _azureStorage.GetBlobContainerClient(rootName).GetBlobClient($"{info.papers[i].blob}/{paperIndex.slides[j].url}").DownloadContentAsync();
  694. QuestionData questionData = itemblobDownload.Content.ToObjectFromJson<QuestionData>();
  695. setCorrectChoices(questionData, learnRecordItem);
  696. // 使用HtmlAgilityPack解析HTML
  697. HtmlDocument doc = new HtmlDocument();
  698. doc.LoadHtml(questionData.item[0].question);
  699. // 先刪除所有<img>標籤
  700. foreach (var imgNode in doc.DocumentNode.Descendants("img").ToArray())
  701. {
  702. imgNode.Remove();
  703. }
  704. // 再取純文字
  705. learnRecordItem.Desc = doc.DocumentNode.InnerText;
  706. }
  707. #endregion
  708. learnRecordItem.ExamQuesQty = null;
  709. learnRecordItem.TotalScore = null;
  710. learnRecordItem.Points = paperIndex.slides[j].scoring == null ? new List<string>() : paperIndex.slides[j].scoring.knowledge;
  711. //比對答案
  712. learnRecordItem.Success = paperIndex.slides[j].scoring == null ? null : (paperIndex.slides[j].scoring.ans.SequenceEqual(ansList[j]) ? true : false);
  713. learnRecordItems.Add(learnRecordItem);
  714. }
  715. #endregion
  716. }
  717. #endregion
  718. #region ===EndExam 結束課堂===
  719. LearnRecordItem LRItem_EndExam = new();
  720. LRItem_EndExam.verb = "EndExam";
  721. LRItem_EndExam.actor = getStuId(info.school, stuid, stuDic);
  722. LRItem_EndExam.time = info.endTime;
  723. LRItem_EndExam.ID = info.id;
  724. LRItem_EndExam.Desc = info.name;
  725. LRItem_EndExam.Correct = null;
  726. LRItem_EndExam.Choices = null;
  727. LRItem_EndExam.ExamQuesQty = info.papers[i].point.Count;
  728. LRItem_EndExam.TotalScore = 0;
  729. foreach (var pointItem in info.papers[i].point)
  730. {
  731. LRItem_EndExam.TotalScore = LRItem_EndExam.TotalScore + pointItem;
  732. }
  733. LRItem_EndExam.Success = null;
  734. learnRecordItems.Add(LRItem_EndExam);
  735. #endregion
  736. }
  737. }
  738. }
  739. }
  740. }
  741. #endregion
  742. if (learnRecordItems.Count > 0)
  743. {
  744. #region 寫入blob
  745. // 容器名称
  746. string containerName = "twmoeld";
  747. // 新文件的名称
  748. string blobName = $"/{DateTime.Now.ToString("yyyyMMdd")}/{info.id}.json";
  749. // 要上传的文件内容
  750. string fileContent = Newtonsoft.Json.JsonConvert.SerializeObject(learnRecordItems);
  751. // 获取容器引用
  752. BlobContainerClient containerClient = _azureStorage.GetBlobContainerClient(containerName);
  753. // 获取 Blob 客户端
  754. BlobClient blobClient = containerClient.GetBlobClient(blobName);
  755. // 将文件内容上传到 Blob
  756. using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(fileContent)))
  757. {
  758. await blobClient.UploadAsync(stream, true);
  759. }
  760. #endregion
  761. }
  762. }
  763. }
  764. }
  765. }
  766. catch (Exception ex)
  767. {
  768. }
  769. }
  770. /// <summary>
  771. /// 取得學習紀錄的actor
  772. /// </summary>
  773. /// <param name="learnRecordItem"></param>
  774. /// <param name="school"></param>
  775. /// <param name="stuid"></param>
  776. /// <returns></returns>
  777. private static string getStuId(string school, string stuid, Dictionary<string, List<string>> stuDic)
  778. {
  779. if (!string.IsNullOrWhiteSpace(school) && stuDic.ContainsKey(school) && stuDic[school].Contains(stuid))
  780. {// 校內帳號用組合的 "Base-hbgl,473891247381"
  781. return $"Base-{school.Trim()},{stuid}";
  782. }
  783. else
  784. {// 未入校老師的評量
  785. return stuid;
  786. }
  787. }
  788. private static void setCorrectChoices(QuestionData questionData, LearnRecordItem learnRecordItem)
  789. {
  790. #region === Correct Choices ===
  791. #region === 是非題邏輯 ===
  792. if (questionData.exercise.type == "judge" && questionData.exercise.answer.Count > 0)
  793. {// 如果是是非題 正確答案要用true false的方式設定
  794. if (questionData.exercise.answer[0] == "A")
  795. {
  796. learnRecordItem.Correct = true;
  797. }
  798. else
  799. {
  800. learnRecordItem.Correct = false;
  801. }
  802. }
  803. else
  804. {// 防呆 去html標籤
  805. if (questionData.exercise.answer.Count > 0)
  806. {
  807. List<string> anslist = new();
  808. foreach (var answer in questionData.exercise.answer)
  809. {
  810. // 使用HtmlAgilityPack解析HTML
  811. HtmlDocument doc = new HtmlDocument();
  812. doc.LoadHtml(answer);
  813. // 再取純文字
  814. anslist.Add(doc.DocumentNode.InnerText);
  815. }
  816. learnRecordItem.Correct = anslist;
  817. }
  818. else
  819. {
  820. learnRecordItem.Correct = questionData.exercise.answer;
  821. }
  822. }
  823. #endregion
  824. if (questionData.item[0].option.Count > 0)
  825. {// 如果有選項資料 記錄起來
  826. foreach (var option in questionData.item[0].option)
  827. {
  828. ChoicesItem item = new();
  829. item.id = option.code;
  830. if (questionData.exercise.type == "judge")
  831. {// 如果是是非題 固定選項
  832. if (option.code == "A")
  833. {
  834. item.description.zhTW = "是";
  835. }
  836. else
  837. {
  838. item.description.zhTW = "否";
  839. }
  840. }
  841. else
  842. {
  843. if (string.IsNullOrWhiteSpace(option.value))
  844. {
  845. item.description.zhTW = $"選項{option.code}";
  846. }
  847. else
  848. {
  849. // 使用HtmlAgilityPack解析HTML
  850. HtmlDocument doc = new HtmlDocument();
  851. doc.LoadHtml(option.value);
  852. // 再取純文字
  853. item.description.zhTW = doc.DocumentNode.InnerText;
  854. }
  855. }
  856. learnRecordItem.Choices.Add(item);
  857. }
  858. }
  859. #endregion
  860. }
  861. public static async Task resultStatus(CosmosClient client, List<ExamClassResult> examClassResults)
  862. {
  863. List<Task<ItemResponse<ExamClassResult>>> tasks = new();
  864. //结算单科单班的标准差和平均分
  865. foreach (ExamClassResult classResult in examClassResults)
  866. {
  867. //标记单科单班总得分
  868. double subScore = 0;
  869. //标准差
  870. double sPowSum = 0;
  871. List<double> newSumScore = new List<double>();
  872. List<double> effectiveScore = new List<double>();
  873. int lostStu = classResult.status.Where(c => c == 1).ToList().Count;
  874. var scount = classResult.studentIds.Count - lostStu;
  875. int index = 0;
  876. if (classResult.status.Count > 0)
  877. {
  878. foreach (var sta in classResult.status)
  879. {
  880. if (sta == 1)
  881. {
  882. for (int i = 0; i < classResult.studentScores[index].Count; i++)
  883. {
  884. if (classResult.studentScores[index][i] == -1)
  885. {
  886. classResult.studentScores[index][i] = 0;
  887. }
  888. }
  889. }
  890. else if (sta == 0)
  891. {
  892. //var ans = classResult.studentAnswers[index];
  893. //该学生缺考,历史数据的判定
  894. //if (ans.Count == 0)
  895. //{
  896. for (int i = 0; i < classResult.studentScores[index].Count; i++)
  897. {
  898. if (classResult.studentScores[index][i] == -1)
  899. {
  900. classResult.studentScores[index][i] = 0;
  901. }
  902. }
  903. /*if (ans.Count == 0)
  904. {
  905. classResult.status[index] = 1;
  906. } */
  907. //}
  908. }
  909. index++;
  910. }
  911. }
  912. else
  913. {
  914. List<int> sta = new();
  915. foreach (var id in classResult.studentIds)
  916. {
  917. sta.Add(0);
  918. }
  919. classResult.status = sta;
  920. foreach (var ans in classResult.studentAnswers)
  921. {
  922. //该学生缺考,历史数据的判定
  923. if (ans.Count == 0)
  924. {
  925. for (int i = 0; i < classResult.studentScores[index].Count; i++)
  926. {
  927. if (classResult.studentScores[index][i] == -1)
  928. {
  929. classResult.studentScores[index][i] = 0;
  930. }
  931. }
  932. classResult.status[index] = 1;
  933. }
  934. index++;
  935. }
  936. }
  937. int sIndex = 0;
  938. foreach (List<double> sc in classResult.studentScores)
  939. {
  940. List<double> newSc = new List<double>();
  941. foreach (double ssc in sc)
  942. {
  943. if (ssc == -1)
  944. {
  945. newSc.Add(0);
  946. }
  947. else
  948. {
  949. newSc.Add(ssc);
  950. }
  951. }
  952. double nc = Math.Round(newSc.Sum(), 2);
  953. if (classResult.status[sIndex] == 0)
  954. {
  955. effectiveScore.Add(nc);
  956. };
  957. newSumScore.Add(nc);
  958. subScore += nc;
  959. classResult.sum[sIndex] = nc;
  960. sIndex++;
  961. }
  962. double rateScore = scount > 0 ? Math.Round(subScore * 1.0 / scount, 2) : 0;
  963. //有效分数
  964. foreach (double scs in effectiveScore)
  965. {
  966. sPowSum += Math.Pow(scs - rateScore, 2);
  967. }
  968. classResult.standard = Math.Round(scount > 0 ? Math.Pow(sPowSum / scount, 0.5) : 0, 2);
  969. classResult.average = scount > 0 ? Math.Round(subScore / scount, 2) : 0;
  970. classResult.progress = true;
  971. tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new PartitionKey($"{classResult.code}")));
  972. }
  973. await Task.WhenAll(tasks);
  974. }
  975. public static async Task<Settlement> getMore(CosmosClient client, ExamInfo info)
  976. {
  977. //计算单次考试简易统计信息
  978. Settlement settlement = new();
  979. List<ExamResult> examResults = new();
  980. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamResult>(
  981. queryText: $"select value(c) from c where c.examId = '{info.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}") }))
  982. {
  983. examResults.Add(item);
  984. }
  985. if (examResults.Count > 0)
  986. {
  987. //记录某次考试所有学生得分总分
  988. double score = 0;
  989. double allScore = 0;
  990. int stuCount = 0;
  991. //标准差
  992. double powSum = 0;
  993. List<string> losStu = new List<string>();
  994. //当前完成考试得人数
  995. int total = examResults[0].studentIds.Distinct().Count();
  996. //先与第一个值取并集
  997. losStu = losStu.Union(examResults[0].lostStus).ToList();
  998. foreach (ExamResult examResult in examResults)
  999. {
  1000. //取交集
  1001. losStu = losStu.Intersect(examResult.lostStus).ToList();
  1002. }
  1003. //处理缺考的学生
  1004. List<string> stus = examResults[0].studentIds.Except(losStu).ToList();
  1005. foreach (ExamResult examResult in examResults)
  1006. {
  1007. foreach (var id in stus)
  1008. {
  1009. int index = examResult.studentIds.IndexOf(id);
  1010. score += examResult.studentScores[index].Sum();
  1011. }
  1012. }
  1013. stuCount = total - losStu.Count;
  1014. double NewsRateScore = stuCount > 0 ? Math.Round(score * 1.0 / stuCount, 2) : 0;
  1015. foreach (PaperSimple simple in info.papers)
  1016. {
  1017. allScore += simple.point.Sum();
  1018. }
  1019. //计算全科标准差
  1020. foreach (string id in stus)
  1021. {
  1022. double sc = 0;
  1023. foreach (ExamResult result in examResults)
  1024. {
  1025. if (result.studentScores.Count > 0)
  1026. {
  1027. sc += result.studentScores[result.studentIds.IndexOf(id)].Sum();
  1028. }
  1029. }
  1030. powSum += Math.Pow(sc - NewsRateScore, 2);
  1031. }
  1032. info.standard = Math.Round(total - losStu.Count > 0 ? Math.Pow(powSum / (total - losStu.Count), 0.5) : 0, 2);
  1033. double NewsRate = allScore > 0 ? Math.Round(NewsRateScore / allScore * 100, 2) : 0;
  1034. double qrate = Math.Round(total > 0 ? losStu.Count * 1.0 / total * 100 : 0, 2);
  1035. settlement.rate = NewsRate;
  1036. settlement.score = NewsRateScore;
  1037. settlement.stus = losStu;
  1038. settlement.total = total;
  1039. settlement.qrate = qrate;
  1040. }
  1041. return settlement;
  1042. }
  1043. //处理全部学生选题计数
  1044. public static async Task examRecordCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, ExamResult er, List<ExamClassResult> classResults, AzureCosmosFactory _azureCosmos)
  1045. {
  1046. try
  1047. {
  1048. List<double> scores = new List<double>();
  1049. foreach (List<double> sc in er.studentScores)
  1050. {
  1051. scores.Add(sc.Sum());
  1052. }
  1053. //确定高分组 最低分数
  1054. //var srowallorder = scores.EnumerateIndexed().OrderByDescending(g => g.Item2); //各生總分排序
  1055. //var srowallorder = scores.OrderByDescending(g => g);
  1056. double[] point = StringHelper.ListTodouble(er.paper.point);
  1057. double[,] result = StringHelper.ListToDouble(er.studentScores);
  1058. var cdm = new ClouDASMatrix(result, point);
  1059. scores.Sort((s1, s2) => { return s2.CompareTo(s1); });
  1060. int rhwCount = cdm.SH.Count();
  1061. double rhw = cdm.SH.LastOrDefault().Item2;
  1062. int rhlCount = cdm.SL.Count();
  1063. double rhl = cdm.SL.FirstOrDefault().Item2;
  1064. List<string> phs = new();
  1065. List<string> pls = new();
  1066. //分别获取高分组低分组人员
  1067. foreach (var ph in cdm.SH)
  1068. {
  1069. phs.Add(er.studentIds[ph.Item1]);
  1070. }
  1071. foreach (var pl in cdm.SL)
  1072. {
  1073. pls.Add(er.studentIds[pl.Item1]);
  1074. }
  1075. /* if (scores.Count > 3)
  1076. {
  1077. rhwCount = Convert.ToInt32(Math.Floor(scores.Count * 0.27));
  1078. rhw = rhwCount > 0 ? scores[rhwCount - 1] : 0;
  1079. rhlCount = Convert.ToInt32(Math.Ceiling(scores.Count * 0.73));
  1080. rhl = rhlCount > 0 ? scores[rhlCount] : 0;
  1081. }
  1082. else
  1083. {
  1084. rhwCount = Convert.ToInt32(Math.Floor(scores.Count * 0.27));
  1085. rhw = rhwCount > 0 ? scores[rhwCount] : 0;
  1086. rhlCount = Convert.ToInt32(Math.Ceiling(scores.Count * 0.73));
  1087. rhl = rhlCount > 0 ? scores[rhlCount - 1] : 0;
  1088. }*/
  1089. /*int rhwCount = Convert.ToInt32(Math.Floor(scores.Count * 0.27));
  1090. double rhw = rhwCount > 0 ? scores[rhwCount-1] : 0;
  1091. //var rhww = srowallorder.Take(Convert.ToInt32(Math.Floor(scores.Count * 0.27)));
  1092. //确定低分组 最高分数
  1093. //scores.Sort((s1, s2) => { return s1.CompareTo(s2); });
  1094. int rhlCount = Convert.ToInt32(Math.Ceiling(scores.Count * 0.73));
  1095. double rhl = rhlCount > 0 ? scores[rhlCount-1] : 0;*/
  1096. //var rhll = srowallorder.Skip(Convert.ToInt32(Math.Ceiling(scores.Count * 0.73)));
  1097. //存放高分组学生ID
  1098. List<string> phId = new();
  1099. List<string> plId = new();
  1100. List<List<List<string>>> opth = new();
  1101. List<List<List<string>>> optl = new();
  1102. List<double> akp = await knowledgeCount(info, subject, _dingDing, no, classResults, rhwCount, rhw, rhlCount, rhl, _azureCosmos);
  1103. List<double> afp = await fieldCount(info, subject, _dingDing, no, classResults, rhwCount, rhw, rhlCount, rhl, _azureCosmos);
  1104. int PHCount = 0;
  1105. int PLCount = 0;
  1106. foreach (ExamClassResult classResult in classResults)
  1107. {
  1108. if (classResult.subjectId.Equals(subject.id))
  1109. {
  1110. foreach (string id in classResult.studentIds)
  1111. {
  1112. int index = classResult.studentIds.IndexOf(id);
  1113. if (classResult.studentScores.Count > 0)
  1114. {
  1115. if (phs.Contains(id))
  1116. {
  1117. if (classResult.ans.Count > 0)
  1118. {
  1119. opth.Add(classResult.ans[index]);
  1120. PHCount++;
  1121. continue;
  1122. }
  1123. }
  1124. if (pls.Contains(id))
  1125. {
  1126. if (classResult.ans.Count > 0)
  1127. {
  1128. optl.Add(classResult.ans[index]);
  1129. PLCount++;
  1130. continue;
  1131. }
  1132. }
  1133. }
  1134. }
  1135. }
  1136. }
  1137. er.phc = getMore(info, no, opth);
  1138. er.plc = getMore(info, no, optl);
  1139. er.afp = afp;
  1140. er.akp = akp;
  1141. }
  1142. catch (Exception ex)
  1143. {
  1144. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测作答记录结算异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1145. }
  1146. }
  1147. public static async Task<List<RGroupList>> Activity(CoreAPIHttpService _coreAPIHttpService, ExamInfo info, List<string> classes, CosmosClient client, DingDing _dingDing, List<string> sub, List<ExamClassResult> results)
  1148. {
  1149. List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
  1150. if (info.groupLists.Count > 0)
  1151. {
  1152. var group = info.groupLists;
  1153. foreach (var gp in group)
  1154. {
  1155. foreach (KeyValuePair<string, List<string>> pp in gp)
  1156. {
  1157. ps.Add((pp.Key, pp.Value));
  1158. }
  1159. }
  1160. }
  1161. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, classes, info.school, ps);
  1162. var addStudentsCls = tchList.FindAll(x => x.type == 2);
  1163. var addTmdidsCls = tchList.FindAll(x => x.type == 1);
  1164. List<StuActivity> stuActivities = new List<StuActivity>();
  1165. List<StuActivity> tmdActivities = new List<StuActivity>();
  1166. var papers = info.papers.GroupBy(c => c.subjectId).Select(x => new
  1167. {
  1168. subject = x.Key,
  1169. blob = x.ToList().Select(z => z.blob).ToList()
  1170. });
  1171. bool flag = info.papers.Exists(c => c.subjectId != null);
  1172. if (addTmdidsCls.IsNotEmpty())
  1173. {
  1174. addTmdidsCls.ForEach(x =>
  1175. {
  1176. HashSet<string> classIds = new HashSet<string>();
  1177. classLists.ForEach(z =>
  1178. {
  1179. z.members.ForEach(y =>
  1180. {
  1181. if (y.id.Equals(x.id) && y.type == 1)
  1182. {
  1183. classIds.Add(z.id);
  1184. }
  1185. });
  1186. });
  1187. bool iss = false;
  1188. //标记学生作答状态
  1189. int ts = 0;
  1190. if (results.Count > 0)
  1191. {
  1192. foreach (ExamClassResult exam in results)
  1193. {
  1194. int index = exam.studentIds.IndexOf(x.id);
  1195. if (index != -1)
  1196. {
  1197. if (exam.studentAnswers[index].Count > 0)
  1198. {
  1199. bool flag = exam.studentScores[index].Exists(x => x == -1);
  1200. if (!flag)
  1201. {
  1202. ts = 1;
  1203. iss = true;
  1204. break;
  1205. }
  1206. else
  1207. {
  1208. ts = 0;
  1209. }
  1210. }
  1211. else
  1212. {
  1213. ts = -1;
  1214. }
  1215. }
  1216. }
  1217. }
  1218. else
  1219. {
  1220. ts = -1;
  1221. }
  1222. tmdActivities.Add(new StuActivity
  1223. {
  1224. pk = "Activity",
  1225. id = info.id,
  1226. code = $"Activity-{x.id}",
  1227. type = "Exam",
  1228. name = info.name,
  1229. source = info.source,
  1230. startTime = info.startTime,
  1231. endTime = info.endTime,
  1232. scode = info.code,
  1233. scope = info.scope,
  1234. school = info.school,
  1235. creatorId = info.creatorId,
  1236. subjects = sub,
  1237. blob = null,
  1238. paper = flag ? papers.Select(c => new
  1239. {
  1240. c.subject,
  1241. blob = c.blob[new Random().Next(c.blob.Count)]
  1242. }) : "",
  1243. owner = info.owner,
  1244. createTime = info.createTime,
  1245. taskStatus = ts,
  1246. qamode = info.qamode,
  1247. ext = new Dictionary<string, JsonElement>() { { "type", info.examType.ToJsonString().ToObject<JsonElement>() },
  1248. { "subjects", info.subjects.ToJsonString().ToObject<JsonElement>() } },
  1249. sStatus = iss ? 1 : 0,
  1250. classIds = classIds.ToList()
  1251. }); ;
  1252. });
  1253. }
  1254. if (addStudentsCls.IsNotEmpty())
  1255. {
  1256. addStudentsCls.ForEach(x =>
  1257. {
  1258. HashSet<string> classIds = new HashSet<string>();
  1259. classLists.ForEach(z =>
  1260. {
  1261. z.members.ForEach(y =>
  1262. {
  1263. if (y.id.Equals(x.id) && y.code.Equals(info.school) && y.type == 2)
  1264. {
  1265. classIds.Add(z.id);
  1266. }
  1267. });
  1268. });
  1269. bool iss = false;
  1270. //标记学生作答状态
  1271. int ts = 0;
  1272. if (results.Count > 0)
  1273. {
  1274. foreach (ExamClassResult exam in results)
  1275. {
  1276. int index = exam.studentIds.IndexOf(x.id);
  1277. if (index != -1)
  1278. {
  1279. if (exam.studentAnswers[index].Count > 0)
  1280. {
  1281. bool flag = exam.studentScores[index].Exists(x => x == -1);
  1282. if (!flag)
  1283. {
  1284. ts = 1;
  1285. iss = true;
  1286. break;
  1287. }
  1288. else
  1289. {
  1290. ts = 0;
  1291. }
  1292. }
  1293. else
  1294. {
  1295. ts = -1;
  1296. }
  1297. }
  1298. }
  1299. }
  1300. else
  1301. {
  1302. ts = -1;
  1303. }
  1304. stuActivities.Add(new StuActivity
  1305. {
  1306. pk = "Activity",
  1307. id = info.id,
  1308. code = $"Activity-{x.code.Replace("Base-", "")}-{x.id}",
  1309. type = "Exam",
  1310. name = info.name,
  1311. source = info.source,
  1312. startTime = info.startTime,
  1313. endTime = info.endTime,
  1314. scode = info.code,
  1315. scope = info.scope,
  1316. school = info.school,
  1317. creatorId = info.creatorId,
  1318. subjects = sub,
  1319. blob = null,
  1320. paper = flag ? papers.Select(c => new
  1321. {
  1322. c.subject,
  1323. blob = c.blob[new Random().Next(c.blob.Count)]
  1324. }) : "",
  1325. owner = info.owner,
  1326. classIds = classIds.ToList(),
  1327. createTime = info.createTime,
  1328. qamode = info.qamode,
  1329. ext = new Dictionary<string, JsonElement>() { { "type", info.examType.ToJsonString().ToObject<JsonElement>() },
  1330. { "subjects", info.subjects.ToJsonString().ToObject<JsonElement>() } },
  1331. taskStatus = ts,
  1332. sStatus = iss ? 1 : 0,
  1333. });
  1334. });
  1335. }
  1336. await IESActivityService.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities, null);
  1337. return classLists;
  1338. }
  1339. public static async Task<List<double>> knowledgeCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, List<ExamClassResult> classResults,
  1340. double rhwCount, double rhw, double rhlCount, double rhl, AzureCosmosFactory _azureCosmos)
  1341. {
  1342. List<double> akp = new();
  1343. try
  1344. {
  1345. int phcount = 0;
  1346. int plcount = 0;
  1347. //存放并去重知识点
  1348. HashSet<string> kname = new HashSet<string>();
  1349. if (info.papers[no].knowledge.Count > 0)
  1350. {
  1351. info.papers[no].knowledge.ForEach(kno =>
  1352. {
  1353. kno.ForEach(k =>
  1354. {
  1355. kname.Add(k);
  1356. });
  1357. });
  1358. List<string> knowledgeName = new List<string>();
  1359. foreach (string cla in kname)
  1360. {
  1361. knowledgeName.Add(cla);
  1362. }
  1363. for (int k = 0; k < knowledgeName.Count; k++)
  1364. {
  1365. if (null == knowledgeName[k])
  1366. {
  1367. knowledgeName.Remove(knowledgeName[k]);
  1368. }
  1369. }
  1370. foreach (ExamClassResult classResult in classResults)
  1371. {
  1372. if (classResult.subjectId.Equals(subject.id))
  1373. {
  1374. //List<int> phc = new List<int>();
  1375. List<int> ph = new List<int>();
  1376. List<int> pl = new List<int>();
  1377. List<int> pc = new List<int>();
  1378. List<double> persent = new List<double>();
  1379. int lostStu = classResult.status.Where(c => c == 1).ToList().Count;
  1380. for (int i = 0; i < knowledgeName.Count; i++)
  1381. {
  1382. //初始化单个知识点得分
  1383. double score = 0;
  1384. int n = 0;
  1385. int phCount = 0;
  1386. int plCount = 0;
  1387. int pCount = 0;
  1388. double classScore = 0;
  1389. foreach (List<string> str in info.papers[no].knowledge)
  1390. {
  1391. if (str.Contains(knowledgeName[i]))
  1392. {
  1393. var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
  1394. classScore += info.papers[no].point.Count > 0 ? (info.papers[no].point[n] * itemPersent) : 0;
  1395. foreach (string id in classResult.studentIds)
  1396. {
  1397. int index = classResult.studentIds.IndexOf(id);
  1398. if (classResult.studentScores.Count > 0)
  1399. {
  1400. if (classResult.studentScores[index].Count > 0)
  1401. {
  1402. double realScore = classResult.studentScores[index][n] == -1 ? 0 : classResult.studentScores[index][n] * itemPersent;
  1403. score += realScore;
  1404. //score += classResult.studentScores[index][n] == -1 ? 0 : classResult.studentScores[index][n] * itemPersent;
  1405. if (classResult.studentScores[index].Sum() >= rhw && phcount < rhwCount)
  1406. {
  1407. if (classResult.studentScores[index][n] <= 0)
  1408. {
  1409. phCount++;
  1410. }
  1411. phcount++;
  1412. continue;
  1413. }
  1414. if (classResult.studentScores[index].Sum() <= rhl && plcount < (info.stuCount - rhlCount))
  1415. {
  1416. if (classResult.studentScores[index][n] <= 0)
  1417. {
  1418. plCount++;
  1419. }
  1420. plcount++;
  1421. continue;
  1422. }
  1423. if (classResult.studentScores[index][n] <= 0)
  1424. {
  1425. pCount++;
  1426. }
  1427. }
  1428. }
  1429. }
  1430. }
  1431. n++;
  1432. }
  1433. pc.Add(pCount);
  1434. ph.Add(phCount);
  1435. pl.Add(plCount);
  1436. double per = classResult.studentIds.Count - lostStu > 0 ? Math.Round(score / (classResult.studentIds.Count - lostStu), 2) : 0;
  1437. persent.Add(classScore > 0 ? Math.Round(per * 1.0 / classScore, 2) : 0);
  1438. }
  1439. classResult.phc = ph;
  1440. classResult.plc = pl;
  1441. classResult.pc = pc;
  1442. classResult.krate = persent;
  1443. }
  1444. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new Azure.Cosmos.PartitionKey($"{classResult.code}"));
  1445. }
  1446. foreach (string k in knowledgeName)
  1447. {
  1448. double score = 0;
  1449. double allScore = 0;
  1450. int count = 0;
  1451. int m = 0;
  1452. foreach (List<string> str in info.papers[no].knowledge)
  1453. {
  1454. if (str.Contains(k))
  1455. {
  1456. var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
  1457. allScore += info.papers[no].point.Count > 0 ? info.papers[no].point[m] * itemPersent : 0;
  1458. }
  1459. m++;
  1460. }
  1461. foreach (ExamClassResult result in classResults)
  1462. {
  1463. if (result.subjectId.Equals(subject.id))
  1464. {
  1465. int n = 0;
  1466. foreach (List<string> str in info.papers[no].knowledge)
  1467. {
  1468. if (str.Contains(k))
  1469. {
  1470. var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
  1471. if (result.studentScores.Count > 0)
  1472. {
  1473. foreach (List<double> sc in result.studentScores)
  1474. {
  1475. double tsc = sc[n] == -1 ? 0 : sc[n];
  1476. score += (tsc * itemPersent);
  1477. }
  1478. }
  1479. }
  1480. n++;
  1481. }
  1482. count += result.studentIds.Count;
  1483. }
  1484. }
  1485. double per = count - info.lostStu.Count > 0 ? Math.Round(score / (count - info.lostStu.Count), 2) : 0;
  1486. akp.Add(allScore > 0 ? Math.Round(per / allScore, 2) : 0);
  1487. }
  1488. }
  1489. return akp;
  1490. }
  1491. catch (Exception ex)
  1492. {
  1493. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测知识点结算异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1494. return null;
  1495. }
  1496. }
  1497. public static async Task<List<double>> fieldCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, List<ExamClassResult> classResults,
  1498. double rhwCount, double rhw, double rhlCount, double rhl, AzureCosmosFactory _azureCosmos)
  1499. {
  1500. List<double> afp = new();
  1501. try
  1502. {
  1503. int phcount = 0;
  1504. int plcount = 0;
  1505. //存放并去重知识点
  1506. List<int> knowledgeName = new List<int>() { 1, 2, 3, 4, 5, 6 };
  1507. /* knowledgeName.Add(1);
  1508. knowledgeName.Add(2);
  1509. knowledgeName.Add(3);
  1510. knowledgeName.Add(4);
  1511. knowledgeName.Add(5);
  1512. knowledgeName.Add(6);*/
  1513. foreach (ExamClassResult classResult in classResults)
  1514. {
  1515. if (classResult.subjectId.Equals(subject.id))
  1516. {
  1517. //List<int> phc = new List<int>();
  1518. List<int> ph = new List<int>();
  1519. List<int> pl = new List<int>();
  1520. List<int> pc = new List<int>();
  1521. List<double> persent = new List<double>();
  1522. int lostStu = classResult.status.Where(c => c == 1).ToList().Count;
  1523. for (int i = 0; i < knowledgeName.Count; i++)
  1524. {
  1525. //初始化单个知识点得分
  1526. double score = 0;
  1527. int n = 0;
  1528. int phCount = 0;
  1529. int plCount = 0;
  1530. int pCount = 0;
  1531. double classScore = 0;
  1532. if (info.papers[no].field.Count > 0)
  1533. {
  1534. foreach (int str in info.papers[no].field)
  1535. {
  1536. if (str == knowledgeName[i])
  1537. {
  1538. var itemPersent = 1;
  1539. classScore += info.papers[no].point.Count > 0 ? info.papers[no].point[n] * itemPersent : 0;
  1540. foreach (string id in classResult.studentIds)
  1541. {
  1542. int index = classResult.studentIds.IndexOf(id);
  1543. if (classResult.studentScores.Count > 0)
  1544. {
  1545. if (classResult.studentScores[index].Count > 0)
  1546. {
  1547. score += classResult.studentScores[index][n] == -1 ? 0 : classResult.studentScores[index][n];
  1548. if (classResult.studentScores[index].Sum() >= rhw && phcount < rhwCount)
  1549. {
  1550. if (classResult.studentScores[index][n] <= 0)
  1551. {
  1552. phCount++;
  1553. }
  1554. phcount++;
  1555. continue;
  1556. }
  1557. if (classResult.studentScores[index].Sum() <= rhl && plcount < (info.stuCount - rhlCount))
  1558. {
  1559. if (classResult.studentScores[index][n] <= 0)
  1560. {
  1561. plCount++;
  1562. }
  1563. plcount++;
  1564. continue;
  1565. }
  1566. if (classResult.studentScores[index][n] <= 0)
  1567. {
  1568. pCount++;
  1569. }
  1570. }
  1571. }
  1572. }
  1573. }
  1574. n++;
  1575. }
  1576. pc.Add(pCount);
  1577. ph.Add(phCount);
  1578. pl.Add(plCount);
  1579. double per = classResult.studentIds.Count - lostStu > 0 ? Math.Round(score / (classResult.studentIds.Count - lostStu), 2) : 0;
  1580. persent.Add(classScore > 0 ? Math.Round(per / classScore, 2) : 0);
  1581. }
  1582. }
  1583. classResult.fphc = ph;
  1584. classResult.fplc = pl;
  1585. classResult.fpc = pc;
  1586. classResult.frate = persent;
  1587. }
  1588. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new Azure.Cosmos.PartitionKey($"{classResult.code}"));
  1589. }
  1590. for (int i = 0; i < knowledgeName.Count; i++)
  1591. {
  1592. double score = 0;
  1593. double allScore = 0;
  1594. int count = 0;
  1595. int m = 0;
  1596. foreach (int str in info.papers[no].field)
  1597. {
  1598. if (str == knowledgeName[i])
  1599. {
  1600. var itemPersent = 1;
  1601. allScore += info.papers[no].point.Count > 0 ? info.papers[no].point[m] * itemPersent : 0;
  1602. }
  1603. m++;
  1604. }
  1605. foreach (ExamClassResult result in classResults)
  1606. {
  1607. if (result.subjectId.Equals(subject.id))
  1608. {
  1609. int n = 0;
  1610. foreach (int str in info.papers[no].field)
  1611. {
  1612. var itemPersent = 1;
  1613. if (str == knowledgeName[i])
  1614. {
  1615. if (result.studentScores.Count > 0)
  1616. {
  1617. foreach (List<double> sc in result.studentScores)
  1618. {
  1619. double tsc = sc[n] == -1 ? 0 : sc[n];
  1620. score += tsc * itemPersent;
  1621. }
  1622. }
  1623. }
  1624. n++;
  1625. }
  1626. count += result.studentIds.Count;
  1627. }
  1628. }
  1629. double per = count - info.lostStu.Count > 0 ? Math.Round(score / (count - info.lostStu.Count), 2) : 0;
  1630. afp.Add(allScore > 0 ? Math.Round(per / allScore, 2) : 0);
  1631. }
  1632. return afp;
  1633. }
  1634. catch (Exception ex)
  1635. {
  1636. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测认知层次结算异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1637. return null;
  1638. }
  1639. }
  1640. //处理选题计数
  1641. public static List<Dictionary<string, int>> getMore(ExamInfo info, int no, List<List<List<string>>> list)
  1642. {
  1643. List<Dictionary<string, int>> recorde = new List<Dictionary<string, int>>();
  1644. try
  1645. {
  1646. for (int i = 0; i < info.papers[no].answers.Count; i++)
  1647. {
  1648. if (info.papers[no].answers[i].Count <= 0)
  1649. {
  1650. recorde.Add(new Dictionary<string, int>());
  1651. continue;
  1652. }
  1653. Dictionary<string, int> optCount = new Dictionary<string, int>();
  1654. foreach (List<List<string>> stu in list)
  1655. {
  1656. if (stu.Count == info.papers[no].answers.Count)
  1657. {
  1658. var item = stu[i];
  1659. foreach (string opt in item)
  1660. {
  1661. if (optCount.ContainsKey(opt))
  1662. {
  1663. optCount[opt] = optCount[opt] + 1;
  1664. }
  1665. else
  1666. {
  1667. optCount[opt] = 1;
  1668. }
  1669. }
  1670. }
  1671. }
  1672. recorde.Add(optCount);
  1673. }
  1674. return recorde;
  1675. }
  1676. catch (Exception)
  1677. {
  1678. return recorde;
  1679. }
  1680. }
  1681. public static async Task createClassResultAsync(ExamInfo info, List<ExamClassResult> examClassResults, ExamSubject subject, int no, AzureCosmosFactory _azureCosmos, DingDing _dingDing, AzureStorageFactory _azureStorage, IHttpClientFactory _httpClient, IConfiguration _configuration)
  1682. {
  1683. //保证试卷信息与科目信息同步
  1684. ExamResult result = new ExamResult();
  1685. //人数总和
  1686. int Count = 0;
  1687. int m = 0;
  1688. double score = 0;
  1689. //标准差
  1690. //double powSum = 0;
  1691. double allScore = info.papers[no].point.Sum();
  1692. List<ClassRange> classRanges = new List<ClassRange>();
  1693. List<string> lostStu = new List<string>();
  1694. List<double> csRate = new List<double>();
  1695. List<List<List<string>>> opt = new List<List<List<string>>>();
  1696. //List<Task<ItemResponse<ExamClassResult>>> tasks = new();
  1697. foreach (ExamClassResult classResult in examClassResults)
  1698. {
  1699. double classSrate = 0;
  1700. if (classResult.subjectId.Equals(subject.id))
  1701. {
  1702. foreach (List<List<string>> op in classResult.ans)
  1703. {
  1704. opt.Add(op);
  1705. }
  1706. //记录缺考学生索引位置
  1707. int index_stu = 0;
  1708. foreach (var ans in classResult.studentAnswers)
  1709. {
  1710. if (ans.Count == 0)
  1711. {
  1712. if (!lostStu.Contains(classResult.studentIds[index_stu]))
  1713. {
  1714. lostStu.Add(classResult.studentIds[index_stu]);
  1715. }
  1716. }
  1717. else
  1718. {
  1719. if (classResult.status[index_stu] == 1)
  1720. {
  1721. if (!lostStu.Contains(classResult.studentIds[index_stu]))
  1722. {
  1723. lostStu.Add(classResult.studentIds[index_stu]);
  1724. }
  1725. }
  1726. }
  1727. index_stu++;
  1728. }
  1729. int index = 0;
  1730. foreach (List<double> scores in classResult.studentScores)
  1731. {
  1732. List<double> newScores = new List<double>();
  1733. //int count = 0;
  1734. if (scores.Count > 0)
  1735. {
  1736. foreach (double sc in scores)
  1737. {
  1738. newScores.Add(sc > -1 ? sc : 0);
  1739. }
  1740. }
  1741. else
  1742. {
  1743. newScores.Add(0);
  1744. }
  1745. classSrate += newScores.Sum();
  1746. score += newScores.Sum();
  1747. result.studentScores.Add(newScores);
  1748. index++;
  1749. }
  1750. //处理班级信息
  1751. ClassRange range = new ClassRange();
  1752. range.id = classResult.info.id;
  1753. range.name = classResult.info.name;
  1754. range.gradeId = classResult.gradeId;
  1755. List<int> ran = new List<int>();
  1756. int stuCount = classResult.studentIds.Count;
  1757. //todo 与实际的缺考人数比较
  1758. int lostStus = classResult.status.Where(c => c == 1).ToList().Count;
  1759. Count += stuCount;
  1760. if (m == 0)
  1761. {
  1762. ran.Add(0);
  1763. ran.Add(stuCount - 1);
  1764. }
  1765. else
  1766. {
  1767. ran.Add(Count - stuCount);
  1768. ran.Add(Count - 1);
  1769. }
  1770. m++;
  1771. range.range = ran;
  1772. classRanges.Add(range);
  1773. //处理学生ID
  1774. foreach (string id in classResult.studentIds)
  1775. {
  1776. result.studentIds.Add(id);
  1777. }
  1778. if (allScore > 0)
  1779. {
  1780. csRate.Add(classResult.studentIds.Count - lostStus > 0 ? Math.Round(classSrate * 1.0 / (classResult.studentIds.Count - lostStus), 2) : 0 / allScore);
  1781. }
  1782. else
  1783. {
  1784. csRate.Add(0);
  1785. }
  1786. //powSum += Math.Pow(classSrate - result.average, 2);
  1787. //处理选项计数内容
  1788. }
  1789. //tasks.Add(_azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new PartitionKey($"{classResult.code}")));
  1790. }
  1791. //await tasks.TaskPage(10);
  1792. /*foreach (string id in result.lostStus) {
  1793. if (!examClassResults[0].studentIds.Contains(id)) {
  1794. int index = result.lostStus.IndexOf(id);
  1795. result.lostStus.RemoveAt(index);
  1796. }
  1797. }*/
  1798. //处理人员变更时被移除的人员
  1799. result.lostStus = lostStu;
  1800. List<string> stuIds = examClassResults.SelectMany(x => x.studentIds).ToList();
  1801. if (result.lostStus.Count > 0)
  1802. {
  1803. for (int i = 0; i < result.lostStus.Count; i++)
  1804. {
  1805. if (!stuIds.Contains(result.lostStus[i]))
  1806. {
  1807. result.lostStus.RemoveAt(i);
  1808. }
  1809. }
  1810. }
  1811. result.record = getMore(info, no, opt);
  1812. result.average = result.studentIds.Count - result.lostStus.Count > 0 ? Math.Round(score * 1.0 / (result.studentIds.Count - result.lostStus.Count), 2) : 0;
  1813. double powSum = 0;
  1814. //int sco = 0;
  1815. result.studentIds.ForEach(x =>
  1816. {
  1817. double sc = result.studentScores[result.studentIds.IndexOf(x)].Sum();
  1818. if (!result.lostStus.Contains(x))
  1819. {
  1820. powSum += Math.Pow(sc - result.average, 2);
  1821. }
  1822. });
  1823. result.standard = Math.Round((result.studentIds.Count - result.lostStus.Count) > 0 ? Math.Pow(powSum / (result.studentIds.Count - result.lostStus.Count), 0.5) : 0, 2);
  1824. result.csRate = csRate;
  1825. result.sRate = allScore > 0 ? Math.Round(result.average / allScore * 100, 2) : 0;
  1826. result.classes = classRanges;
  1827. result.code = "ExamResult-" + info.id;
  1828. result.school = info.school;
  1829. result.id = subject.id;
  1830. result.examId = info.id;
  1831. result.subjectId = subject.id;
  1832. result.year = info.year;
  1833. result.paper = info.papers[no];
  1834. //result.point = info.papers[j].point;
  1835. result.scope = info.scope;
  1836. result.name = info.name;
  1837. result.time = info.startTime;
  1838. await examRecordCount(info, subject, _dingDing, no, result, examClassResults, _azureCosmos);
  1839. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").UpsertItemAsync(result, new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}"));
  1840. List<ErrorItems> errorItems = new();
  1841. string code = string.Empty;
  1842. string pk = string.Empty;
  1843. string table = "School";
  1844. if (info.scope.Equals("school"))
  1845. {
  1846. code = $"ErrorItems-{info.school}";
  1847. pk = $"Item-{info.school}";
  1848. }
  1849. else
  1850. {
  1851. code = "ErrorItems";
  1852. pk = $"Item-{info.creatorId}";
  1853. table = "Teacher";
  1854. }
  1855. string sqlqueryText = $"select value(c) from c where c.activityId = '{info.id}'and c.subjectId = '{info.subjects[no].id}' and c.stuId in ({string.Join(",", result.studentIds.Select(x => $"'{x}'"))})";
  1856. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Student").GetItemQueryIterator<ErrorItems>(queryText: sqlqueryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{code}") }))
  1857. {
  1858. errorItems.Add(item);
  1859. }
  1860. try {
  1861. /* bool isError = examClassResults.SelectMany(c => c.status).ToList().Exists(z => z == 1);
  1862. if () {
  1863. }*/
  1864. if (errorItems.Count == 0 && info.qamode != 2)
  1865. {
  1866. // 新增逻辑 收集错题内容
  1867. BlobDownloadResult index_json;
  1868. if (info.scope.Equals("school"))
  1869. {
  1870. index_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{info.papers[no].blob}/index.json").DownloadContentAsync();
  1871. }
  1872. else
  1873. {
  1874. index_json = await _azureStorage.GetBlobContainerClient($"{info.creatorId}").GetBlobClient($"{info.papers[no].blob}/index.json").DownloadContentAsync();
  1875. }
  1876. //BlobDownloadResult index_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{info.papers[no].blob}/index.json").DownloadContentAsync();
  1877. JsonElement RecordingJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(index_json.Content.ToString()))).RootElement;
  1878. RecordingJson.TryGetProperty("slides", out JsonElement slides);
  1879. var sdes = slides.ToObject<List<Slides>>();
  1880. List<string> attachments = new List<string>();
  1881. if (info.qamode == 1)
  1882. {
  1883. attachments = RecordingJson.GetProperty("attachments").ToObject<List<string>>();
  1884. if (attachments.Count == 0)
  1885. {
  1886. return;
  1887. }
  1888. }
  1889. List<string> urls = new();
  1890. foreach (var ne in sdes)
  1891. {
  1892. if (!ne.type.Equals("compose"))
  1893. {
  1894. urls.Add(ne.url);
  1895. }
  1896. }
  1897. // 获取整体的题目ID集合
  1898. List<string> ids = new();
  1899. List<(string id, string pid, int level, string type, List<string> knows)> itemInfos = new();
  1900. foreach (string url in urls)
  1901. {
  1902. string id = url.Replace(".json", "");
  1903. BlobDownloadResult index_item_json;
  1904. if (info.scope.Equals("school"))
  1905. {
  1906. index_item_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{info.papers[no].blob}/{url}").DownloadContentAsync();
  1907. }
  1908. else
  1909. {
  1910. index_item_json = await _azureStorage.GetBlobContainerClient($"{info.creatorId}").GetBlobClient($"{info.papers[no].blob}/{url}").DownloadContentAsync();
  1911. }
  1912. JObject keys = JObject.Parse(index_item_json.Content.ToString());
  1913. string type = keys["exercise"].Value<string>("type");
  1914. int level = keys["exercise"].Value<int>("level");
  1915. var knowledge = keys["exercise"].Value<JArray>("knowledge")?.ToObject<List<string>>();
  1916. string pid = keys.Value<string>("pid");
  1917. itemInfos.Add((id, pid, level, type, knowledge));
  1918. }
  1919. /* double[] point = StringHelper.ListTodouble(result.paper.point);
  1920. double[,] res = StringHelper.ListToDouble(result.studentScores);
  1921. var cdm = new ClouDASMatrix(res, point);*/
  1922. //需要努力的题目
  1923. //var ss = cdm.StriveTopic;
  1924. int n = 0;
  1925. List<Task<ItemResponse<ErrorItems>>> task_error = new();
  1926. List<ErrorItems> errors = new();
  1927. foreach (var sIds in result.studentIds)
  1928. {
  1929. ErrorItems error = new()
  1930. {
  1931. ttl = -1,
  1932. code = code,
  1933. id = Guid.NewGuid().ToString(),
  1934. stuId = sIds,
  1935. school = info.school,
  1936. activityId = info.id,
  1937. subjectId = result.subjectId,
  1938. time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1939. };
  1940. int index_stu = result.studentIds.IndexOf(sIds);
  1941. //顺序学生错题的索引
  1942. var itemScore = result.studentScores[index_stu];
  1943. List<int> index = new();
  1944. int index_item = 0;
  1945. foreach (var sc in itemScore)
  1946. {
  1947. if (sc == 0)
  1948. {
  1949. index.Add(index_item + 1);
  1950. }
  1951. index_item++;
  1952. }
  1953. if (index.Count == 0)
  1954. {
  1955. continue;
  1956. }
  1957. //int[] item_index = ss[n];
  1958. foreach (var item in index)
  1959. {
  1960. Items items = new()
  1961. {
  1962. id = urls[item - 1].Replace(".json", ""),
  1963. blob = info.papers[no].blob
  1964. };
  1965. items.level = itemInfos.Where(c => c.id.Equals(items.id)).FirstOrDefault().level;
  1966. items.type = itemInfos.Where(c => c.id.Equals(items.id)).FirstOrDefault().type;
  1967. items.pId = itemInfos.Where(c => c.id.Equals(items.id)).FirstOrDefault().pid;
  1968. items.knowledge = itemInfos.Where(c => c.id.Equals(items.id)).FirstOrDefault().knows;
  1969. items.qamode = info.qamode;
  1970. error.its.Add(items);
  1971. }
  1972. errors.Add(error);
  1973. n++;
  1974. task_error.Add(_azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(error, new PartitionKey($"{error.code}")));
  1975. }
  1976. //string connect = _configuration.GetValue<string>("HaBookAuth:Crtmabank") + "https://malearnfunction.chinacloudsites.cn/api/crtmabank";
  1977. string location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
  1978. string urlAction = string.Empty;
  1979. string accessKey = string.Empty;
  1980. if (location.Contains("China"))
  1981. {
  1982. if (location.Equals("China")) //大陸正式站
  1983. {
  1984. urlAction = "https://malearn.teammodel.cn";
  1985. accessKey = "2BcXFR_hvzG1pZjqIkaM7Dx74Hcu6m0PwwOacFpDpq44AzFuHJBRXA==";
  1986. }
  1987. else if (location.Equals("China-Dep") || location.Equals("China-Test")) //大陸測試站
  1988. {
  1989. urlAction = "https://malearn-rc.teammodel.cn";
  1990. accessKey = "lghWhJduNiAlo-e8isqEoROjdR7DAC-50XNtanIwHKYlAzFu1aog_A==";
  1991. }
  1992. }
  1993. else if (location.Contains("Global"))
  1994. {
  1995. if (location.Equals("Global")) //國際正式站
  1996. {
  1997. urlAction = "https://malearn.teammodel.net";
  1998. accessKey = "I-2lTcdggJkZWSBwOXQIm4oHx-huwX3d0wLe-9pgojThAzFuq_KNFg==";
  1999. }
  2000. else if (location.Equals("Global-Test")) //國際測試站
  2001. {
  2002. urlAction = "https://malearn-rc.teammodel.net";
  2003. accessKey = "_l4Cb_tHIRBw_iv3ZuwVqjkMwjg4_HtDaxhAmZ8OwJraAzFu_DAY8A==";
  2004. }
  2005. }
  2006. string connect = $"{urlAction}/api/crtmabank";
  2007. var htc = _httpClient.CreateClient();
  2008. if (htc.DefaultRequestHeaders.Contains("x-functions-key"))
  2009. {
  2010. htc.DefaultRequestHeaders.Remove("x-functions-key");
  2011. }
  2012. htc.DefaultRequestHeaders.Add("x-functions-key", accessKey);
  2013. ///智慧題庫school欄位修正
  2014. foreach (ErrorItems error in errors)
  2015. {
  2016. error.school = (info.scope.Equals("school")) ? info.school : string.Empty;
  2017. }
  2018. string paramJson = JsonConvert.SerializeObject(errors);
  2019. var content = new StringContent(paramJson, Encoding.UTF8, "application/json");
  2020. var response = await htc.PostAsync(connect, content);
  2021. if ((int)response.StatusCode == 200)
  2022. {
  2023. await task_error.TaskPage(10);
  2024. }
  2025. }
  2026. }
  2027. catch (Exception e)
  2028. {
  2029. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测错题异常{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  2030. }
  2031. }
  2032. public class Settlement
  2033. {
  2034. public double rate { get; set; }
  2035. public double score { get; set; }
  2036. public List<string> stus { get; set; } = new List<string>();
  2037. public int total { get; set; }
  2038. public double qrate { get; set; }
  2039. }
  2040. #region ===學習記錄用類別===
  2041. private class PaperIndex
  2042. {
  2043. public PaperIndex()
  2044. {
  2045. slides = new List<Slide>();
  2046. }
  2047. public List<Slide> slides { get; set; }
  2048. }
  2049. private class Slide
  2050. {
  2051. /// <summary>
  2052. /// blob 路徑
  2053. /// </summary>
  2054. public string url { get; set; }
  2055. /// <summary>
  2056. /// 題型
  2057. /// </summary>
  2058. public string type { get; set; }
  2059. /// <summary>
  2060. /// scoring
  2061. /// </summary>
  2062. public Scoring scoring { get; set; }
  2063. }
  2064. private class Scoring
  2065. {
  2066. /// <summary>
  2067. /// knowledge
  2068. /// </summary>
  2069. public List<string> knowledge { get; set; }
  2070. /// <summary>
  2071. /// 答案
  2072. /// </summary>
  2073. public List<string> ans { get; set; }
  2074. }
  2075. private class StudentAnswers
  2076. {
  2077. /// <summary>
  2078. /// 學生作答 blob 路徑
  2079. /// </summary>
  2080. public List<List<string>> studentAnswers { get; set; }
  2081. /// <summary>
  2082. /// 學生ID
  2083. /// </summary>
  2084. public List<string> studentIds { get; set; } = new();
  2085. }
  2086. private class QuestionData
  2087. {
  2088. public QuestionData()
  2089. {
  2090. item = new List<QuestionItem>();
  2091. }
  2092. public QuestionExercise exercise { get; set; }
  2093. public List<QuestionItem> item { get; set; }
  2094. }
  2095. private class QuestionItem
  2096. {
  2097. public QuestionItem()
  2098. {
  2099. option = new List<OptionItem>();
  2100. }
  2101. public string question { get; set; }
  2102. public List<OptionItem> option { get; set; }
  2103. }
  2104. private class OptionItem
  2105. {
  2106. public string code { get; set; }
  2107. public string value { get; set; }
  2108. }
  2109. private class QuestionExercise
  2110. {
  2111. public string type { get; set; }
  2112. public List<string> knowledge { get; set; }
  2113. public List<string> answer { get; set; }
  2114. }
  2115. #endregion
  2116. }
  2117. }