TriggerHomework.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. using Azure.Cosmos;
  2. using Azure.Messaging.ServiceBus;
  3. using HTEXLib.COMM.Helpers;
  4. using Microsoft.Azure.Documents;
  5. using Microsoft.Extensions.Configuration;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Text.Json;
  11. using System.Threading.Tasks;
  12. using TEAMModelOS.SDK;
  13. using TEAMModelOS.SDK.DI;
  14. using TEAMModelOS.SDK.Extension;
  15. using TEAMModelOS.SDK.Models;
  16. using TEAMModelOS.SDK.Models.Cosmos.Common;
  17. using TEAMModelOS.SDK.Models.Service;
  18. namespace TEAMModelOS.FunctionV4
  19. {
  20. public static class TriggerHomework
  21. {
  22. public static async Task Trigger(CoreAPIHttpService _coreAPIHttpService, AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
  23. CosmosClient client, JsonElement input, TriggerData tdata, AzureRedisFactory _azureRedis, IConfiguration _configuration)
  24. {
  25. try
  26. {
  27. if ((tdata.status != null && tdata.status.Value == 404))
  28. {
  29. await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(tdata.id, new PartitionKey(tdata.code));
  30. ActivityList data = input.ToObject<ActivityList>();
  31. await ActivityService.DeleteActivity(_coreAPIHttpService, client, _dingDing, data);
  32. var table_cancel = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  33. List<ChangeRecord> records = await table_cancel.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tdata.id } });
  34. foreach (var record in records)
  35. {
  36. try
  37. {
  38. await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  39. }
  40. catch (Exception)
  41. {
  42. continue;
  43. }
  44. }
  45. return;
  46. }
  47. var adid = tdata.id;
  48. var adcode = "";
  49. string blobcntr = null;
  50. if (tdata.scope.Equals("school"))
  51. {
  52. adcode = $"Activity-{tdata.school}";
  53. blobcntr = tdata.school;
  54. }
  55. else
  56. {
  57. adcode = $"Activity-{tdata.creatorId}";
  58. blobcntr = tdata.creatorId;
  59. }
  60. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}作业活动【{tdata.name}-{tdata.id}-ttl={tdata.ttl}】正在操作", GroupNames.成都开发測試群組);
  61. Homework work = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Homework>(tdata.id, new Azure.Cosmos.PartitionKey($"{tdata.code}"));
  62. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  63. if (work != null)
  64. {
  65. string PartitionKey = string.Format("{0}{1}{2}", work.code, "-", work.progress);
  66. List<ChangeRecord> changeRecords = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tdata.id }, { "PartitionKey", PartitionKey } });
  67. switch (work.progress)
  68. {
  69. case "pending":
  70. var messageWork = new ServiceBusMessage(new { tdata.id, progress = "going", tdata.code }.ToJsonString());
  71. messageWork.ApplicationProperties.Add("name", "Homework");
  72. if (changeRecords.Count > 0)
  73. {
  74. await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), changeRecords[0].sequenceNumber);
  75. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWork, DateTimeOffset.FromUnixTimeMilliseconds(tdata.startTime));
  76. changeRecords[0].sequenceNumber = start;
  77. await table.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
  78. }
  79. else
  80. {
  81. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWork, DateTimeOffset.FromUnixTimeMilliseconds(tdata.startTime));
  82. ChangeRecord changeRecord = new()
  83. {
  84. RowKey = tdata.id,
  85. PartitionKey = PartitionKey,
  86. sequenceNumber = start,
  87. msgId = messageWork.MessageId
  88. };
  89. await table.Save<ChangeRecord>(changeRecord);
  90. }
  91. break;
  92. case "going":
  93. await Activity(_coreAPIHttpService, _serviceBus, _dingDing, client, _configuration, work);
  94. var messageWorkEnd = new ServiceBusMessage(new { id = tdata.id, progress = "finish", code = tdata.code }.ToJsonString());
  95. messageWorkEnd.ApplicationProperties.Add("name", "Homework");
  96. if (changeRecords.Count > 0)
  97. {
  98. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWorkEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.endTime));
  99. await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), changeRecords[0].sequenceNumber);
  100. changeRecords[0].sequenceNumber = end;
  101. await table.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
  102. }
  103. else
  104. {
  105. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWorkEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.endTime));
  106. ChangeRecord changeRecord = new()
  107. {
  108. RowKey = tdata.id,
  109. PartitionKey = PartitionKey,
  110. sequenceNumber = end,
  111. msgId = messageWorkEnd.MessageId
  112. };
  113. await table.Save<ChangeRecord>(changeRecord);
  114. }
  115. //if (bustasks.IsNotEmpty())
  116. //{
  117. // await Task.WhenAll(bustasks);
  118. //}
  119. break;
  120. case "finish":
  121. await Activity(_coreAPIHttpService, _serviceBus, _dingDing, client, _configuration, work);
  122. break;
  123. }
  124. }
  125. }
  126. catch (CosmosException e)
  127. {
  128. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDB异常{e.StackTrace}{e.Message}\n{e.Status}", GroupNames.成都开发測試群組);
  129. }
  130. catch (Exception ex)
  131. {
  132. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}研修作业活动异常{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  133. }
  134. }
  135. private static async Task Activity(CoreAPIHttpService _coreAPIHttpService, AzureServiceBusFactory _serviceBus, DingDing _dingDing, CosmosClient client, IConfiguration _configuration, Homework work)
  136. {
  137. List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
  138. if (work.groupLists.Count > 0)
  139. {
  140. var group = work.groupLists;
  141. foreach (var gp in group)
  142. {
  143. foreach (KeyValuePair<string, List<string>> pp in gp)
  144. {
  145. ps.Add((pp.Key, pp.Value));
  146. }
  147. }
  148. }
  149. List<string> classes = ExamService.getClasses(work.classes, work.stuLists);
  150. (List<RMember> tmdids, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, classes, work.school, ps);
  151. var addStudentsCls = tmdids.FindAll(x => x.type == 2);
  152. var addTmdidsCls = tmdids.FindAll(x => x.type == 1);
  153. List<StuActivity> stuActivities = new();
  154. List<StuActivity> tmdActivities = new();
  155. List<StuActivity> tchActivities = new();
  156. List<string> tIds = addStudentsCls.Select(x => x.id).ToList();
  157. List<StuActivity> tac = new();
  158. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<StuActivity>(queryText: $"select value(c) from c where c.id ='{work.id}' and c.type = 'Homework'"))
  159. {
  160. tac.Add(item);
  161. }
  162. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<StuActivity>(queryText: $"select value(c) from c where c.id ='{work.id}' and c.type = 'Homework'"))
  163. {
  164. tac.Add(item);
  165. }
  166. if (addTmdidsCls.IsNotEmpty())
  167. {
  168. addTmdidsCls.ForEach(x =>
  169. {
  170. HashSet<string> classIds = new HashSet<string>();
  171. classLists.ForEach(z =>
  172. {
  173. z.members.ForEach(y =>
  174. {
  175. if (y.id.Equals(x) && y.type == 1)
  176. {
  177. classIds.Add(z.id);
  178. }
  179. });
  180. });
  181. int sta = -1;
  182. if (tac.Count > 0)
  183. {
  184. StuActivity activity = tac.Where(t => t.code.Equals($"Activity-{x.id}")).FirstOrDefault();
  185. if (activity != null)
  186. {
  187. sta = activity.taskStatus;
  188. }
  189. }
  190. tmdActivities.Add(new StuActivity
  191. {
  192. pk = "Activity",
  193. id = work.id,
  194. code = $"Activity-{x.id}",
  195. type = "Homework",
  196. name = work.name,
  197. startTime = work.startTime,
  198. endTime = work.endTime,
  199. scode = work.code,
  200. scope = work.scope,
  201. school = work.school,
  202. creatorId = work.creatorId,
  203. subjects = new List<string> { "" },
  204. blob = work.blob,
  205. owner = work.owner,
  206. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  207. taskStatus = sta,
  208. mustSubmit = work.mustSubmit,
  209. classIds = classIds.ToList()
  210. });
  211. });
  212. }
  213. if (addStudentsCls.IsNotEmpty())
  214. {
  215. addStudentsCls.ForEach(x =>
  216. {
  217. HashSet<string> classIds = new HashSet<string>();
  218. classLists.ForEach(z =>
  219. {
  220. z.members.ForEach(y =>
  221. {
  222. if (y.id.Equals(x) && y.code.Equals(work.school) && y.type == 2)
  223. {
  224. classIds.Add(z.id);
  225. }
  226. });
  227. });
  228. int sta = -1;
  229. if (tac.Count > 0)
  230. {
  231. StuActivity activity = tac.Where(t => t.code.Equals($"Activity-{x.code.Replace("Base-", "")}-{x.id}")).FirstOrDefault();
  232. if (activity != null)
  233. {
  234. sta = activity.taskStatus;
  235. }
  236. }
  237. stuActivities.Add(new StuActivity
  238. {
  239. pk = "Activity",
  240. id = work.id,
  241. code = $"Activity-{x.code.Replace("Base-", "")}-{x.id}",
  242. type = "Homework",
  243. name = work.name,
  244. startTime = work.startTime,
  245. endTime = work.endTime,
  246. scode = work.code,
  247. scope = work.scope,
  248. school = work.school,
  249. creatorId = work.creatorId,
  250. subjects = new List<string> { "" },
  251. blob = work.blob,
  252. owner = work.owner,
  253. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  254. taskStatus = sta,
  255. classIds = classIds.ToList(),
  256. mustSubmit = work.mustSubmit
  257. });
  258. });
  259. }
  260. (List<RMember> tchList, List<RGroupList> classInfos) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, work.tchLists, work.school, ps);
  261. (string standard, List<string> tmdids, string school, List<string> update, int statistics) list = (null, null, null, new List<string> { StatisticsService.OfflineRecord }, 0);
  262. if (tchList.IsNotEmpty())
  263. {
  264. list.tmdids = tchList.Select(x => x.id).ToList();
  265. School school = null;
  266. if (!string.IsNullOrEmpty(work.school))
  267. {
  268. school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(work.school, new Azure.Cosmos.PartitionKey("Base"));
  269. list.school = school.id;
  270. list.standard = school.standard;
  271. }
  272. tchList.ForEach(x =>
  273. {
  274. HashSet<string> classIds = new();
  275. classInfos.ForEach(z =>
  276. {
  277. z.members.ForEach(y =>
  278. {
  279. if (y.id.Equals(x) && y.type == 1)
  280. {
  281. classIds.Add(z.id);
  282. }
  283. });
  284. });
  285. int sta = -1;
  286. if (tac.Count > 0)
  287. {
  288. StuActivity activity = tac.Where(t => t.code.Equals($"Activity-{x.id}")).FirstOrDefault();
  289. if (activity != null)
  290. {
  291. sta = activity.taskStatus;
  292. }
  293. }
  294. tchActivities.Add(new StuActivity
  295. {
  296. pk = "Activity",
  297. id = work.id,
  298. code = $"Activity-{x.id}",
  299. type = "Homework",
  300. name = work.name,
  301. startTime = work.startTime,
  302. endTime = work.endTime,
  303. scode = work.code,
  304. scope = work.scope,
  305. school = work.school,
  306. creatorId = work.creatorId,
  307. subjects = new List<string> { "" },
  308. blob = work.blob,
  309. owner = work.owner,
  310. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  311. taskStatus = sta,
  312. classIds = classIds.ToList()
  313. });
  314. });
  315. }
  316. await ActivityService.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities, tchActivities);
  317. await StatisticsService.SendServiceBus(list, _configuration, _serviceBus, client);
  318. }
  319. }
  320. }