TriggerHomework.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. using Microsoft.Azure.Cosmos;
  2. using Azure.Messaging.ServiceBus;
  3. using Microsoft.Azure.Documents;
  4. using Microsoft.Extensions.Configuration;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Text.Json;
  10. using System.Threading.Tasks;
  11. using TEAMModelOS.SDK;
  12. using TEAMModelOS.SDK.DI;
  13. using TEAMModelOS.SDK.Extension;
  14. using TEAMModelOS.SDK.Models;
  15. using TEAMModelOS.SDK.Models.Cosmos;
  16. using TEAMModelOS.SDK.Models.Service;
  17. using TEAMModelOS.SDK.Models.Service.BI;
  18. using TEAMModelOS.Function;
  19. namespace TEAMModelOS.CosmosDBTriggers
  20. {
  21. public static class TriggerHomework
  22. {
  23. public static async Task Trigger(CoreAPIHttpService _coreAPIHttpService, AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
  24. CosmosClient client, JsonElement input, TriggerData tdata, AzureRedisFactory _azureRedis, IConfiguration _configuration)
  25. {
  26. try
  27. {
  28. if ((tdata.status != null && tdata.status.Value == 404))
  29. {
  30. await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(tdata.id, new Microsoft.Azure.Cosmos.PartitionKey(tdata.code));
  31. ActivityList data = input.ToObject<ActivityList>();
  32. //await IESActivityService.DeleteActivity(_coreAPIHttpService, client, _dingDing, data);
  33. var table_cancel = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  34. List<ChangeRecord> records = await table_cancel.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tdata.id } });
  35. foreach (var record in records)
  36. {
  37. try
  38. {
  39. await table_cancel.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  40. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  41. }
  42. catch (Exception)
  43. {
  44. continue;
  45. }
  46. }
  47. await BIStats.SetTypeAddStats(client, _dingDing, tdata.school, "Homework", -1, careDate: tdata.startTime);//BI统计增/减量
  48. return;
  49. }
  50. var adid = tdata.id;
  51. var adcode = "";
  52. string blobcntr = null;
  53. if (tdata.scope.Equals("school"))
  54. {
  55. adcode = $"Activity-{tdata.school}";
  56. blobcntr = tdata.school;
  57. }
  58. else
  59. {
  60. adcode = $"Activity-{tdata.creatorId}";
  61. blobcntr = tdata.creatorId;
  62. }
  63. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}作业活动【{tdata.name}-{tdata.id}-ttl={tdata.ttl}】正在操作", GroupNames.醍摩豆服務運維群組);
  64. Homework work = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Homework>(tdata.id, new Microsoft.Azure.Cosmos.PartitionKey($"{tdata.code}"));
  65. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  66. if (work != null)
  67. {
  68. string PartitionKey = string.Format("{0}{1}{2}", work.code, "-", work.progress);
  69. List<ChangeRecord> changeRecords = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tdata.id }, { "PartitionKey", PartitionKey } });
  70. switch (work.progress)
  71. {
  72. case "pending":
  73. var messageWork = new ServiceBusMessage(new { tdata.id, progress = "going", tdata.code }.ToJsonString());
  74. messageWork.ApplicationProperties.Add("name", "Homework");
  75. if (changeRecords.Count > 0)
  76. {
  77. try
  78. {
  79. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), changeRecords[0].sequenceNumber);
  80. }
  81. catch (Exception)
  82. {
  83. }
  84. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWork, DateTimeOffset.FromUnixTimeMilliseconds(tdata.startTime));
  85. changeRecords[0].sequenceNumber = start;
  86. await table.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
  87. }
  88. else
  89. {
  90. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWork, DateTimeOffset.FromUnixTimeMilliseconds(tdata.startTime));
  91. ChangeRecord changeRecord = new()
  92. {
  93. RowKey = tdata.id,
  94. PartitionKey = PartitionKey,
  95. sequenceNumber = start,
  96. msgId = messageWork.MessageId
  97. };
  98. await table.Save<ChangeRecord>(changeRecord);
  99. }
  100. break;
  101. case "going":
  102. try {
  103. await Activity(_coreAPIHttpService, _serviceBus, _dingDing, client, _configuration, work);
  104. var messageWorkEnd = new ServiceBusMessage(new { id = tdata.id, progress = "finish", code = tdata.code }.ToJsonString());
  105. messageWorkEnd.ApplicationProperties.Add("name", "Homework");
  106. if (changeRecords.Count > 0)
  107. {
  108. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWorkEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.endTime));
  109. try
  110. {
  111. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), changeRecords[0].sequenceNumber);
  112. }
  113. catch (Exception)
  114. {
  115. }
  116. changeRecords[0].sequenceNumber = end;
  117. await table.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
  118. }
  119. else
  120. {
  121. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWorkEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.endTime));
  122. ChangeRecord changeRecord = new()
  123. {
  124. RowKey = tdata.id,
  125. PartitionKey = PartitionKey,
  126. sequenceNumber = end,
  127. msgId = messageWorkEnd.MessageId
  128. };
  129. await table.Save<ChangeRecord>(changeRecord);
  130. }
  131. if (work!=null && work.scope.Equals("private"))
  132. {
  133. await SystemService.RecordAccumulateData(_azureRedis, _dingDing, new SDK.Models.Dtos.Accumulate { client="web", count=1, id=work.id, key="homework-going", name=work.name, scope="teacher", target=work.creatorId });
  134. }
  135. } catch (Exception e) {
  136. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}研修作业活动going{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
  137. }
  138. finally {
  139. string pkey = string.Format("{0}{1}{2}", work.code, "-", "pending");
  140. await table.DeleteSingle<ChangeRecord>(pkey, tdata.id);
  141. }
  142. //if (bustasks.IsNotEmpty())
  143. //{
  144. // await Task.WhenAll(bustasks);
  145. //}
  146. break;
  147. case "finish":
  148. try {
  149. await Activity(_coreAPIHttpService, _serviceBus, _dingDing, client, _configuration, work);
  150. List<(string pId, List<string> gid)> gls = 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. gls.Add((pp.Key, pp.Value));
  159. }
  160. }
  161. }
  162. //处理家庭作业活动结束统计账户信息
  163. if (work.staffIds.Count == 0)
  164. {
  165. List<FMember> idsList = await GroupListService.GetFinishMemberInfo(_coreAPIHttpService, client, _dingDing, work.school, work.classes, work.stuLists, work.tchLists, gls);
  166. work.staffIds = idsList;
  167. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync<Homework>(work, work.id, new Microsoft.Azure.Cosmos.PartitionKey(work.code));
  168. }
  169. } catch (Exception e) {
  170. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}研修作业活动finish{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
  171. } finally {
  172. string pk = string.Format("{0}{1}{2}", work.code, "-", "going");
  173. await table.DeleteSingle<ChangeRecord>(pk, tdata.id);
  174. }
  175. break;
  176. }
  177. }
  178. }
  179. catch (CosmosException e)
  180. {
  181. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}", GroupNames.醍摩豆服務運維群組);
  182. }
  183. catch (Exception ex)
  184. {
  185. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}研修作业活动异常{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  186. }
  187. }
  188. private static async Task Activity(CoreAPIHttpService _coreAPIHttpService, AzureServiceBusFactory _serviceBus, DingDing _dingDing, CosmosClient client, IConfiguration _configuration, Homework work)
  189. {
  190. List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
  191. if (work.groupLists.Count > 0)
  192. {
  193. var group = work.groupLists;
  194. foreach (var gp in group)
  195. {
  196. foreach (KeyValuePair<string, List<string>> pp in gp)
  197. {
  198. ps.Add((pp.Key, pp.Value));
  199. }
  200. }
  201. }
  202. List<string> classes = ExamService.getClasses(work.classes, work.stuLists);
  203. (List<RMember> tmdids, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, classes, work.school, ps);
  204. var addStudentsCls = tmdids.FindAll(x => x.type == 2);
  205. var addTmdidsCls = tmdids.FindAll(x => x.type == 1);
  206. //List<StuActivity> stuActivities = new();
  207. //List<StuActivity> tmdActivities = new();
  208. //List<StuActivity> tchActivities = new();
  209. //List<StuActivity> tac = new();
  210. List<string> tIds = addStudentsCls.Select(x => x.id).ToList();
  211. /*
  212. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIteratorSql<StuActivity>(queryText: $"select value(c) from c where c.id ='{work.id}' and c.type = 'Homework'"))
  213. {
  214. tac.Add(item);
  215. }
  216. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<StuActivity>(queryText: $"select value(c) from c where c.id ='{work.id}' and c.type = 'Homework'"))
  217. {
  218. tac.Add(item);
  219. }
  220. List<string> sub = new();
  221. if (work.tchLists.Count == 0)
  222. {
  223. if (work.targets.Count > 0)
  224. {
  225. foreach (var course in work.targets)
  226. {
  227. var info = course.ToObject<List<string>>();
  228. if (info.Count > 1)
  229. {
  230. sub.Add(info[0]);
  231. }
  232. }
  233. }
  234. }
  235. if (addTmdidsCls.IsNotEmpty())
  236. {
  237. addTmdidsCls.ForEach(x =>
  238. {
  239. HashSet<string> classIds = new HashSet<string>();
  240. classLists.ForEach(z =>
  241. {
  242. z.members.ForEach(y =>
  243. {
  244. if (y.id.Equals(x.id) && y.type == 1)
  245. {
  246. classIds.Add(z.id);
  247. }
  248. });
  249. });
  250. int sta = -1;
  251. if (tac.Count > 0)
  252. {
  253. StuActivity activity = tac.Where(t => t.code.Equals($"Activity-{x.id}")).FirstOrDefault();
  254. if (activity != null)
  255. {
  256. sta = activity.taskStatus;
  257. }
  258. }
  259. tmdActivities.Add(new StuActivity
  260. {
  261. pk = "Activity",
  262. id = work.id,
  263. code = $"Activity-{x.id}",
  264. type = "Homework",
  265. name = work.name,
  266. startTime = work.startTime,
  267. endTime = work.endTime,
  268. scode = work.code,
  269. scope = work.scope,
  270. school = work.school,
  271. creatorId = work.creatorId,
  272. subjects = sub,
  273. blob = work.blob,
  274. owner = work.owner,
  275. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  276. taskStatus = sta,
  277. mustSubmit = work.mustSubmit,
  278. classIds = classIds.ToList()
  279. });
  280. });
  281. }
  282. if (addStudentsCls.IsNotEmpty())
  283. {
  284. addStudentsCls.ForEach(x =>
  285. {
  286. HashSet<string> classIds = new HashSet<string>();
  287. classLists.ForEach(z =>
  288. {
  289. z.members.ForEach(y =>
  290. {
  291. if (y.id.Equals(x.id) && y.type == 2)
  292. {
  293. classIds.Add(z.id);
  294. }
  295. });
  296. });
  297. int sta = -1;
  298. if (tac.Count > 0)
  299. {
  300. StuActivity activity = tac.Where(t => t.code.Equals($"Activity-{x.code.Replace("Base-", "")}-{x.id}")).FirstOrDefault();
  301. if (activity != null)
  302. {
  303. sta = activity.taskStatus;
  304. }
  305. }
  306. stuActivities.Add(new StuActivity
  307. {
  308. pk = "Activity",
  309. id = work.id,
  310. code = $"Activity-{x.code.Replace("Base-", "")}-{x.id}",
  311. type = "Homework",
  312. name = work.name,
  313. startTime = work.startTime,
  314. endTime = work.endTime,
  315. scode = work.code,
  316. scope = work.scope,
  317. school = work.school,
  318. creatorId = work.creatorId,
  319. subjects = sub,
  320. blob = work.blob,
  321. owner = work.owner,
  322. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  323. taskStatus = sta,
  324. classIds = classIds.ToList(),
  325. mustSubmit = work.mustSubmit
  326. });
  327. });
  328. }
  329. */
  330. (List<RMember> tchList, List<RGroupList> classInfos) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, work.tchLists, work.school, ps);
  331. (string standard, List<string> tmdids, string school, List<string> update, int statistics) list = (null, null, null, new List<string> { StatisticsService.OfflineRecord }, 0);
  332. if (tchList.IsNotEmpty())
  333. {
  334. list.tmdids = tchList.Select(x => x.id).ToList();
  335. School school = null;
  336. if (!string.IsNullOrEmpty(work.school))
  337. {
  338. school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(work.school, new Microsoft.Azure.Cosmos.PartitionKey("Base"));
  339. list.school = school.id;
  340. list.standard = school.standard;
  341. }
  342. /*
  343. tchList.ForEach(x =>
  344. {
  345. HashSet<string> classIds = new();
  346. classInfos.ForEach(z =>
  347. {
  348. z.members.ForEach(y =>
  349. {
  350. if (y.id.Equals(x.id) && y.type == 1)
  351. {
  352. classIds.Add(z.id);
  353. }
  354. });
  355. });
  356. int sta = -1;
  357. if (tac.Count > 0)
  358. {
  359. StuActivity activity = tac.Where(t => t.code.Equals($"Activity-{x.id}")).FirstOrDefault();
  360. if (activity != null)
  361. {
  362. sta = activity.taskStatus;
  363. }
  364. }
  365. tchActivities.Add(new StuActivity
  366. {
  367. pk = "Activity",
  368. id = work.id,
  369. code = $"Activity-{x.id}",
  370. type = "Homework",
  371. name = work.name,
  372. startTime = work.startTime,
  373. endTime = work.endTime,
  374. scode = work.code,
  375. scope = work.scope,
  376. school = work.school,
  377. creatorId = work.creatorId,
  378. subjects = new List<string> { "" },
  379. blob = work.blob,
  380. owner = work.owner,
  381. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  382. taskStatus = sta,
  383. classIds = classIds.ToList()
  384. });
  385. });
  386. */
  387. }
  388. //await IESActivityService.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities, tchActivities);
  389. await StatisticsService.SendServiceBus(list, _configuration, _serviceBus, client);
  390. }
  391. }
  392. }