TriggerSurvey.cs 19 KB

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