TriggerSurvey.cs 25 KB

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