JointService.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. using Azure.Messaging.ServiceBus;
  2. using Azure.Storage.Blobs.Models;
  3. using Azure;
  4. using Microsoft.Azure.Cosmos;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Security.Cryptography;
  9. using System.Text;
  10. using System.Text.Json;
  11. using System.Threading.Tasks;
  12. using TEAMModelOS.SDK.DI;
  13. using TEAMModelOS.SDK.Extension;
  14. using TEAMModelOS.SDK.Models.Service.BI;
  15. using TEAMModelOS.SDK.Services;
  16. using static TEAMModelOS.SDK.Models.JointEventGroupBase;
  17. using Azure.Core;
  18. using Microsoft.Extensions.Configuration;
  19. using static TEAMModelOS.SDK.Models.JointEvent;
  20. using TEAMModelOS.SDK.Models.Dtos;
  21. namespace TEAMModelOS.SDK.Models.Service
  22. {
  23. public static class JointService
  24. {
  25. //取得JointExam生成Exam
  26. public static async Task GenerateExamFromJointExamAsync(CosmosClient client, AzureStorageFactory _azureStorage, AzureServiceBusFactory _serviceBus, CoreAPIHttpService _coreAPIHttpService, AzureRedisFactory _azureRedis, IConfiguration _configuration, DingDing _dingDing, JointExam jointExam, string creatorId)
  27. {
  28. try
  29. {
  30. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  31. //取得JointExam
  32. List<JointEventClassBase> classes = new List<JointEventClassBase>();
  33. List<JointEventGroupBase> stuLists = new List<JointEventGroupBase>();
  34. //取得JointCourse ※examType == "custom" 之後再處理
  35. List<JointEventGroupDb> jointCourses = new List<JointEventGroupDb>();
  36. if (!jointExam.examType.Equals("custom")) //熱身賽:老師報名名單
  37. {
  38. string jointCourseSql = $"SELECT * FROM c WHERE c.jointEventId = '{jointExam.jointEventId}' AND c.jointGroupId = '{jointExam.jointGroupId}' AND ( IS_DEFINED(c.type) = false OR c.type = 'regular' )";
  39. if (!string.IsNullOrWhiteSpace(creatorId)) jointCourseSql += $" AND c.creatorId = '{creatorId}' ";
  40. await foreach (var item in client.GetContainer("TEAMModelOS", Constant.Teacher).GetItemQueryIteratorSql<JointEventGroupDb>(queryText: jointCourseSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"JointCourse") }))
  41. {
  42. jointCourses.Add(item);
  43. }
  44. }
  45. else //決賽:決賽名單
  46. {
  47. string jointCourseSql = $"SELECT * FROM c WHERE c.jointEventId = '{jointExam.jointEventId}' AND c.jointGroupId = '{jointExam.jointGroupId}' AND IS_DEFINED(c.type) = true AND c.type = 'custom' ";
  48. if (!string.IsNullOrWhiteSpace(creatorId)) jointCourseSql += $" AND c.creatorId = '{creatorId}' ";
  49. await foreach (var item in client.GetContainer("TEAMModelOS", Constant.Teacher).GetItemQueryIteratorSql<JointEventGroupDb>(queryText: jointCourseSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"JointCourse") }))
  50. {
  51. jointCourses.Add(item);
  52. }
  53. }
  54. //評量資料生成 ExamInfo actExamInfo ※一個課程一個Exam
  55. List<ExamInfo> examList = new List<ExamInfo>();
  56. foreach (JointEventGroupDb jointCourse in jointCourses)
  57. {
  58. string actExamCreatorId = jointCourse.creatorId;
  59. //個人課程
  60. if(jointCourse.scope.Equals("private"))
  61. {
  62. foreach (JointEventGroupCourse jointExamGroupCourse in jointCourse.courseLists)
  63. {
  64. string actExamCourseId = jointExamGroupCourse.courseId;
  65. string actExamCourseName = jointExamGroupCourse.courseName;
  66. //評量資料生成
  67. ExamInfo actExamInfo = new ExamInfo();
  68. ///取得已生成的Exam ※
  69. string examSql = $"SELECT DISTINCT c.id, c.source, c.name, c.jointExamId, c.subjects, c.stuLists, c.targets, c.papers, c.year, c.startTime, c.endTime, c.code, c.owner, c.scope, c.creatorId FROM c JOIN s IN c.subjects WHERE c.jointExamId = '{jointExam.id}' AND s.id = '{actExamCourseId}'";
  70. await foreach (var item in client.GetContainer("TEAMModelOS", Constant.Common).GetItemQueryIteratorSql<ExamInfo>(queryText: examSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Exam-{actExamCreatorId}") }))
  71. {
  72. actExamInfo = item;
  73. }
  74. ///尚無評量資料
  75. if (string.IsNullOrWhiteSpace(actExamInfo.id))
  76. {
  77. actExamInfo.code = $"Exam-{actExamCreatorId}";
  78. actExamInfo.owner = "teacher";
  79. actExamInfo.scope = jointCourse.scope;
  80. actExamInfo.creatorId = actExamCreatorId;
  81. actExamInfo.id = Guid.NewGuid().ToString();
  82. }
  83. actExamInfo.source = jointExam.source;
  84. actExamInfo.name = jointExam.name;
  85. actExamInfo.jointExamId = jointExam.id;
  86. actExamInfo.subjects = new List<ExamSubject>() { new ExamSubject() { id = actExamCourseId, name = actExamCourseName, classCount = jointExamGroupCourse.groupLists.Count } };
  87. ///評量stuLists
  88. foreach (JointEventGroupCourseGroup actGroup in jointExamGroupCourse.groupLists)
  89. {
  90. if(!actExamInfo.stuLists.Contains(actGroup.id))
  91. {
  92. actExamInfo.stuLists.Add(actGroup.id);
  93. }
  94. List<string> targetRow = new List<string>() { actExamCourseId, actGroup.id };
  95. var targetRowJson = JsonSerializer.SerializeToElement(targetRow);
  96. bool add = true;
  97. foreach(JsonElement target in actExamInfo.targets)
  98. {
  99. if(target.ToJsonString().Equals(targetRowJson.ToJsonString()))
  100. {
  101. add = false;
  102. break;
  103. }
  104. }
  105. if(add)
  106. {
  107. actExamInfo.targets.Add(targetRowJson);
  108. }
  109. }
  110. ///試卷
  111. actExamInfo.papers = Newtonsoft.Json.JsonConvert.DeserializeObject<List<PaperSimple>>(Newtonsoft.Json.JsonConvert.SerializeObject(jointExam.papers));
  112. ///時間
  113. actExamInfo.year = DateTimeOffset.UtcNow.Year;
  114. actExamInfo.startTime = jointExam.startTime;
  115. actExamInfo.endTime = jointExam.endTime;
  116. ///是否重複作答
  117. actExamInfo.overwriteDisable = (jointExam.examOverwrite.Equals(false)) ? true : false;
  118. ///(前端)是否可見 ※只有決賽不可見
  119. actExamInfo.jointVisiable = (jointExam.examType.Equals("custom")) ? false : true;
  120. examList.Add(actExamInfo);
  121. }
  122. }
  123. //[待做] 學校班級
  124. }
  125. //生成評量
  126. if (examList.Count > 0)
  127. {
  128. foreach (ExamInfo exam in examList)
  129. {
  130. await GenerateExam(client, _azureStorage, _serviceBus, _coreAPIHttpService, _azureRedis, _configuration, _dingDing, jointExam, exam);
  131. }
  132. }
  133. }
  134. catch (Exception)
  135. {
  136. }
  137. }
  138. //生成評量(單)
  139. private static async Task<string> GenerateExam(CosmosClient client, AzureStorageFactory _azureStorage, AzureServiceBusFactory _serviceBus, CoreAPIHttpService _coreAPIHttpService, AzureRedisFactory _azureRedis, IConfiguration _configuration, DingDing _dingDing, JointExam jointExam, ExamInfo exam)
  140. {
  141. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  142. string Result = string.Empty;
  143. exam.createTime = now;
  144. if (exam.startTime <= 0) exam.startTime = now;
  145. List<(string pId, List<string> gid)> ps = new();
  146. var group = exam.groupLists;
  147. if (group.Count > 0)
  148. {
  149. foreach (var keys in group)
  150. {
  151. foreach (KeyValuePair<string, List<string>> pp in keys)
  152. {
  153. ps.Add((pp.Key, pp.Value));
  154. }
  155. }
  156. }
  157. List<string> classes = ExamService.getClasses(exam.classes, exam.stuLists);
  158. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, classes, exam.school, ps);
  159. exam.stuCount = tchList.Count;
  160. string mode = string.Empty;
  161. ResponseMessage response = null;
  162. if (string.IsNullOrEmpty(exam.id))
  163. {
  164. mode = "add";
  165. }
  166. else
  167. {
  168. response = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(exam.id, new PartitionKey($"{exam.code}"));
  169. if (response.StatusCode == System.Net.HttpStatusCode.OK) mode = "upd";
  170. else mode = "add";
  171. }
  172. //DB操作
  173. if (mode.Equals("add")) //新建
  174. {
  175. if (string.IsNullOrWhiteSpace(exam.id)) exam.id = Guid.NewGuid().ToString();
  176. exam.progress = (exam.startTime > now) ? "pending" : "going";
  177. var messageBlob = new ServiceBusMessage();
  178. if (exam.scope.Equals("school") && !string.IsNullOrWhiteSpace(exam.school))
  179. {
  180. exam.size = await _azureStorage.GetBlobContainerClient(exam.school).GetBlobsSize($"exam/{exam.id}");
  181. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = exam.school }, _serviceBus, _configuration, _azureRedis);
  182. }
  183. else
  184. {
  185. exam.size = await _azureStorage.GetBlobContainerClient(exam.creatorId).GetBlobsSize($"exam/{exam.id}");
  186. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = exam.creatorId }, _serviceBus, _configuration, _azureRedis);
  187. }
  188. int n = 0;
  189. List<string> sheetIds = new List<string>();
  190. foreach (PaperSimple simple in exam.papers)
  191. {
  192. simple.blob = $"/exam/{exam.id}/paper/{exam.subjects[n].id}";
  193. n++;
  194. simple.sheet = null;
  195. }
  196. exam = await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(exam, new PartitionKey($"{exam.code}"));
  197. await BIStats.SetTypeAddStats(client, _dingDing, exam.school, "Exam", 1);//BI统计增/减量
  198. }
  199. else if (response != null) //更新
  200. {
  201. using var json = await JsonDocument.ParseAsync(response.Content);
  202. ExamInfo info = json.ToObject<ExamInfo>();
  203. if (info.progress.Equals("going"))
  204. {
  205. Result = "活动正在进行中,无法修改";
  206. }
  207. var messageBlob = new ServiceBusMessage();
  208. if (exam.scope.Equals("school") && !string.IsNullOrWhiteSpace(exam.school))
  209. {
  210. exam.size = await _azureStorage.GetBlobContainerClient(exam.school).GetBlobsSize($"exam/{exam.id}");
  211. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = $"exam", name = exam.school }, _serviceBus, _configuration, _azureRedis);
  212. }
  213. else
  214. {
  215. exam.size = await _azureStorage.GetBlobContainerClient(exam.creatorId).GetBlobsSize($"exam/{exam.id}");
  216. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = $"exam", name = exam.creatorId }, _serviceBus, _configuration, _azureRedis);
  217. }
  218. exam.progress = info.progress;
  219. int n = 0;
  220. List<string> sheetIds = new List<string>();
  221. foreach (PaperSimple simple in exam.papers)
  222. {
  223. if (!string.IsNullOrEmpty(simple.subjectId))
  224. {
  225. simple.blob = $"/exam/{exam.id}/paper/{simple.subjectId}/{simple.id}";
  226. }
  227. else
  228. {
  229. simple.blob = $"/exam/{exam.id}/paper/{exam.subjects[n].id}";
  230. n++;
  231. }
  232. simple.sheet = null;
  233. }
  234. exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
  235. }
  236. //Blob操作 ※取得試卷源(blob)、複製到評測紀錄下
  237. ///試卷源字典
  238. List<Dictionary<string, string>> sourcePaperInfo = new List<Dictionary<string, string>>();
  239. foreach (PaperSimple paperInfo in jointExam.papers)
  240. {
  241. string paperBlobPath = (!paperInfo.blob.EndsWith("/")) ? paperInfo.blob + "/" : paperInfo.blob;
  242. paperBlobPath = (paperInfo.blob.StartsWith("/")) ? paperBlobPath.Remove(0, 1) : paperBlobPath;
  243. sourcePaperInfo.Add(new Dictionary<string, string>() { { "id", paperInfo.id }, { "blob", paperBlobPath }, { "itemcount", paperInfo.point.Count.ToString() } });
  244. }
  245. bool paperDataCopyErrFlg = false; //試卷資料拷貝錯誤Flag true:拷貝錯誤
  246. //Blob拷貝程序
  247. int paperIndex = 0;
  248. foreach (Dictionary<string, string> sourcePaperInfoDic in sourcePaperInfo)
  249. {
  250. //拷貝源:Container => jointExam.creatorId Path:papers.blob
  251. //拷貝對象:Container => exam.creatorId, Path:exam/{exam.id}/paper/{exam.subjects[paperIndex].id}/
  252. string targetScope = exam.scope; //評測對象 school:校本班級 private:私人課程
  253. var sourceBlobContainer = _azureStorage.GetBlobContainerClient(jointExam.creatorId); //統測活動來源一定是個人
  254. var blobPrivateContainer = (targetScope.Equals("school")) ? _azureStorage.GetBlobContainerClient(exam.school) : _azureStorage.GetBlobContainerClient(exam.creatorId);
  255. string sourceBlobPath = sourcePaperInfoDic["blob"];
  256. string subjectId = exam.subjects[paperIndex].id;
  257. string destBlobPath = $"exam/{exam.id}/paper/{subjectId}/"; //拷貝對象路徑 path:exam/{評測ID}/paper/{subjectID}/
  258. Pageable<BlobItem> sourceBlobs = sourceBlobContainer.GetBlobs(prefix: sourceBlobPath);
  259. if (sourceBlobs.Count() > 0)
  260. {
  261. foreach (var blob in sourceBlobs)
  262. {
  263. var sourceFileBlob = sourceBlobContainer.GetBlobClient(blob.Name);
  264. if (sourceFileBlob.Exists())
  265. {
  266. var sourceFileUri = sourceBlobContainer.GetBlobClient(blob.Name).Uri;
  267. string fileName = blob.Name.Replace(sourceBlobPath, "");
  268. string destBlobFilePath = $"{destBlobPath}{fileName}";
  269. await blobPrivateContainer.GetBlobClient(destBlobFilePath).StartCopyFromUriAsync(sourceFileUri);
  270. }
  271. else
  272. {
  273. paperDataCopyErrFlg = true;
  274. }
  275. }
  276. }
  277. paperIndex++;
  278. }
  279. return Result;
  280. }
  281. //以JointSchedule為單位,判斷班級/課程名單是否完成並生成決賽名單
  282. public static async Task<List<JointEventGroupDb>> CreatePassJointCourseBySchedule(CosmosClient client, string jointEventId, string jointGroupId, string jointScheduleId, string scope)
  283. {
  284. List<JointEventGroupDb> result = new List<JointEventGroupDb>();
  285. //0. 取得jointEvent、JointEventSchedule
  286. JointEvent jointEvent = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<JointEvent>(jointEventId, new PartitionKey("JointEvent"));
  287. if (jointEvent == null)
  288. {
  289. return result;
  290. }
  291. JointEventSchedule jointEventSchedule = jointEvent.schedule.Where(s => s.id.Equals(jointScheduleId)).FirstOrDefault();
  292. if (jointEventSchedule == null)
  293. {
  294. return result;
  295. }
  296. //1. 用jointEventId、jointGroupId 取得所有老師報名的 班級/課程名單
  297. List<JointEventGroupDb> jointEventCourse = new List<JointEventGroupDb>();
  298. StringBuilder stringBuilderJointCourse = new($"SELECT * FROM c WHERE c.jointEventId = '{jointEventId}' AND c.jointGroupId = '{jointGroupId}' AND c.scope = '{scope}' AND (c.type = 'regular' OR NOT IS_DEFINED(c.type) OR IS_NULL(c.type)) ");
  299. string container = (scope.Equals("school")) ? Constant.School : Constant.Teacher;
  300. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, container).GetItemQueryStreamIteratorSql(queryText: stringBuilderJointCourse.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("JointCourse") }))
  301. {
  302. using var json = await JsonDocument.ParseAsync(item.Content);
  303. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  304. {
  305. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  306. {
  307. jointEventCourse.Add(obj.ToObject<JointEventGroupDb>());
  308. }
  309. }
  310. }
  311. //2. 取得本Schedule的所有JointExam
  312. List<string> jointExamIdList = new List<string>();
  313. List<JointExam> jointEventExam = new List<JointExam>();
  314. StringBuilder stringBuilderJointExam = new($"SELECT * FROM c WHERE c.jointEventId = '{jointEventId}' AND c.jointGroupId = '{jointGroupId}' AND c.jointScheduleId = '{jointScheduleId}' ");
  315. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Common).GetItemQueryStreamIteratorSql(queryText: stringBuilderJointExam.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("JointExam") }))
  316. {
  317. using var json = await JsonDocument.ParseAsync(item.Content);
  318. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  319. {
  320. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  321. {
  322. JointExam jointExamRow = obj.ToObject<JointExam>();
  323. jointEventExam.Add(jointExamRow);
  324. if (!jointExamIdList.Contains(jointExamRow.id))
  325. {
  326. jointExamIdList.Add(jointExamRow.id);
  327. }
  328. }
  329. }
  330. }
  331. //3. 取得所有JointExam關聯的Exam
  332. List<ExamInfo> exam = new List<ExamInfo>();
  333. StringBuilder stringBuilderExam = new($"SELECT * FROM c WHERE c.pk = 'Exam' AND ARRAY_CONTAINS({JsonSerializer.Serialize(jointExamIdList)}, c.jointExamId) ");
  334. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Common).GetItemQueryStreamIteratorSql(queryText: stringBuilderExam.ToString(), requestOptions: null))
  335. {
  336. using var json = await JsonDocument.ParseAsync(item.Content);
  337. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  338. {
  339. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  340. {
  341. exam.Add(obj.ToObject<ExamInfo>());
  342. }
  343. }
  344. }
  345. //4. 用 IfJointExamComplete 列出完成評量的 班級/課程名單
  346. List<JointEventGroupPassDto> passGroupsBindJointexam = new List<JointEventGroupPassDto>(); //已完成的課程名單和已完成的JointExam對照表
  347. JointEventSchedule finalSchedule = jointEvent.schedule.Where(s => s.type.Equals("exam") && s.examType.Equals("custom")).FirstOrDefault(); //取schedule中的決賽為jointScheduleId ※應該只會有一個決賽
  348. if (finalSchedule != null) //可取得挑戰賽才繼續
  349. {
  350. foreach (JointExam jointExamRow in jointEventExam)
  351. {
  352. ///第1層 JointExam
  353. List<ExamInfo> examsNow = exam.Where(e => e.jointExamId.Equals(jointExamRow.id)).ToList();
  354. foreach (JointEventGroupDb jointEventCourseRow in jointEventCourse)
  355. {
  356. ///第2層 jointEventCourse
  357. string creatorIdRow = jointEventCourseRow.creatorId;
  358. foreach (JointEventGroupBase.JointEventGroupCourse jointCourseIn in jointEventCourseRow.courseLists)
  359. {
  360. ///第3層 老師報名的course
  361. string courseId = jointCourseIn.courseId;
  362. string courseName = jointCourseIn.courseName;
  363. List<string> groupIds = jointCourseIn.groupLists.Select(c => c.id).ToList();
  364. ExamInfo examNow = examsNow.Where(e => e.creatorId.Equals(creatorIdRow) && e.subjects[0].id.Equals(courseId)).FirstOrDefault();
  365. if (examNow != null)
  366. {
  367. string examId = examNow.id;
  368. string schoolId = string.Empty;
  369. string classId = string.Empty;
  370. foreach (string groupId in groupIds)
  371. {
  372. JointEventGroupBase.JointEventGroupCourseGroup passGroupInfo = await IfExamComplete(client, examId, scope, creatorIdRow, schoolId, classId, groupId);
  373. if (passGroupInfo != null)
  374. {
  375. //生成決賽通過的老師課程名單用中間model
  376. JointEventGroupPassDto passGroupRow = passGroupsBindJointexam.Where(p => p.creatorId.Equals(jointEventCourseRow.creatorId) && p.courseId.Equals(courseId) && p.groupId.Equals(groupId)).FirstOrDefault();
  377. if (passGroupRow == null)
  378. {
  379. passGroupsBindJointexam.Add(new JointEventGroupPassDto()
  380. {
  381. creatorId = jointEventCourseRow.creatorId,
  382. courseId = courseId,
  383. groupId = groupId
  384. });
  385. passGroupRow = passGroupsBindJointexam.Where(p => p.creatorId.Equals(jointEventCourseRow.creatorId) && p.courseId.Equals(courseId) && p.groupId.Equals(groupId)).FirstOrDefault();
  386. }
  387. if (!passGroupRow.jointExamId.Contains(jointExamRow.id))
  388. {
  389. passGroupRow.jointExamId.Add(jointExamRow.id);
  390. }
  391. if (passGroupRow.jointExamId.Count.Equals(jointExamIdList.Count))
  392. {
  393. passGroupRow.pass = true;
  394. }
  395. }
  396. }
  397. }
  398. }
  399. }
  400. }
  401. }
  402. //5. 決賽課程生成
  403. ///生成資料製作
  404. List<JointEventGroupDb> jointCourseCreates = new List<JointEventGroupDb>(); //要生成的老師課程名單
  405. foreach (JointEventGroupDb jointEventCourseRow in jointEventCourse)
  406. {
  407. foreach (JointEventGroupBase.JointEventGroupCourse course in jointEventCourseRow.courseLists)
  408. {
  409. foreach (JointEventGroupBase.JointEventGroupCourseGroup group in course.groupLists)
  410. {
  411. JointEventGroupPassDto passGroupRow = passGroupsBindJointexam.Where(g => g.creatorId.Equals(jointEventCourseRow.creatorId) && g.courseId.Equals(course.courseId) && g.groupId.Equals(group.id) && g.pass.Equals(true)).FirstOrDefault();
  412. if (passGroupRow != null)
  413. {
  414. string courseId = course.courseId;
  415. string courseName = course.courseName;
  416. JointEventGroupDb jointCourseCreateRow = jointCourseCreates.Where(c => c.jointEventId.Equals(jointEventCourseRow.jointEventId) && c.jointGroupId.Equals(jointEventCourseRow.jointGroupId) && c.creatorId.Equals(jointEventCourseRow.creatorId)).FirstOrDefault();
  417. if (jointCourseCreateRow == null)
  418. {
  419. JointEventGroupDb finalEventCourse = new JointEventGroupDb();
  420. finalEventCourse.jointEventId = jointEventCourseRow.jointEventId;
  421. finalEventCourse.jointGroupId = jointEventCourseRow.jointGroupId;
  422. finalEventCourse.code = jointEventCourseRow.code;
  423. finalEventCourse.pk = jointEventCourseRow.pk;
  424. finalEventCourse.scope = jointEventCourseRow.scope;
  425. finalEventCourse.type = "custom"; //決賽
  426. finalEventCourse.creatorId = jointEventCourseRow.creatorId;
  427. finalEventCourse.creatorName = jointEventCourseRow.creatorName;
  428. finalEventCourse.creatorEmail = jointEventCourseRow.creatorEmail;
  429. finalEventCourse.schoolId = jointEventCourseRow.schoolId;
  430. finalEventCourse.schoolName = jointEventCourseRow.schoolName;
  431. finalEventCourse.jointScheduleId = finalSchedule.id;
  432. finalEventCourse.courseLists.Add(new JointEventGroupBase.JointEventGroupCourse()
  433. {
  434. courseId = courseId,
  435. courseName = courseName,
  436. groupLists = new List<JointEventGroupBase.JointEventGroupCourseGroup>() {
  437. new() { id = group.id, name = group.name }
  438. }
  439. });
  440. finalEventCourse.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  441. jointCourseCreates.Add(finalEventCourse);
  442. }
  443. else
  444. {
  445. JointEventGroupBase.JointEventGroupCourse courseRowNow = jointCourseCreateRow.courseLists.Where(c => c.courseId.Equals(courseId)).FirstOrDefault();
  446. if (courseRowNow == null)
  447. {
  448. jointCourseCreateRow.courseLists.Add(
  449. new JointEventGroupBase.JointEventGroupCourse
  450. {
  451. courseId = courseId,
  452. courseName = courseName,
  453. groupLists = new List<JointEventGroupBase.JointEventGroupCourseGroup>() {
  454. new() { id = group.id, name = group.name }
  455. }
  456. }
  457. );
  458. }
  459. else
  460. {
  461. JointEventGroupBase.JointEventGroupCourseGroup groupRowNow = courseRowNow.groupLists.Where(g => g.id.Equals(group.id)).FirstOrDefault();
  462. if (groupRowNow == null)
  463. {
  464. courseRowNow.groupLists.Add(
  465. new() { id = group.id, name = group.name }
  466. );
  467. }
  468. }
  469. }
  470. }
  471. }
  472. }
  473. }
  474. ///DB
  475. if (jointCourseCreates.Count > 0)
  476. {
  477. //取得所有已存在的決賽課程名單
  478. List<JointEventGroupDb> jointCourseFinalExist = new List<JointEventGroupDb>();
  479. StringBuilder stringBuilderJointCourseCreates = new($"SELECT * FROM c WHERE c.jointEventId = '{jointEventId}' AND c.jointGroupId = '{jointGroupId}' AND c.scope = '{scope}' AND c.type = 'custom' AND c.jointScheduleId = '{finalSchedule.id}' ");
  480. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, container).GetItemQueryStreamIteratorSql(queryText: stringBuilderJointCourseCreates.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("JointCourse") }))
  481. {
  482. using var json = await JsonDocument.ParseAsync(item.Content);
  483. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  484. {
  485. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  486. {
  487. jointCourseFinalExist.Add(obj.ToObject<JointEventGroupDb>());
  488. }
  489. }
  490. }
  491. //生成決賽課程名單
  492. foreach (JointEventGroupDb jointCourseCreateRow in jointCourseCreates)
  493. {
  494. JointEventGroupDb jointCourseFinalExistRow = jointCourseFinalExist.Where(j => j.creatorId.Equals(jointCourseCreateRow.creatorId)).FirstOrDefault();
  495. jointCourseCreateRow.id = (jointCourseFinalExistRow != null) ? jointCourseFinalExistRow.id : Guid.NewGuid().ToString();
  496. await client.GetContainer(Constant.TEAMModelOS, container).UpsertItemAsync(jointCourseCreateRow);
  497. result.Add(jointCourseCreateRow);
  498. }
  499. }
  500. return result;
  501. }
  502. //判斷某課程名單是否已完成評量
  503. //回傳值: 班級ID 或 課程名單ID 列表
  504. private static async Task<JointEventGroupCourseGroup> IfExamComplete(CosmosClient client, string examId, string scope, string creatorId, string school, string classId, string groupId)
  505. {
  506. JointEventGroupCourseGroup result = null;
  507. try
  508. {
  509. if (string.IsNullOrWhiteSpace(classId) && string.IsNullOrWhiteSpace(groupId)) return result;
  510. if ((scope.Equals("private") && string.IsNullOrWhiteSpace(creatorId)) || (scope.Equals("school") && string.IsNullOrWhiteSpace(school))) return result;
  511. string examClassResultCode = (scope.Equals("school") && !string.IsNullOrWhiteSpace(school)) ? $"ExamClassResult-{school}" : $"ExamClassResult-{creatorId}";
  512. StringBuilder stringBuilder = new($"SELECT c.info.id AS infoId, c.info.name AS infoName, c.studentIds, c.studentAnswers FROM c WHERE c.examId = '{examId}' ");
  513. if (!string.IsNullOrWhiteSpace(classId))
  514. {
  515. stringBuilder.Append($" AND c.info.id = '{classId}' ");
  516. }
  517. else
  518. {
  519. stringBuilder.Append($" AND c.info.id = '{groupId}' ");
  520. }
  521. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Common).GetItemQueryStreamIteratorSql(queryText: stringBuilder.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{examClassResultCode}") }))
  522. {
  523. using var json = await JsonDocument.ParseAsync(item.Content);
  524. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  525. {
  526. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  527. {
  528. string infoId = obj.GetProperty("infoId").GetString();
  529. string infoName = obj.GetProperty("infoName").GetString();
  530. List<string> studentIds = obj.GetProperty("studentIds").ToObject<List<string>>();
  531. List<List<string>> studentAnswers = obj.GetProperty("studentAnswers").ToObject<List<List<string>>>();
  532. bool hasAnswer = false;
  533. foreach (List<string> studentAnswer in studentAnswers)
  534. {
  535. if (studentAnswer.Count > 0)
  536. {
  537. hasAnswer = true;
  538. break;
  539. }
  540. }
  541. if (hasAnswer)
  542. {
  543. result = new JointEventGroupBase.JointEventGroupCourseGroup() { id = infoId, name = infoName };
  544. }
  545. }
  546. }
  547. }
  548. return result;
  549. }
  550. catch (Exception e)
  551. {
  552. return result;
  553. }
  554. }
  555. /// <summary>
  556. /// 計算決賽通過的老師課程名單用中間model
  557. /// </summary>
  558. public class JointEventGroupPassDto
  559. {
  560. public string creatorId { get; set; }
  561. public string courseId { get; set; }
  562. public string groupId { get; set; }
  563. public bool pass { get; set; }
  564. public List<string> jointExamId { get; set; } = new(); //已完成的活動評量ID
  565. }
  566. }
  567. }