TriggerSurvey.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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, _dingDing, 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. owner = survey.owner
  96. });
  97. });
  98. }
  99. if (students.IsNotEmpty()) {
  100. students.ForEach(x => {
  101. stuActivities.Add(new StuActivity {
  102. pk = "Activity",
  103. id = survey.id,
  104. code = $"Activity-{survey.school}-{x.id}",
  105. type = "Survey",
  106. name = survey.name,
  107. startTime = survey.startTime,
  108. endTime = survey.endTime,
  109. scode = survey.code,
  110. scope = survey.scope,
  111. school = survey.school,
  112. creatorId = survey.creatorId,
  113. subjects = new List<string> { "" },
  114. blob = survey.blob,
  115. owner = survey.owner
  116. });
  117. });
  118. }
  119. await TriggerStuActivity.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities);
  120. //向学生或醍摩豆账号发起通知
  121. #region
  122. Notice notice = new Notice()
  123. {
  124. creation = survey.startTime,
  125. expire = survey.endTime,
  126. creatorId = survey.creatorId,
  127. stuids = students,
  128. tmdids = tmdids,
  129. type = "notice",//问卷参加参加通知
  130. priority = "normal",
  131. //data = new { }.ToJsonString()
  132. msgId = survey.id,
  133. school = survey.school,
  134. scope = survey.scope,
  135. body = new Body { sid = survey.id, scode = survey.code, spk = survey.pk, biztype = "survey-join" }
  136. };
  137. //var messageBlob = new ServiceBusMessage(notice.ToJsonString());
  138. //messageBlob.ApplicationProperties.Add("name", "Notice");
  139. //await _serviceBus.GetServiceBusClient().SendMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageBlob);
  140. #endregion
  141. #if DEBUG
  142. await _dingDing.SendBotMsg($"问卷调查{tdata.id}写入完成!", GroupNames.成都开发測試群組);
  143. #endif
  144. var messageSurveyEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = tdata.code }.ToJsonString());
  145. messageSurveyEnd.ApplicationProperties.Add("name", "Survey");
  146. if (changeRecords.Count > 0)
  147. {
  148. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageSurveyEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
  149. await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), changeRecords[0].sequenceNumber);
  150. changeRecords[0].sequenceNumber = end;
  151. await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
  152. }
  153. else
  154. {
  155. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageSurveyEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
  156. ChangeRecord changeRecord = new ChangeRecord
  157. {
  158. RowKey = input.Id,
  159. PartitionKey = "going",
  160. sequenceNumber = end,
  161. msgId = messageSurveyEnd.MessageId
  162. };
  163. await _azureStorage.Save<ChangeRecord>(changeRecord);
  164. }
  165. #if DEBUG
  166. await _dingDing.SendBotMsg($"问卷调查{tdata.id}将于:{tdata.etime}完成并结算!", GroupNames.成都开发測試群組);
  167. #endif
  168. break;
  169. case "finish":
  170. #if DEBUG
  171. await _dingDing.SendBotMsg($"问卷调查{tdata.id}开始结算{tdata.etime}!", GroupNames.成都开发測試群組);
  172. #endif
  173. var records = await _azureRedis.GetRedisClient(8).HashGetAllAsync($"Survey:Record:{survey.id}");
  174. var submits = await _azureRedis.GetRedisClient(8).SetMembersAsync($"Survey:Submit:{survey.id}");
  175. List<dynamic> recs = new List<dynamic>();
  176. foreach (var rcd in records)
  177. {
  178. var value = rcd.Value.ToString().ToObject<JsonElement>();
  179. recs.Add(new { index = rcd.Name.ToString(), ans = value });
  180. }
  181. List<dynamic> userids = new List<dynamic>();
  182. foreach (var submit in submits)
  183. {
  184. var value = submit.ToString();
  185. userids.Add(value);
  186. }
  187. List<QuestionRecord> questionRecords = new List<QuestionRecord>();
  188. //结算每道题的答题情况
  189. var ContainerClient = _azureStorage.GetBlobContainerClient(blobcntr);
  190. //List<Task<string>> tasks = new List<Task<string>>();
  191. //获取
  192. try {
  193. List<string> items = await ContainerClient.List($"survey/{survey.id}/urecord");
  194. List<SurveyRecord> surveyRecords = new List<SurveyRecord>();
  195. foreach (string item in items)
  196. {
  197. var Download = await _azureStorage.GetBlobContainerClient(blobcntr).GetBlobClient(item).DownloadAsync();
  198. var json = await JsonDocument.ParseAsync(Download.Value.Content);
  199. var Record = json.RootElement.ToObject<SurveyRecord>();
  200. surveyRecords.Add(Record);
  201. }
  202. #if DEBUG
  203. await _dingDing.SendBotMsg($"问卷调查问题结算数据{surveyRecords.ToJsonString()}", GroupNames.成都开发測試群組);
  204. #endif
  205. for (int index = 0; index < survey.answers.Count; index++)
  206. {
  207. string url = $"{survey.id}/qrecord/{index}.json";
  208. QuestionRecord question = new QuestionRecord() { index = index };
  209. foreach (SurveyRecord record in surveyRecords)
  210. {
  211. if (record.ans.Count == survey.answers.Count)
  212. {
  213. foreach (var an in record.ans[index])
  214. {
  215. //
  216. if (question.opt.ContainsKey(an))
  217. {
  218. if (question.opt[an] != null)
  219. {
  220. question.opt[an].Add(record.userid);
  221. }
  222. else
  223. {
  224. question.opt[an] = new HashSet<string>() { record.userid };
  225. }
  226. }
  227. else
  228. {
  229. if (survey.answers[index].Contains(an))
  230. {
  231. //如果是客观题code
  232. question.opt.Add(an, new HashSet<string> { record.userid });
  233. }
  234. else
  235. {
  236. //如果不是客观code
  237. question.other[record.userid] = an;
  238. }
  239. }
  240. }
  241. }
  242. }
  243. questionRecords.Add(question);
  244. //tasks.Add( _azureStorage.UploadFileByContainer(blobcntr, question.ToJsonString(), "survey", url));
  245. }
  246. // await Task.WhenAll(tasks);
  247. } catch (Exception ex) {
  248. await _dingDing.SendBotMsg($"问卷调查问题结算异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  249. }
  250. var cods = new { records = recs, userids, question= questionRecords };
  251. //问卷整体情况
  252. await _azureStorage.UploadFileByContainer(blobcntr, cods.ToJsonString(), "survey", $"{survey.id}/record.json");
  253. if (string.IsNullOrEmpty(survey.recordUrl))
  254. {
  255. survey.recordUrl = $"/survey/{survey.id}/record.json";
  256. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync<Survey>(survey, survey.id, new Azure.Cosmos.PartitionKey(survey.code));
  257. }
  258. else {
  259. _azureRedis.GetRedisClient(8).KeyDelete($"Survey:Record:{survey.id}");
  260. _azureRedis.GetRedisClient(8).KeyDelete($"Survey:Submit:{survey.id}");
  261. break;
  262. }
  263. //更新结束状态
  264. //data.progress = "finish";
  265. //if (survey.scope == "school")
  266. //{
  267. // await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<ActivityData>(data, data.id, new Azure.Cosmos.PartitionKey(data.code));
  268. //}
  269. //else if (survey.scope == "private")
  270. //{
  271. // await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<ActivityData>(data, data.id, new Azure.Cosmos.PartitionKey(data.code));
  272. //}
  273. break;
  274. }
  275. }
  276. }
  277. }
  278. /**
  279. * {survey.id}/qrecord/{index}.json
  280. {
  281. "opt": {
  282. "A": [
  283. "userid1",
  284. "userid2",
  285. "userid3"
  286. ],
  287. "B": [
  288. "userid1",
  289. "userid2",
  290. "userid3"
  291. ]
  292. },
  293. "other": {
  294. "userid1": "建议XXXX1",
  295. "userid2": "建议XXXX2"
  296. }
  297. }
  298. **/
  299. public class QuestionRecord {
  300. public int index { get; set; }
  301. public Dictionary<string, HashSet<string>> opt { get; set; } = new Dictionary<string, HashSet<string>>();
  302. public Dictionary<string, string> other { get; set; } = new Dictionary<string, string>();
  303. }
  304. }