TriggerSurvey.cs 17 KB

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