TriggerExam.cs 129 KB

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