TriggerSurvey.cs 18 KB

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