TriggerSurvey.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. using Azure.Cosmos;
  2. using Azure.Messaging.ServiceBus;
  3. using Azure.Storage.Blobs.Models;
  4. using Azure.Storage.Sas;
  5. using Microsoft.Azure.Documents;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Net.Http;
  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.Helper.Common.CollectionHelper;
  15. using TEAMModelOS.SDK.Models;
  16. using TEAMModelOS.SDK.Models.Cosmos;
  17. using TEAMModelOS.SDK.Models.Cosmos.Common.Inner;
  18. using TEAMModelOS.SDK.Module.AzureBlob.Configuration;
  19. namespace TEAMModelFunction
  20. {
  21. public class TriggerSurvey
  22. {
  23. public static async void Trigger( AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
  24. CosmosClient client, Document input, TriggerData tdata,AzureRedisFactory _azureRedis)
  25. {
  26. if ((tdata.status != null && tdata.status.Value == 404) || tdata.ttl > 0)
  27. {
  28. return;
  29. }
  30. var adid = tdata.id;
  31. var adcode = "";
  32. string blobcntr = null;
  33. if (tdata.scope == "school")
  34. {
  35. adcode = $"Activity-{tdata.school}";
  36. blobcntr = tdata.school;
  37. }
  38. else if (tdata.scope == "private"){
  39. adcode = $"Activity-{tdata.creatorId}";
  40. blobcntr = tdata.creatorId;
  41. }
  42. ActivityData data = null;
  43. try
  44. {
  45. if (tdata.scope == "school")
  46. {
  47. data = await client.GetContainer("TEAMModelOS", "School").ReadItemAsync<ActivityData>(adid, new Azure.Cosmos.PartitionKey($"{adcode}"));
  48. }
  49. else if (tdata.scope == "private")
  50. {
  51. data = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<ActivityData>(adid, new Azure.Cosmos.PartitionKey($"{adcode}"));
  52. }
  53. }
  54. catch { data = null; }
  55. Survey survey = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Survey>(input.Id, new Azure.Cosmos.PartitionKey($"{tdata.code}"));
  56. List<ChangeRecord> changeRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", survey.progress } });
  57. if (survey != null) {
  58. switch (survey.progress)
  59. {
  60. case "pending":
  61. var messageSurvey = new ServiceBusMessage(new { id = input.Id, progress = "going", code = tdata.code }.ToJsonString());
  62. messageSurvey.ApplicationProperties.Add("name", "Survey");
  63. if (changeRecords.Count > 0)
  64. {
  65. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", changeRecords[0].sequenceNumber);
  66. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageSurvey, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
  67. changeRecords[0].sequenceNumber = start;
  68. await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
  69. }
  70. else
  71. {
  72. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageSurvey, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
  73. ChangeRecord changeRecord = new ChangeRecord
  74. {
  75. RowKey = input.Id,
  76. PartitionKey = "pending",
  77. sequenceNumber = start,
  78. msgId = messageSurvey.MessageId
  79. };
  80. await _azureStorage.Save<ChangeRecord>(changeRecord);
  81. }
  82. break;
  83. case "going":
  84. if (survey.scope == "school")
  85. {
  86. data = new ActivityData
  87. {
  88. id = survey.id,
  89. code = $"Activity-{survey.school}",
  90. type = "survey",
  91. name = survey.name,
  92. startTime = survey.startTime,
  93. endTime = survey.endTime,
  94. scode = survey.code,
  95. scope = survey.scope,
  96. classes = survey.classes.IsNotEmpty() ? survey.classes : new List<string> { "" },
  97. tmdids = survey.tmdids.IsNotEmpty() ? survey.tmdids : new List<string> { "" },
  98. progress = "going",
  99. subjects = new List<string> { "" }
  100. };
  101. await client.GetContainer("TEAMModelOS", "School").UpsertItemAsync<ActivityData>(data, new Azure.Cosmos.PartitionKey(data.code));
  102. }
  103. else if (survey.scope == "private")
  104. {
  105. data = new ActivityData
  106. {
  107. id = survey.id,
  108. code = $"Activity-Common",
  109. type = "survey",
  110. name = survey.name,
  111. startTime = survey.startTime,
  112. endTime = survey.endTime,
  113. scode = survey.code,
  114. scope = survey.scope,
  115. progress = "going",
  116. classes = survey.classes.IsNotEmpty() ? survey.classes : new List<string> { "" },
  117. tmdids = new List<string> { "" },
  118. subjects = new List<string> { "" }
  119. };
  120. await client.GetContainer("TEAMModelOS", "Teacher").UpsertItemAsync<ActivityData>(data, new Azure.Cosmos.PartitionKey(data.code));
  121. }
  122. var messageSurveyEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = tdata.code }.ToJsonString());
  123. messageSurveyEnd.ApplicationProperties.Add("name", "Survey");
  124. if (changeRecords.Count > 0)
  125. {
  126. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageSurveyEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
  127. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", changeRecords[0].sequenceNumber);
  128. changeRecords[0].sequenceNumber = end;
  129. await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
  130. }
  131. else
  132. {
  133. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageSurveyEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
  134. ChangeRecord changeRecord = new ChangeRecord
  135. {
  136. RowKey = input.Id,
  137. PartitionKey = "going",
  138. sequenceNumber = end,
  139. msgId = messageSurveyEnd.MessageId
  140. };
  141. await _azureStorage.Save<ChangeRecord>(changeRecord);
  142. }
  143. await _dingDing.SendBotMsg($"问卷调查{tdata.id}将于:{tdata.etime}完成并结算!", GroupNames.成都开发測試群組);
  144. break;
  145. case "finish":
  146. await _dingDing.SendBotMsg($"问卷调查{tdata.id}开始结算{tdata.etime}!", GroupNames.成都开发測試群組);
  147. var records = await _azureRedis.GetRedisClient(8).HashGetAllAsync($"Survey:Record:{survey.id}");
  148. var submits = await _azureRedis.GetRedisClient(8).SetMembersAsync($"Survey:Submit:{survey.id}");
  149. List<dynamic> recs = new List<dynamic>();
  150. foreach (var rcd in records)
  151. {
  152. var value = rcd.Value.ToString().ToObject<JsonElement>();
  153. recs.Add(new { index = rcd.Name.ToString(), ans = value });
  154. }
  155. List<dynamic> userids = new List<dynamic>();
  156. foreach (var submit in submits)
  157. {
  158. var value = submit.ToString();
  159. userids.Add(value);
  160. }
  161. var cods = new { records = recs, userids };
  162. //问卷整体情况
  163. await _azureStorage.UploadFileByContainer(blobcntr, cods.ToJsonString(), "survey", $"{survey.id}/record.json");
  164. //结算每道题的答题情况
  165. var ContainerClient = _azureStorage.GetBlobContainerClient(blobcntr);
  166. List<Task<string>> tasks = new List<Task<string>>();
  167. //获取
  168. try {
  169. List<string> items = await ContainerClient.List($"survey/{survey.id}/urecord");
  170. List<SurveyRecord> surveyRecords = new List<SurveyRecord>();
  171. foreach (string item in items)
  172. {
  173. var Download = await _azureStorage.GetBlobContainerClient(blobcntr).GetBlobClient(item).DownloadAsync();
  174. var json = await JsonDocument.ParseAsync(Download.Value.Content);
  175. var Record = json.RootElement.ToObject<SurveyRecord>();
  176. surveyRecords.Add(Record);
  177. }
  178. await _dingDing.SendBotMsg($"问卷调查问题结算数据{surveyRecords.ToJsonString()}", GroupNames.成都开发測試群組);
  179. for (int index = 0; index < survey.answers.Count; index++)
  180. {
  181. string url = $"{survey.id}/qrecord/{index}.json";
  182. QuestionRecord question = new QuestionRecord() { index = index };
  183. foreach (SurveyRecord record in surveyRecords)
  184. {
  185. if (record.ans.Count == survey.answers.Count)
  186. {
  187. foreach (var an in record.ans[index])
  188. {
  189. //
  190. if (question.opt.ContainsKey(an))
  191. {
  192. if (question.opt[an] != null)
  193. {
  194. question.opt[an].Add(record.userid);
  195. }
  196. else
  197. {
  198. question.opt[an] = new HashSet<string>() { record.userid };
  199. }
  200. }
  201. else
  202. {
  203. if (survey.answers[index].Contains(an))
  204. {
  205. //如果是客观题code
  206. question.opt.Add(an, new HashSet<string> { record.userid });
  207. }
  208. else
  209. {
  210. //如果不是客观code
  211. question.other[record.userid] = an;
  212. }
  213. }
  214. }
  215. }
  216. }
  217. tasks.Add( _azureStorage.UploadFileByContainer(blobcntr, question.ToJsonString(), "survey", url));
  218. }
  219. await Task.WhenAll(tasks);
  220. } catch (Exception ex) {
  221. await _dingDing.SendBotMsg($"问卷调查问题结算异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  222. }
  223. if (string.IsNullOrEmpty(survey.recordUrl))
  224. {
  225. survey.recordUrl = $"/survey/{survey.id}/record.json";
  226. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync<Survey>(survey, survey.id, new Azure.Cosmos.PartitionKey(survey.code));
  227. }
  228. else {
  229. _azureRedis.GetRedisClient(8).KeyDelete($"Survey:Record:{survey.id}");
  230. _azureRedis.GetRedisClient(8).KeyDelete($"Survey:Submit:{survey.id}");
  231. break;
  232. }
  233. //更新结束状态
  234. data.progress = "finish";
  235. if (survey.scope == "school")
  236. {
  237. await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<ActivityData>(data, data.id, new Azure.Cosmos.PartitionKey(data.code));
  238. }
  239. else if (survey.scope == "private")
  240. {
  241. await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<ActivityData>(data, data.id, new Azure.Cosmos.PartitionKey(data.code));
  242. }
  243. break;
  244. }
  245. }
  246. }
  247. }
  248. /**
  249. * {survey.id}/qrecord/{index}.json
  250. {
  251. "opt": {
  252. "A": [
  253. "userid1",
  254. "userid2",
  255. "userid3"
  256. ],
  257. "B": [
  258. "userid1",
  259. "userid2",
  260. "userid3"
  261. ]
  262. },
  263. "other": {
  264. "userid1": "建议XXXX1",
  265. "userid2": "建议XXXX2"
  266. }
  267. }
  268. **/
  269. public class QuestionRecord {
  270. public int index { get; set; }
  271. public Dictionary<string, HashSet<string>> opt { get; set; } = new Dictionary<string, HashSet<string>>();
  272. public Dictionary<string, string> other { get; set; } = new Dictionary<string, string>();
  273. }
  274. }