TriggerSurvey.cs 17 KB

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