JointService.cs 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  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. ///cloudas ※只有決賽有cloudas
  121. actExamInfo.cloudas = (jointExam.examType.Equals("custom")) ? true : false;
  122. examList.Add(actExamInfo);
  123. }
  124. }
  125. //[待做] 學校班級
  126. }
  127. //生成評量
  128. if (examList.Count > 0)
  129. {
  130. foreach (ExamInfo exam in examList)
  131. {
  132. await GenerateExam(client, _azureStorage, _serviceBus, _coreAPIHttpService, _azureRedis, _configuration, _dingDing, jointExam, exam);
  133. }
  134. }
  135. }
  136. catch (Exception)
  137. {
  138. }
  139. }
  140. //生成評量(單)
  141. private static async Task<string> GenerateExam(CosmosClient client, AzureStorageFactory _azureStorage, AzureServiceBusFactory _serviceBus, CoreAPIHttpService _coreAPIHttpService, AzureRedisFactory _azureRedis, IConfiguration _configuration, DingDing _dingDing, JointExam jointExam, ExamInfo exam)
  142. {
  143. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  144. string Result = string.Empty;
  145. exam.createTime = now;
  146. if (exam.startTime <= 0) exam.startTime = now;
  147. List<(string pId, List<string> gid)> ps = new();
  148. var group = exam.groupLists;
  149. if (group.Count > 0)
  150. {
  151. foreach (var keys in group)
  152. {
  153. foreach (KeyValuePair<string, List<string>> pp in keys)
  154. {
  155. ps.Add((pp.Key, pp.Value));
  156. }
  157. }
  158. }
  159. List<string> classes = ExamService.getClasses(exam.classes, exam.stuLists);
  160. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, classes, exam.school, ps);
  161. exam.stuCount = tchList.Count;
  162. string mode = string.Empty;
  163. ResponseMessage response = null;
  164. if (string.IsNullOrEmpty(exam.id))
  165. {
  166. mode = "add";
  167. }
  168. else
  169. {
  170. response = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(exam.id, new PartitionKey($"{exam.code}"));
  171. if (response.StatusCode == System.Net.HttpStatusCode.OK) mode = "upd";
  172. else mode = "add";
  173. }
  174. //DB操作
  175. if (mode.Equals("add")) //新建
  176. {
  177. if (string.IsNullOrWhiteSpace(exam.id)) exam.id = Guid.NewGuid().ToString();
  178. exam.progress = (exam.startTime > now) ? "pending" : "going";
  179. var messageBlob = new ServiceBusMessage();
  180. if (exam.scope.Equals("school") && !string.IsNullOrWhiteSpace(exam.school))
  181. {
  182. exam.size = await _azureStorage.GetBlobContainerClient(exam.school).GetBlobsSize($"exam/{exam.id}");
  183. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = exam.school }, _serviceBus, _configuration, _azureRedis);
  184. }
  185. else
  186. {
  187. exam.size = await _azureStorage.GetBlobContainerClient(exam.creatorId).GetBlobsSize($"exam/{exam.id}");
  188. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = exam.creatorId }, _serviceBus, _configuration, _azureRedis);
  189. }
  190. int n = 0;
  191. List<string> sheetIds = new List<string>();
  192. foreach (PaperSimple simple in exam.papers)
  193. {
  194. simple.blob = $"/exam/{exam.id}/paper/{exam.subjects[n].id}";
  195. n++;
  196. simple.sheet = null;
  197. }
  198. exam = await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(exam, new PartitionKey($"{exam.code}"));
  199. await BIStats.SetTypeAddStats(client, _dingDing, exam.school, "Exam", 1);//BI统计增/减量
  200. }
  201. else if (response != null) //更新
  202. {
  203. using var json = await JsonDocument.ParseAsync(response.Content);
  204. ExamInfo info = json.ToObject<ExamInfo>();
  205. if (info.progress.Equals("going"))
  206. {
  207. Result = "活动正在进行中,无法修改";
  208. }
  209. var messageBlob = new ServiceBusMessage();
  210. if (exam.scope.Equals("school") && !string.IsNullOrWhiteSpace(exam.school))
  211. {
  212. exam.size = await _azureStorage.GetBlobContainerClient(exam.school).GetBlobsSize($"exam/{exam.id}");
  213. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = $"exam", name = exam.school }, _serviceBus, _configuration, _azureRedis);
  214. }
  215. else
  216. {
  217. exam.size = await _azureStorage.GetBlobContainerClient(exam.creatorId).GetBlobsSize($"exam/{exam.id}");
  218. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = $"exam", name = exam.creatorId }, _serviceBus, _configuration, _azureRedis);
  219. }
  220. exam.progress = info.progress;
  221. int n = 0;
  222. List<string> sheetIds = new List<string>();
  223. foreach (PaperSimple simple in exam.papers)
  224. {
  225. if (!string.IsNullOrEmpty(simple.subjectId))
  226. {
  227. simple.blob = $"/exam/{exam.id}/paper/{simple.subjectId}/{simple.id}";
  228. }
  229. else
  230. {
  231. simple.blob = $"/exam/{exam.id}/paper/{exam.subjects[n].id}";
  232. n++;
  233. }
  234. simple.sheet = null;
  235. }
  236. exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
  237. }
  238. //Blob操作 ※取得試卷源(blob)、複製到評測紀錄下
  239. ///試卷源字典
  240. List<Dictionary<string, string>> sourcePaperInfo = new List<Dictionary<string, string>>();
  241. foreach (PaperSimple paperInfo in jointExam.papers)
  242. {
  243. string paperBlobPath = (!paperInfo.blob.EndsWith("/")) ? paperInfo.blob + "/" : paperInfo.blob;
  244. paperBlobPath = (paperInfo.blob.StartsWith("/")) ? paperBlobPath.Remove(0, 1) : paperBlobPath;
  245. sourcePaperInfo.Add(new Dictionary<string, string>() { { "id", paperInfo.id }, { "blob", paperBlobPath }, { "itemcount", paperInfo.point.Count.ToString() } });
  246. }
  247. bool paperDataCopyErrFlg = false; //試卷資料拷貝錯誤Flag true:拷貝錯誤
  248. //Blob拷貝程序
  249. int paperIndex = 0;
  250. foreach (Dictionary<string, string> sourcePaperInfoDic in sourcePaperInfo)
  251. {
  252. //拷貝源:Container => jointExam.creatorId Path:papers.blob
  253. //拷貝對象:Container => exam.creatorId, Path:exam/{exam.id}/paper/{exam.subjects[paperIndex].id}/
  254. string targetScope = exam.scope; //評測對象 school:校本班級 private:私人課程
  255. var sourceBlobContainer = _azureStorage.GetBlobContainerClient(jointExam.creatorId); //統測活動來源一定是個人
  256. var blobPrivateContainer = (targetScope.Equals("school")) ? _azureStorage.GetBlobContainerClient(exam.school) : _azureStorage.GetBlobContainerClient(exam.creatorId);
  257. string sourceBlobPath = sourcePaperInfoDic["blob"];
  258. string subjectId = exam.subjects[paperIndex].id;
  259. string destBlobPath = $"exam/{exam.id}/paper/{subjectId}/"; //拷貝對象路徑 path:exam/{評測ID}/paper/{subjectID}/
  260. Pageable<BlobItem> sourceBlobs = sourceBlobContainer.GetBlobs(prefix: sourceBlobPath);
  261. if (sourceBlobs.Count() > 0)
  262. {
  263. foreach (var blob in sourceBlobs)
  264. {
  265. var sourceFileBlob = sourceBlobContainer.GetBlobClient(blob.Name);
  266. if (sourceFileBlob.Exists())
  267. {
  268. var sourceFileUri = sourceBlobContainer.GetBlobClient(blob.Name).Uri;
  269. string fileName = blob.Name.Replace(sourceBlobPath, "");
  270. string destBlobFilePath = $"{destBlobPath}{fileName}";
  271. await blobPrivateContainer.GetBlobClient(destBlobFilePath).StartCopyFromUriAsync(sourceFileUri);
  272. }
  273. else
  274. {
  275. paperDataCopyErrFlg = true;
  276. }
  277. }
  278. }
  279. paperIndex++;
  280. }
  281. return Result;
  282. }
  283. //以JointSchedule為單位,判斷班級/課程名單是否完成並生成決賽名單
  284. /// <param name="mode">updDb true:更新DB false:不更新DB</param>
  285. /// <param name="classCnt"> 班級流水號 (此次活動參加的班級數)
  286. public static async Task<object> CreatePassJointCourseBySchedule(CosmosClient client, string jointEventId, string jointGroupId, string jointScheduleId, string scope, bool updDb, int classCnt)
  287. {
  288. List<JointEventGroupDb> result = new List<JointEventGroupDb>();
  289. //0. 取得jointEvent、JointEventSchedule
  290. JointEvent jointEvent = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<JointEvent>(jointEventId, new PartitionKey("JointEvent"));
  291. if (jointEvent == null)
  292. {
  293. return result;
  294. }
  295. JointEventSchedule jointEventSchedule = jointEvent.schedule.Where(s => s.id.Equals(jointScheduleId)).FirstOrDefault();
  296. if (jointEventSchedule == null)
  297. {
  298. return result;
  299. }
  300. //1. 用jointEventId、jointGroupId 取得所有老師報名的 班級/課程名單
  301. List<JointEventGroupDb> jointEventCourse = new List<JointEventGroupDb>();
  302. 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)) ");
  303. string container = (scope.Equals("school")) ? Constant.School : Constant.Teacher;
  304. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, container).GetItemQueryStreamIteratorSql(queryText: stringBuilderJointCourse.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("JointCourse") }))
  305. {
  306. using var json = await JsonDocument.ParseAsync(item.Content);
  307. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  308. {
  309. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  310. {
  311. jointEventCourse.Add(obj.ToObject<JointEventGroupDb>());
  312. }
  313. }
  314. }
  315. //2. 取得本Schedule的所有JointExam
  316. List<string> jointExamIdList = new List<string>();
  317. List<JointExam> jointEventExam = new List<JointExam>();
  318. StringBuilder stringBuilderJointExam = new($"SELECT * FROM c WHERE c.jointEventId = '{jointEventId}' AND c.jointGroupId = '{jointGroupId}' AND c.jointScheduleId = '{jointScheduleId}' ");
  319. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Common).GetItemQueryStreamIteratorSql(queryText: stringBuilderJointExam.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("JointExam") }))
  320. {
  321. using var json = await JsonDocument.ParseAsync(item.Content);
  322. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  323. {
  324. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  325. {
  326. JointExam jointExamRow = obj.ToObject<JointExam>();
  327. jointEventExam.Add(jointExamRow);
  328. if (!jointExamIdList.Contains(jointExamRow.id))
  329. {
  330. jointExamIdList.Add(jointExamRow.id);
  331. }
  332. }
  333. }
  334. }
  335. //3. 取得所有JointExam關聯的Exam
  336. List<ExamInfo> exam = new List<ExamInfo>();
  337. StringBuilder stringBuilderExam = new($"SELECT * FROM c WHERE c.pk = 'Exam' AND ARRAY_CONTAINS({JsonSerializer.Serialize(jointExamIdList)}, c.jointExamId) ");
  338. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Common).GetItemQueryStreamIteratorSql(queryText: stringBuilderExam.ToString(), requestOptions: null))
  339. {
  340. using var json = await JsonDocument.ParseAsync(item.Content);
  341. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  342. {
  343. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  344. {
  345. exam.Add(obj.ToObject<ExamInfo>());
  346. }
  347. }
  348. }
  349. //4. 用 IfJointExamComplete 列出完成評量的 班級/課程名單
  350. List<JointEventGroupPassDto> passGroupsBindJointexam = new List<JointEventGroupPassDto>(); //已完成的課程名單和已完成的JointExam對照表
  351. JointEventSchedule finalSchedule = jointEvent.schedule.Where(s => s.type.Equals("exam") && s.examType.Equals("custom")).FirstOrDefault(); //取schedule中的決賽為jointScheduleId ※應該只會有一個決賽
  352. if (finalSchedule != null) //可取得挑戰賽才繼續
  353. {
  354. foreach (JointExam jointExamRow in jointEventExam)
  355. {
  356. ///第1層 JointExam
  357. List<ExamInfo> examsNow = exam.Where(e => e.jointExamId.Equals(jointExamRow.id)).ToList();
  358. foreach (JointEventGroupDb jointEventCourseRow in jointEventCourse)
  359. {
  360. ///第2層 jointEventCourse
  361. string creatorIdRow = jointEventCourseRow.creatorId;
  362. foreach (JointEventGroupBase.JointEventGroupCourse jointCourseIn in jointEventCourseRow.courseLists)
  363. {
  364. ///第3層 老師報名的course
  365. string courseId = jointCourseIn.courseId;
  366. string courseName = jointCourseIn.courseName;
  367. List<string> groupIds = jointCourseIn.groupLists.Select(c => c.id).ToList();
  368. ExamInfo examNow = examsNow.Where(e => e.creatorId.Equals(creatorIdRow) && e.subjects[0].id.Equals(courseId)).FirstOrDefault();
  369. if (examNow != null)
  370. {
  371. string examId = examNow.id;
  372. string schoolId = string.Empty;
  373. string classId = string.Empty;
  374. foreach (string groupId in groupIds)
  375. {
  376. JointEventGroupBase.JointEventGroupCourseGroup passGroupInfo = await IfExamComplete(client, examId, scope, creatorIdRow, schoolId, classId, groupId);
  377. if (passGroupInfo != null)
  378. {
  379. //生成決賽通過的老師課程名單用中間model
  380. JointEventGroupPassDto passGroupRow = passGroupsBindJointexam.Where(p => p.creatorId.Equals(jointEventCourseRow.creatorId) && p.courseId.Equals(courseId) && p.groupId.Equals(groupId)).FirstOrDefault();
  381. if (passGroupRow == null)
  382. {
  383. passGroupsBindJointexam.Add(new JointEventGroupPassDto()
  384. {
  385. creatorId = jointEventCourseRow.creatorId,
  386. courseId = courseId,
  387. groupId = groupId
  388. });
  389. passGroupRow = passGroupsBindJointexam.Where(p => p.creatorId.Equals(jointEventCourseRow.creatorId) && p.courseId.Equals(courseId) && p.groupId.Equals(groupId)).FirstOrDefault();
  390. }
  391. if (!passGroupRow.jointExamId.Contains(jointExamRow.id))
  392. {
  393. passGroupRow.jointExamId.Add(jointExamRow.id);
  394. }
  395. //根據評量連動類型計算是否生成決賽評量
  396. switch (jointEvent.examLinkType)
  397. {
  398. case "one": //有任一評量完成 => pass
  399. if (passGroupRow.jointExamId.Count > 0)
  400. {
  401. passGroupRow.pass = true;
  402. }
  403. break;
  404. case "all": //所有評量都完成 => pass
  405. if (passGroupRow.jointExamId.Count.Equals(jointExamIdList.Count))
  406. {
  407. passGroupRow.pass = true;
  408. }
  409. break;
  410. default:
  411. passGroupRow.pass = true;
  412. break;
  413. }
  414. }
  415. }
  416. }
  417. }
  418. }
  419. }
  420. }
  421. //5. 決賽課程生成
  422. ///生成資料製作
  423. List<JointEventGroupDb> jointCourseCreates = new List<JointEventGroupDb>(); //要生成的老師課程名單
  424. foreach (JointEventGroupDb jointEventCourseRow in jointEventCourse)
  425. {
  426. foreach (JointEventGroupBase.JointEventGroupCourse course in jointEventCourseRow.courseLists)
  427. {
  428. foreach (JointEventGroupBase.JointEventGroupCourseGroup group in course.groupLists)
  429. {
  430. 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();
  431. if (passGroupRow != null)
  432. {
  433. string courseId = course.courseId;
  434. string courseName = course.courseName;
  435. JointEventGroupDb jointCourseCreateRow = jointCourseCreates.Where(c => c.jointEventId.Equals(jointEventCourseRow.jointEventId) && c.jointGroupId.Equals(jointEventCourseRow.jointGroupId) && c.creatorId.Equals(jointEventCourseRow.creatorId)).FirstOrDefault();
  436. if (jointCourseCreateRow == null)
  437. {
  438. ///DB 老師決賽document
  439. JointEventGroupDb finalEventCourse = new JointEventGroupDb();
  440. finalEventCourse.jointEventId = jointEventCourseRow.jointEventId;
  441. finalEventCourse.jointGroupId = jointEventCourseRow.jointGroupId;
  442. finalEventCourse.code = jointEventCourseRow.code;
  443. finalEventCourse.pk = jointEventCourseRow.pk;
  444. finalEventCourse.scope = jointEventCourseRow.scope;
  445. finalEventCourse.type = "custom"; //決賽
  446. finalEventCourse.creatorId = jointEventCourseRow.creatorId;
  447. finalEventCourse.creatorName = jointEventCourseRow.creatorName;
  448. finalEventCourse.creatorEmail = jointEventCourseRow.creatorEmail;
  449. finalEventCourse.schoolId = jointEventCourseRow.schoolId;
  450. finalEventCourse.schoolName = jointEventCourseRow.schoolName;
  451. finalEventCourse.countryId = jointEventCourseRow.countryId;
  452. finalEventCourse.countryName = jointEventCourseRow.countryName;
  453. finalEventCourse.provinceId = jointEventCourseRow.provinceId;
  454. finalEventCourse.provinceName = jointEventCourseRow.provinceName;
  455. finalEventCourse.cityId = jointEventCourseRow.cityId;
  456. finalEventCourse.cityName = jointEventCourseRow.cityName;
  457. finalEventCourse.jointScheduleId = finalSchedule.id;
  458. classCnt++;
  459. finalEventCourse.courseLists.Add(new JointEventGroupBase.JointEventGroupCourse()
  460. {
  461. courseId = courseId,
  462. courseName = courseName,
  463. groupLists = new List<JointEventGroupBase.JointEventGroupCourseGroup>() {
  464. new() { id = group.id, name = group.name, no = classCnt.ToString() }
  465. }
  466. });
  467. finalEventCourse.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  468. jointCourseCreates.Add(finalEventCourse);
  469. }
  470. else
  471. {
  472. JointEventGroupBase.JointEventGroupCourse courseRowNow = jointCourseCreateRow.courseLists.Where(c => c.courseId.Equals(courseId)).FirstOrDefault();
  473. if (courseRowNow == null)
  474. {
  475. ///DB 老師決賽課程資料
  476. classCnt++;
  477. jointCourseCreateRow.courseLists.Add(
  478. new JointEventGroupBase.JointEventGroupCourse
  479. {
  480. courseId = courseId,
  481. courseName = courseName,
  482. groupLists = new List<JointEventGroupBase.JointEventGroupCourseGroup>() {
  483. new() { id = group.id, name = group.name, no = classCnt.ToString() }
  484. }
  485. }
  486. );
  487. }
  488. else
  489. {
  490. JointEventGroupBase.JointEventGroupCourseGroup groupRowNow = courseRowNow.groupLists.Where(g => g.id.Equals(group.id)).FirstOrDefault();
  491. if (groupRowNow == null)
  492. {
  493. ///DB 老師決賽班級資料
  494. classCnt++;
  495. courseRowNow.groupLists.Add(
  496. new() { id = group.id, name = group.name, no = classCnt.ToString() }
  497. );
  498. }
  499. }
  500. }
  501. }
  502. }
  503. }
  504. }
  505. ///DB
  506. if (jointCourseCreates.Count > 0)
  507. {
  508. //取得所有已存在的決賽課程名單
  509. List<JointEventGroupDb> jointCourseFinalExist = new List<JointEventGroupDb>();
  510. 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}' ");
  511. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, container).GetItemQueryStreamIteratorSql(queryText: stringBuilderJointCourseCreates.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("JointCourse") }))
  512. {
  513. using var json = await JsonDocument.ParseAsync(item.Content);
  514. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  515. {
  516. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  517. {
  518. jointCourseFinalExist.Add(obj.ToObject<JointEventGroupDb>());
  519. }
  520. }
  521. }
  522. //生成決賽課程名單
  523. foreach (JointEventGroupDb jointCourseCreateRow in jointCourseCreates)
  524. {
  525. JointEventGroupDb jointCourseFinalExistRow = jointCourseFinalExist.Where(j => j.creatorId.Equals(jointCourseCreateRow.creatorId)).FirstOrDefault();
  526. jointCourseCreateRow.id = (jointCourseFinalExistRow != null) ? jointCourseFinalExistRow.id : Guid.NewGuid().ToString();
  527. if(updDb)
  528. {
  529. await client.GetContainer(Constant.TEAMModelOS, container).UpsertItemAsync(jointCourseCreateRow);
  530. }
  531. result.Add(jointCourseCreateRow);
  532. }
  533. }
  534. return new { result = result, classCnt = classCnt };
  535. }
  536. //判斷某課程名單是否已完成評量
  537. //回傳值: 班級ID 或 課程名單ID 列表
  538. private static async Task<JointEventGroupCourseGroup> IfExamComplete(CosmosClient client, string examId, string scope, string creatorId, string school, string classId, string groupId)
  539. {
  540. JointEventGroupCourseGroup result = null;
  541. try
  542. {
  543. if (string.IsNullOrWhiteSpace(classId) && string.IsNullOrWhiteSpace(groupId)) return result;
  544. if ((scope.Equals("private") && string.IsNullOrWhiteSpace(creatorId)) || (scope.Equals("school") && string.IsNullOrWhiteSpace(school))) return result;
  545. string examClassResultCode = (scope.Equals("school") && !string.IsNullOrWhiteSpace(school)) ? $"ExamClassResult-{school}" : $"ExamClassResult-{creatorId}";
  546. StringBuilder stringBuilder = new($"SELECT c.info.id AS infoId, c.info.name AS infoName, c.studentIds, c.studentAnswers FROM c WHERE c.examId = '{examId}' ");
  547. if (!string.IsNullOrWhiteSpace(classId))
  548. {
  549. stringBuilder.Append($" AND c.info.id = '{classId}' ");
  550. }
  551. else
  552. {
  553. stringBuilder.Append($" AND c.info.id = '{groupId}' ");
  554. }
  555. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Common).GetItemQueryStreamIteratorSql(queryText: stringBuilder.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{examClassResultCode}") }))
  556. {
  557. using var json = await JsonDocument.ParseAsync(item.Content);
  558. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  559. {
  560. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  561. {
  562. string infoId = obj.GetProperty("infoId").GetString();
  563. string infoName = obj.GetProperty("infoName").GetString();
  564. List<string> studentIds = obj.GetProperty("studentIds").ToObject<List<string>>();
  565. List<List<string>> studentAnswers = obj.GetProperty("studentAnswers").ToObject<List<List<string>>>();
  566. bool hasAnswer = false;
  567. foreach (List<string> studentAnswer in studentAnswers)
  568. {
  569. if (studentAnswer.Count > 0)
  570. {
  571. hasAnswer = true;
  572. break;
  573. }
  574. }
  575. if (hasAnswer)
  576. {
  577. result = new JointEventGroupBase.JointEventGroupCourseGroup() { id = infoId, name = infoName };
  578. }
  579. }
  580. }
  581. }
  582. return result;
  583. }
  584. catch (Exception e)
  585. {
  586. return result;
  587. }
  588. }
  589. /// <summary>
  590. /// 計算統測活動各報名班級的各活動階段進行狀況
  591. /// </summary>
  592. /// <param name="jointEventId"></param>
  593. /// <param name="jointGroupId"></param>
  594. /// <param name="creatorId"></param>
  595. /// <param name="jointEventGroupDb">要取得的報名課程,若給null則會從DB取</param>
  596. /// <param name="schedule">若給null則所有schedule的status(報名、熱身賽、決賽)都計算</param>
  597. /// <param name="update">是否更新DB true:更新 false:不更新</param>
  598. public static async Task<JointEventGroupDb> CalJointCourseGroupScheduleStatusAsync(CosmosClient client, string jointEventId, string jointGroupId, string creatorId, JointEventGroupDb jointCourse = null, JointEventSchedule schedule = null)
  599. {
  600. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  601. string scope = "private"; //先只指定個人
  602. string container = (scope.Equals("school")) ? Constant.School : Constant.Teacher;
  603. //取得統測活動
  604. JointEvent jointEvent = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<JointEvent>(jointEventId, new PartitionKey("JointEvent"));
  605. if (jointEvent == null)
  606. {
  607. return null;
  608. }
  609. //取得報名名單
  610. if (jointCourse == null)
  611. {
  612. StringBuilder stringBuilder = new($"SELECT * FROM c WHERE c.jointEventId = '{jointEventId}' AND c.jointGroupId = '{jointGroupId}' AND c.creatorId = '{creatorId}' AND c.type = 'regular' ");
  613. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, container).GetItemQueryStreamIteratorSql(queryText: stringBuilder.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("JointCourse") }))
  614. {
  615. using var json = await JsonDocument.ParseAsync(item.Content);
  616. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  617. {
  618. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  619. {
  620. jointCourse = obj.ToObject<JointEventGroupDb>();
  621. }
  622. }
  623. }
  624. }
  625. if (jointCourse == null)
  626. {
  627. return null;
  628. }
  629. //計算各階段Status
  630. List<JointEventSchedule> jointScheduleList = new List<JointEventSchedule>(); //要計算的活動階段
  631. if (schedule != null) jointScheduleList.Add(schedule);
  632. else jointScheduleList = jointEvent.schedule;
  633. ///計算邏輯
  634. foreach (JointEventGroupBase.JointEventGroupCourse courseRow in jointCourse.courseLists) //各報名課程
  635. {
  636. string courseId = courseRow.courseId;
  637. foreach (JointEventGroupBase.JointEventGroupCourseGroup courseGroup in courseRow.groupLists) //各報名課程名單(各班)
  638. {
  639. string groupId = courseGroup.id;
  640. foreach (JointEventSchedule eventSchedule in jointScheduleList) //各活動階段
  641. {
  642. //活動階段篩選:報名、熱身賽、決賽 才記入
  643. if(eventSchedule.type.Equals("join") || eventSchedule.type.Equals("exam"))
  644. {
  645. JointEventGroupBase.JointEventGroupCourseGroup.JointEventGroupCourseGroupSchedule courseGroupSchedule = courseGroup.schedule.FirstOrDefault(s => s.id.Equals(eventSchedule.id));
  646. if (courseGroupSchedule == null) //不存在 > 新建
  647. {
  648. courseGroupSchedule = new JointEventGroupBase.JointEventGroupCourseGroup.JointEventGroupCourseGroupSchedule()
  649. {
  650. id = eventSchedule.id,
  651. status = "undo"
  652. };
  653. courseGroup.schedule.Add(courseGroupSchedule);
  654. courseGroupSchedule = courseGroup.schedule.FirstOrDefault(s => s.id.Equals(eventSchedule.id));
  655. }
  656. courseGroupSchedule.status = await GetGroupJointScheduleStatus(client, jointEventId, jointGroupId, groupId, eventSchedule, jointCourse, creatorId);
  657. }
  658. }
  659. }
  660. }
  661. return jointCourse;
  662. }
  663. //判斷某groupId在某JointSchedule是否完成
  664. /// <summary>
  665. /// 判斷某groupId在某JointSchedule是否完成
  666. /// </summary>
  667. /// <param name="jointEventId"></param>
  668. /// <param name="jointGroupId"></param>
  669. /// <param name="groupId"></param>
  670. /// <param name="schedule"></param>
  671. /// <param name="jointCourse">統測報名班級DB document 若為null則由DB取</param>
  672. /// <param name="creatorId"></param>
  673. /// <returns></returns>
  674. private static async Task<string> GetGroupJointScheduleStatus(CosmosClient client, string jointEventId, string jointGroupId, string groupId, JointEventSchedule schedule, JointEventGroupDb jointCourse, string creatorId)
  675. {
  676. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  677. string result = "undo"; //活動階段開始前一律為 undo
  678. string scope = "private"; //先只指定個人
  679. string container = (scope.Equals("school")) ? Constant.School : Constant.Teacher;
  680. switch (schedule.type)
  681. {
  682. //報名
  683. ///算出邏輯:(1)可取得該報名課程名單 -> complete (2)無法取得 -> undo
  684. case "join":
  685. if (schedule.startTime <= now) //報名期間開始後
  686. {
  687. if (jointCourse == null)
  688. {
  689. StringBuilder stringBuilderJointCourse = new($"SELECT * FROM c WHERE c.jointEventId = '{jointEventId}' AND c.jointGroupId = '{jointGroupId}' AND c.creatorId = '{creatorId}' AND c.type = 'regular' ");
  690. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, container).GetItemQueryStreamIteratorSql(queryText: stringBuilderJointCourse.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("JointCourse") }))
  691. {
  692. using var json = await JsonDocument.ParseAsync(item.Content);
  693. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  694. {
  695. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  696. {
  697. jointCourse = obj.ToObject<JointEventGroupDb>();
  698. }
  699. }
  700. }
  701. }
  702. if (jointCourse != null)
  703. {
  704. foreach (JointEventGroupBase.JointEventGroupCourse courseInfo in jointCourse.courseLists)
  705. {
  706. JointEventGroupBase.JointEventGroupCourseGroup groupExist = courseInfo.groupLists.FirstOrDefault(g => g.id.Equals(groupId));
  707. if (groupExist != null)
  708. {
  709. result = "complete";
  710. }
  711. }
  712. }
  713. }
  714. break;
  715. //競賽
  716. ///算出邏輯: (1)無法取得報名班級(決賽班級) -> 資格不符(disqualify)
  717. /// (2)統測評量數 > 0 && 個人評量完成數(學生有一人有作答則是為完成) == 統測評量數 -> 完成(complete)
  718. /// (3)統測評量數 > 0 && 個人評量完成數 > 0 && 統測評量數 > 個人評量完成數 -> 進行中(doing)
  719. /// (4)default -> undo
  720. case "exam":
  721. if (schedule.startTime <= now) //活動期間開始後
  722. {
  723. //取得老師報名課程或決賽老師課程
  724. List<JointEventGroupDb> jointEventGroup = new List<JointEventGroupDb>(); //個人課程
  725. StringBuilder stringBuilderEventGroup = new($"SELECT * FROM c WHERE c.jointEventId = '{jointEventId}' AND c.jointGroupId = '{jointGroupId}' ");
  726. if (schedule.examType.Equals("regular")) //熱身賽
  727. {
  728. stringBuilderEventGroup.Append($" AND (c.type = 'regular' OR NOT IS_DEFINED(c.type) OR IS_NULL(c.type)) ");
  729. }
  730. else if (schedule.examType.Equals("custom")) //決賽
  731. {
  732. stringBuilderEventGroup.Append($" AND c.type = 'custom' AND c.jointScheduleId = '{schedule.id}' ");
  733. }
  734. if (!string.IsNullOrWhiteSpace(creatorId))
  735. {
  736. stringBuilderEventGroup.Append($" AND c.creatorId = '{creatorId}' ");
  737. }
  738. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryStreamIteratorSql(queryText: stringBuilderEventGroup.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("JointCourse") }))
  739. {
  740. using var json = await JsonDocument.ParseAsync(item.Content);
  741. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  742. {
  743. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  744. {
  745. jointEventGroup.Add(obj.ToObject<JointEventGroupDb>());
  746. }
  747. }
  748. }
  749. //取得本Schedule的所有JointExam
  750. List<string> jointExamIdList = new List<string>();
  751. StringBuilder stringBuilderJointExam = new($"SELECT DISTINCT VALUE c.id FROM c WHERE c.jointEventId = '{jointEventId}' AND c.jointGroupId = '{jointGroupId}' AND c.jointScheduleId = '{schedule.id}' ");
  752. var resultJointExam = await client.GetContainer(Constant.TEAMModelOS, Constant.Common).GetList<string>(stringBuilderJointExam.ToString(), $"JointExam");
  753. if (resultJointExam.list.IsNotEmpty())
  754. {
  755. jointExamIdList = new List<string>(resultJointExam.list);
  756. }
  757. //取得所有個人評量
  758. List<string> examIdList = new List<string>();
  759. string sqlExam = $"SELECT DISTINCT VALUE c.id FROM c WHERE ARRAY_CONTAINS({JsonSerializer.Serialize(jointExamIdList)}, c.jointExamId) AND ARRAY_CONTAINS(c.stuLists, '{groupId}') AND CONTAINS(c.code, 'Exam-')";
  760. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Common).GetItemQueryIteratorSql<string>(queryText: sqlExam, requestOptions: new QueryRequestOptions { }))
  761. {
  762. examIdList.Add(item);
  763. }
  764. //取得所有考試的作答結果
  765. List<string> finishExamIdList = new List<string>();
  766. string sqlExamClassResult = $"SELECT c.examId, c.info.id as classId, c.studentAnswers FROM c WHERE ARRAY_CONTAINS({JsonSerializer.Serialize(examIdList)}, c.examId) AND c.info.id = '{groupId}' AND c.progress=true AND CONTAINS(c.code, 'ExamClassResult')";
  767. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Common).GetItemQueryStreamIteratorSql(queryText: sqlExamClassResult, requestOptions: new QueryRequestOptions() { }))
  768. {
  769. using var json = await JsonDocument.ParseAsync(item.Content);
  770. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  771. {
  772. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  773. {
  774. string examId = obj.GetProperty("examId").ToString();
  775. string classId = obj.GetProperty("classId").ToString();
  776. List<List<string>> studentAnswers = obj.GetProperty("studentAnswers").ToObject<List<List<string>>>();
  777. bool isFinish = false; //評量是否已完成 ※有任一學生有作答則視為已完成
  778. foreach (List<string> studentAnswer in studentAnswers)
  779. {
  780. if (studentAnswer.Count > 0) { isFinish = true; break; }
  781. }
  782. if (isFinish)
  783. {
  784. finishExamIdList.Add(examId);
  785. }
  786. }
  787. }
  788. }
  789. //結果判斷
  790. JointEventGroupBase.JointEventGroupCourseGroup classInGroup = new JointEventGroupBase.JointEventGroupCourseGroup(); //取得該班級的報名/決賽資訊
  791. foreach (JointEventGroupDb eventGroup in jointEventGroup)
  792. {
  793. foreach (JointEventGroupBase.JointEventGroupCourse eventCourse in eventGroup.courseLists)
  794. {
  795. foreach (JointEventGroupBase.JointEventGroupCourseGroup group in eventCourse.groupLists)
  796. {
  797. if (group.id.Equals(groupId))
  798. {
  799. classInGroup = group;
  800. }
  801. }
  802. }
  803. }
  804. if (jointEventGroup.Count.Equals(0) || string.IsNullOrWhiteSpace(classInGroup.id)) //資格不符
  805. {
  806. result = "disqualify";
  807. }
  808. else if (jointExamIdList.Count > 0 && jointExamIdList.Count.Equals(finishExamIdList.Count))
  809. {
  810. result = "complete";
  811. }
  812. else if (jointExamIdList.Count > 0 && finishExamIdList.Count > 0 && jointExamIdList.Count > finishExamIdList.Count)
  813. {
  814. result = "doing";
  815. }
  816. }
  817. break;
  818. }
  819. return result;
  820. }
  821. /// <summary>
  822. /// 將活動預報名轉為正式報名
  823. /// </summary>
  824. /// <param name="client"></param>
  825. /// <param name="jointEventId"></param>
  826. /// <param name="jointGroupId"></param>
  827. /// <param name="creatorId"></param>
  828. /// <returns></returns>
  829. public static async Task<List<JointEventGroupDb>> JointCoursePreToRegularAsync(CosmosClient client, string jointEventId, string jointGroupId, string creatorId)
  830. {
  831. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  832. List<JointEventGroupDb> result = new List<JointEventGroupDb>();
  833. //取得本活動所有預報名
  834. List<string> groupIds = new List<string>();
  835. List<JointEventGroupDb> jointCourseListPre = new List<JointEventGroupDb>();
  836. StringBuilder stringBuilder = new($"SELECT * FROM c WHERE c.jointEventId = '{jointEventId}' ");
  837. if (!string.IsNullOrWhiteSpace(jointGroupId))
  838. {
  839. stringBuilder.Append($" AND c.jointGroupId = '{jointGroupId}' ");
  840. }
  841. if (!string.IsNullOrWhiteSpace(creatorId))
  842. {
  843. stringBuilder.Append($" AND c.creatorId = '{creatorId}' ");
  844. }
  845. StringBuilder stringBuilderPre = new (stringBuilder.ToString());
  846. stringBuilderPre.Append($" AND c.type = 'pre' ");
  847. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIteratorSql(queryText: stringBuilderPre.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("JointCourse") }))
  848. {
  849. using var json = await JsonDocument.ParseAsync(item.Content);
  850. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  851. {
  852. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  853. {
  854. JointEventGroupDb jcourse = obj.ToObject<JointEventGroupDb>();
  855. jointCourseListPre.Add(jcourse);
  856. //取得groupList ID
  857. foreach (JointEventGroupCourse course in jcourse.courseLists)
  858. {
  859. foreach (JointEventGroupCourseGroup group in course.groupLists)
  860. {
  861. if(!groupIds.Contains(group.id))
  862. groupIds.Add(group.id);
  863. }
  864. }
  865. }
  866. }
  867. }
  868. //取得所有班級成員
  869. List<RGroupList> groupList = new List<RGroupList>();
  870. string gids = string.Join(",", groupIds.Select(x => $"'{x}'"));
  871. StringBuilder stringBuilderGrp = new($"SELECT * FROM c WHERE c.id IN ({gids}) ");
  872. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIteratorSql(queryText: stringBuilderGrp.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("GroupList") }))
  873. {
  874. using var json = await JsonDocument.ParseAsync(item.Content);
  875. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  876. {
  877. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  878. {
  879. RGroupList gp = obj.ToObject<RGroupList>();
  880. groupList.Add(gp);
  881. }
  882. }
  883. }
  884. //刪除本活動所有正式報名
  885. List<JointEventGroupDb> jointCourseListRegular = new List<JointEventGroupDb>();
  886. StringBuilder stringBuilderRegular = new StringBuilder(stringBuilder.ToString());
  887. stringBuilderRegular.Append($" AND c.type = 'regular' ");
  888. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIteratorSql(queryText: stringBuilderRegular.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("JointCourse") }))
  889. {
  890. using var json = await JsonDocument.ParseAsync(item.Content);
  891. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  892. {
  893. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  894. {
  895. JointEventGroupDb jcourse = obj.ToObject<JointEventGroupDb>();
  896. jointCourseListRegular.Add(jcourse);
  897. }
  898. }
  899. }
  900. if (jointCourseListRegular.Count > 0)
  901. {
  902. foreach (JointEventGroupDb jcRegular in jointCourseListRegular)
  903. {
  904. await client.GetContainer(Constant.TEAMModelOS, "Teacher").DeleteItemAsync<JointEventGroupDb>(jcRegular.id, new PartitionKey("JointCourse"));
  905. }
  906. }
  907. //生成本活動所有正式報名:有班級成員者才記入
  908. List<JointEventGroupDb> jointCourseListRegularCrt = new List<JointEventGroupDb>();
  909. foreach (JointEventGroupDb jcPre in jointCourseListPre)
  910. {
  911. foreach (JointEventGroupCourse jcPreCourse in jcPre.courseLists)
  912. {
  913. foreach (JointEventGroupCourseGroup jcPreGroup in jcPreCourse.groupLists)
  914. {
  915. string groupId = jcPreGroup.id;
  916. RGroupList groupInfo = groupList.FirstOrDefault(g => g.id.Equals(groupId));
  917. if (groupInfo != null && groupInfo.members.Count > 0)
  918. {
  919. ///正式報名 JointCourse本體生成
  920. JointEventGroupDb jcRegularNow = jointCourseListRegularCrt.FirstOrDefault(j => j.jointEventId.Equals(jcPre.jointEventId) && j.jointGroupId.Equals(jcPre.jointGroupId) && j.creatorId.Equals(jcPre.creatorId));
  921. if (jcRegularNow == null)
  922. {
  923. JointEventGroupDb jcRegularNew = new JointEventGroupDb();
  924. jcRegularNew.id = Guid.NewGuid().ToString();
  925. jcRegularNew.code = "JointCourse";
  926. jcRegularNew.pk = "JointCourse";
  927. jcRegularNew.jointEventId = jcPre.jointEventId;
  928. jcRegularNew.jointGroupId = jcPre.jointGroupId;
  929. jcRegularNew.createTime = now;
  930. jcRegularNew.scope = "private";
  931. jcRegularNew.type = "regular";
  932. jcRegularNew.creatorId = jcPre.creatorId;
  933. jcRegularNew.creatorName = jcPre.creatorName;
  934. jcRegularNew.creatorEmail = jcPre.creatorEmail;
  935. jcRegularNew.schoolId = jcPre.schoolId;
  936. jcRegularNew.schoolName = jcPre.schoolName;
  937. jointCourseListRegularCrt.Add(jcRegularNew);
  938. jcRegularNow = jointCourseListRegularCrt.FirstOrDefault(j => j.jointEventId.Equals(jcPre.jointEventId) && j.jointGroupId.Equals(jcPre.jointGroupId) && j.creatorId.Equals(jcPre.creatorId) && j.type.Equals("regular") && j.scope.Equals("private"));
  939. }
  940. ///courseLists.row 生成
  941. JointEventGroupCourse jcRegularCourseNow = jcRegularNow.courseLists.FirstOrDefault(c => c.courseId.Equals(jcPreCourse.courseId));
  942. if (jcRegularCourseNow == null)
  943. {
  944. JointEventGroupCourse jcRegularCourseNew = new JointEventGroupBase.JointEventGroupCourse();
  945. jcRegularCourseNew.courseId = jcPreCourse.courseId;
  946. jcRegularCourseNew.courseName = jcPreCourse.courseName;
  947. jcRegularNow.courseLists.Add(jcRegularCourseNew);
  948. jcRegularCourseNow = jcRegularNow.courseLists.FirstOrDefault(c => c.courseId.Equals(jcPreCourse.courseId));
  949. }
  950. ///groupLists.row 生成
  951. JointEventGroupCourseGroup jcRegularCourseGroupNow = jcRegularCourseNow.groupLists.FirstOrDefault(g => g.id.Equals(jcPreGroup.id));
  952. if (jcRegularCourseGroupNow == null)
  953. {
  954. JointEventGroupCourseGroup jcRegularCourseGroupNew = new JointEventGroupBase.JointEventGroupCourseGroup();
  955. jcRegularCourseGroupNew.id = groupInfo.id;
  956. jcRegularCourseGroupNew.name = groupInfo.name;
  957. jcRegularCourseNow.groupLists.Add(jcRegularCourseGroupNew);
  958. jcRegularCourseGroupNow = jcRegularCourseNow.groupLists.FirstOrDefault(g => g.id.Equals(jcPreGroup.id));
  959. }
  960. }
  961. }
  962. }
  963. }
  964. //計算各活動階段進行狀況
  965. foreach (JointEventGroupDb jointCourse in jointCourseListRegularCrt)
  966. {
  967. string creator = jointCourse.creatorId;
  968. JointEventGroupDb jointCourseCrt = await JointService.CalJointCourseGroupScheduleStatusAsync(client, jointEventId, jointGroupId, creator, jointCourse, null);
  969. await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).CreateItemAsync<JointEventGroupDb>(jointCourseCrt, new PartitionKey(jointCourseCrt.code));
  970. result.Add(jointCourseCrt);
  971. }
  972. return result;
  973. }
  974. /// <summary>
  975. /// 計算決賽通過的老師課程名單用中間model
  976. /// </summary>
  977. public class JointEventGroupPassDto
  978. {
  979. public string creatorId { get; set; }
  980. public string courseId { get; set; }
  981. public string groupId { get; set; }
  982. public bool pass { get; set; }
  983. public List<string> jointExamId { get; set; } = new(); //已完成的活動評量ID
  984. }
  985. }
  986. }