TriggerSurvey.cs 23 KB

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