TriggerSurvey.cs 29 KB

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