TriggerSurvey.cs 21 KB

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