JointService.cs 35 KB

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