TriggerSurvey.cs 25 KB

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