TriggerStudy.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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.Common;
  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 TriggerStudy
  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) || tdata.publish == 1)
  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. continue;
  44. }
  45. }
  46. await BIStats.SetTypeAddStats(client, _dingDing, tdata.school, "Study", -1, careDate: tdata.startTime);//BI统计增/减量
  47. return;
  48. }
  49. var adid = tdata.id;
  50. var adcode = "";
  51. string blobcntr = null;
  52. if (tdata.scope.Equals("school"))
  53. {
  54. adcode = $"Activity-{tdata.school}";
  55. blobcntr = tdata.school;
  56. }
  57. else
  58. {
  59. adcode = $"Activity-{tdata.creatorId}";
  60. blobcntr = tdata.creatorId;
  61. }
  62. Study study = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Study>(tdata.id, new Microsoft.Azure.Cosmos.PartitionKey($"{tdata.code}"));
  63. if (study != null)
  64. {
  65. string PartitionKey = string.Format("{0}{1}{2}", study.code, "-", study.progress);
  66. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  67. List<ChangeRecord> changeRecords = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tdata.id }, { "PartitionKey", PartitionKey } });
  68. switch (study.progress)
  69. {
  70. case "pending":
  71. var messageWork = new ServiceBusMessage(new { id = tdata.id, progress = "going", code = tdata.code }.ToJsonString());
  72. messageWork.ApplicationProperties.Add("name", "Study");
  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. try
  101. {
  102. List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
  103. if (study.groupLists.Count > 0)
  104. {
  105. var group = study.groupLists;
  106. foreach (var gp in group)
  107. {
  108. foreach (KeyValuePair<string, List<string>> pp in gp)
  109. {
  110. ps.Add((pp.Key, pp.Value));
  111. }
  112. }
  113. }
  114. (List<RMember> tchList, List<RGroupList> classInfos) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, study.tchLists, study.school, ps);
  115. List<StuActivity> tchActivities = new List<StuActivity>();
  116. (string standard, List<string> tmdids, string school, List<string> update, int statistics) list = (null, null, null, new List<string> { StatisticsService.OfflineRecord }, 0);
  117. if (tchList.IsNotEmpty())
  118. {
  119. list.tmdids = tchList.Select(x => x.id).ToList();
  120. School school = null;
  121. if (!string.IsNullOrEmpty(study.school))
  122. {
  123. school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(study.school, new Microsoft.Azure.Cosmos.PartitionKey("Base"));
  124. list.school = school.id;
  125. list.standard = school.standard;
  126. }
  127. string queryScore = $" select c.id from c where c.id ='{study.id}' and c.pk = 'Activity' ";
  128. List<string> ids = new();
  129. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryStreamIteratorSql
  130. (queryText: queryScore))
  131. {
  132. using var json = await JsonDocument.ParseAsync(item.Content);
  133. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  134. {
  135. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  136. {
  137. if (obj.TryGetProperty("id", out JsonElement acId))
  138. {
  139. ids.Add(acId.GetString());
  140. }
  141. }
  142. }
  143. }
  144. if (ids.Count == 0)
  145. {
  146. tchList.ForEach(x =>
  147. {
  148. tchActivities.Add(new StuActivity
  149. {
  150. pk = "Activity",
  151. id = study.id,
  152. code = $"Activity-{x.id}",
  153. type = "Study",
  154. name = study.name,
  155. startTime = study.startTime,
  156. endTime = study.endTime,
  157. scode = study.code,
  158. scope = study.scope,
  159. school = study.school,
  160. creatorId = study.creatorId,
  161. subjects = new List<string> { "" },
  162. blob = null,
  163. owner = study.owner,
  164. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  165. taskStatus = -1,
  166. classIds = study.tchLists
  167. });
  168. });
  169. }
  170. }
  171. await IESActivityService.SaveStuActivity(client, _dingDing, null, null, tchActivities);
  172. await StatisticsService.SendServiceBus(list, _configuration, _serviceBus, client);
  173. var messageWorkEnd = new ServiceBusMessage(new { id = tdata.id, progress = "finish", code = tdata.code }.ToJsonString());
  174. messageWorkEnd.ApplicationProperties.Add("name", "Study");
  175. if (study.teacIds != null && study.teacIds.Count == 0)
  176. {
  177. study.teacIds = list.tmdids;
  178. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(study, study.id, new Microsoft.Azure.Cosmos.PartitionKey($"{study.code}"));
  179. }
  180. if (changeRecords.Count > 0)
  181. {
  182. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWorkEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.endTime));
  183. try
  184. {
  185. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), changeRecords[0].sequenceNumber);
  186. }
  187. catch (Exception)
  188. {
  189. }
  190. changeRecords[0].sequenceNumber = end;
  191. await table.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
  192. }
  193. else
  194. {
  195. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWorkEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.endTime));
  196. ChangeRecord changeRecord = new()
  197. {
  198. RowKey = tdata.id,
  199. PartitionKey = PartitionKey,
  200. sequenceNumber = end,
  201. msgId = messageWorkEnd.MessageId
  202. };
  203. await table.Save<ChangeRecord>(changeRecord);
  204. }
  205. }
  206. catch (Exception ex)
  207. {
  208. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}研修活动异常-going {ex.Message}\n{ex.StackTrace}{tdata.ToJsonString()}{input}", GroupNames.醍摩豆服務運維群組);
  209. }
  210. finally {
  211. string pk = string.Format("{0}{1}{2}", study.code, "-", "pending");
  212. await table.DeleteSingle<ChangeRecord>(pk, tdata.id);
  213. }
  214. break;
  215. case "finish":
  216. try
  217. {
  218. List<(string pId, List<string> gid)> gls = new List<(string pId, List<string> gid)>();
  219. if (study.groupLists.Count > 0)
  220. {
  221. var group = study.groupLists;
  222. foreach (var gp in group)
  223. {
  224. foreach (KeyValuePair<string, List<string>> pp in gp)
  225. {
  226. gls.Add((pp.Key, pp.Value));
  227. }
  228. }
  229. }
  230. //处理教研活动结束统计账户信息
  231. if (study.staffIds.Count == 0)
  232. {
  233. List<FMember> idList = await GroupListService.GetFinishMemberInfo(_coreAPIHttpService, client, _dingDing, study.school, study.classes, study.stuLists, study.tchLists, gls);
  234. study.staffIds = idList;
  235. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync<Study>(study, study.id, new Microsoft.Azure.Cosmos.PartitionKey(study.code));
  236. }
  237. }
  238. catch (Exception e)
  239. {
  240. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}研修活动异常-finish {e.Message}\n{e.StackTrace}{tdata.ToJsonString()}{input}", GroupNames.醍摩豆服務運維群組);
  241. }
  242. finally {
  243. string pk = string.Format("{0}{1}{2}", study.code, "-", "going");
  244. await table.DeleteSingle<ChangeRecord>(pk, tdata.id);
  245. }
  246. break;
  247. }
  248. }
  249. }
  250. catch (CosmosException e)
  251. {
  252. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}", GroupNames.醍摩豆服務運維群組);
  253. }
  254. catch (Exception ex)
  255. {
  256. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}研修活动异常{ex.Message}\n{ex.StackTrace}{tdata.ToJsonString()}{input}", GroupNames.醍摩豆服務運維群組);
  257. }
  258. }
  259. }
  260. }