TriggerSurvey.cs 21 KB

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