TriggerSurvey.cs 31 KB

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