TriggerSurvey.cs 27 KB

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