TriggerSurvey.cs 22 KB

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