TriggerSurvey.cs 19 KB

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