TriggerSurvey.cs 26 KB

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