TriggerHomework.cs 17 KB

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