TriggerSurvey.cs 28 KB

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