TriggerSurvey.cs 21 KB

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