TriggerSurvey.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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. using TEAMModelOS.SDK.Models.Service.BI;
  25. namespace TEAMModelOS.FunctionV4
  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 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 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. /*
  129. List<StuActivity> stuActivities = new List<StuActivity>();
  130. List<StuActivity> tmdActivities = new List<StuActivity>();
  131. List<StuActivity> tchActivities = new List<StuActivity>();
  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 Azure.Cosmos.PartitionKey("Base"));
  228. list.school = school.id;
  229. list.standard = school.standard;
  230. }
  231. /*
  232. tchList.ForEach(x =>
  233. {
  234. HashSet<string> classIds = new HashSet<string>();
  235. classInfos.ForEach(z => {
  236. z.members.ForEach(y => {
  237. if (y.id.Equals(x.id) && y.type == 1)
  238. {
  239. classIds.Add(z.id);
  240. }
  241. });
  242. });
  243. tchActivities.Add(new StuActivity
  244. {
  245. pk = "Activity",
  246. id = survey.id,
  247. code = $"Activity-{x.id}",
  248. type = "Survey",
  249. name = survey.name,
  250. startTime = survey.startTime,
  251. endTime = survey.endTime,
  252. scode = survey.code,
  253. scope = survey.scope,
  254. school = survey.school,
  255. creatorId = survey.creatorId,
  256. subjects = new List<string> { "" },
  257. blob = survey.blob,
  258. owner = survey.owner,
  259. isSub = survey.isSub,
  260. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  261. taskStatus = -1,
  262. classIds = classIds.ToList()
  263. });
  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. if (changeRecords.Count > 0)
  296. {
  297. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageSurveyEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.endTime));
  298. try
  299. {
  300. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), changeRecords[0].sequenceNumber);
  301. }
  302. catch (Exception)
  303. {
  304. }
  305. changeRecords[0].sequenceNumber = end;
  306. await table.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
  307. }
  308. else
  309. {
  310. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageSurveyEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.endTime));
  311. ChangeRecord changeRecord = new ChangeRecord
  312. {
  313. RowKey = tdata.id,
  314. PartitionKey = PartitionKey,
  315. sequenceNumber = end,
  316. msgId = messageSurveyEnd.MessageId
  317. };
  318. await table.Save<ChangeRecord>(changeRecord);
  319. }
  320. #if DEBUG
  321. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查{tdata.id}将于:{tdata.endTime}完成并结算!", GroupNames.醍摩豆服務運維群組);
  322. #endif
  323. break;
  324. case "finish":
  325. #if DEBUG
  326. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查{tdata.id}开始结算{tdata.endTime}!", GroupNames.醍摩豆服務運維群組);
  327. #endif
  328. var records = await _azureRedis.GetRedisClient(8).HashGetAllAsync($"Survey:Record:{survey.id}");
  329. var submits = await _azureRedis.GetRedisClient(8).SetMembersAsync($"Survey:Submit:{survey.id}");
  330. List<dynamic> recs = new List<dynamic>();
  331. foreach (var rcd in records)
  332. {
  333. var value = rcd.Value.ToString().ToObject<JsonElement>();
  334. recs.Add(new { index = rcd.Name.ToString(), ans = value });
  335. }
  336. List<dynamic> userids = new List<dynamic>();
  337. foreach (var submit in submits)
  338. {
  339. var value = submit.ToString();
  340. userids.Add(value);
  341. }
  342. List<QuestionRecord> questionRecords = new List<QuestionRecord>();
  343. //结算每道题的答题情况
  344. var ContainerClient = _azureStorage.GetBlobContainerClient(blobcntr);
  345. List<Task<string>> tasks = new List<Task<string>>();
  346. //获取
  347. List<SurveyRecord> surveyRecords = new List<SurveyRecord>();
  348. try
  349. {
  350. List<string> items = await ContainerClient.List($"survey/{survey.id}/urecord");
  351. foreach (string item in items)
  352. {
  353. var Download = await _azureStorage.GetBlobContainerClient(blobcntr).GetBlobClient(item).DownloadAsync();
  354. var json = await JsonDocument.ParseAsync(Download.Value.Content);
  355. var Record = json.RootElement.ToObject<SurveyRecord>();
  356. surveyRecords.Add(Record);
  357. }
  358. #if DEBUG
  359. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查问题结算数据{surveyRecords.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  360. #endif
  361. for (int index = 0; index < survey.answers.Count; index++)
  362. {
  363. string url = $"{survey.id}/qrecord/{index}.json";
  364. QuestionRecord question = new QuestionRecord() { index = index };
  365. foreach (SurveyRecord record in surveyRecords)
  366. {
  367. if (record.ans.Count == survey.answers.Count)
  368. {
  369. foreach (var an in record.ans[index])
  370. {
  371. //
  372. if (question.opt.ContainsKey(an))
  373. {
  374. if (question.opt[an] != null)
  375. {
  376. question.opt[an].Add(record.userid);
  377. }
  378. else
  379. {
  380. question.opt[an] = new HashSet<string>() { record.userid };
  381. }
  382. }
  383. else
  384. {
  385. if (survey.answers[index].Contains(an))
  386. {
  387. //如果是客观题code
  388. question.opt.Add(an, new HashSet<string> { record.userid });
  389. }
  390. else
  391. {
  392. //如果不是客观code
  393. question.other[record.userid] = an;
  394. }
  395. }
  396. }
  397. }
  398. }
  399. questionRecords.Add(question);
  400. tasks.Add(_azureStorage.GetBlobContainerClient(blobcntr).UploadFileByContainer(question.ToJsonString(), "survey", url));
  401. }
  402. await Task.WhenAll(tasks);
  403. }
  404. catch (Exception ex)
  405. {
  406. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查问题结算异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  407. }
  408. var cods = new { records = recs, userids, question = questionRecords, urecord = surveyRecords };
  409. //问卷整体情况
  410. await _azureStorage.GetBlobContainerClient(blobcntr).UploadFileByContainer(cods.ToJsonString(), "survey", $"{survey.id}/record.json");
  411. List<(string pId, List<string> gid)> gls = new List<(string pId, List<string> gid)>();
  412. if (survey.groupLists.Count > 0)
  413. {
  414. var group = survey.groupLists;
  415. foreach (var gp in group)
  416. {
  417. foreach (KeyValuePair<string, List<string>> pp in gp)
  418. {
  419. gls.Add((pp.Key, pp.Value));
  420. }
  421. }
  422. }
  423. //处理问卷调查活动结束统计账户信息
  424. List<FMember> idsList = await GroupListService.GetFinishMemberInfo(_coreAPIHttpService, client, _dingDing, survey.school, survey.classes, survey.stuLists, survey.tchLists,gls);
  425. survey.staffIds = idsList;
  426. if (string.IsNullOrEmpty(survey.recordUrl))
  427. {
  428. survey.recordUrl = $"/survey/{survey.id}/record.json";
  429. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<Survey>(survey, survey.id, new Azure.Cosmos.PartitionKey(survey.code));
  430. }
  431. else
  432. {
  433. _azureRedis.GetRedisClient(8).KeyDelete($"Survey:Record:{survey.id}");
  434. _azureRedis.GetRedisClient(8).KeyDelete($"Survey:Submit:{survey.id}");
  435. break;
  436. }
  437. //更新结束状态
  438. //data.progress = "finish";
  439. //if (survey.scope .Equals("school"))
  440. //{
  441. // await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<ActivityData>(data, data.id, new Azure.Cosmos.PartitionKey(data.code));
  442. //}
  443. //else if (survey.scope .Equals("private"))
  444. //{
  445. // await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<ActivityData>(data, data.id, new Azure.Cosmos.PartitionKey(data.code));
  446. //}
  447. break;
  448. }
  449. }
  450. }
  451. catch (CosmosException e)
  452. {
  453. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.Status}", GroupNames.醍摩豆服務運維群組);
  454. }
  455. catch (Exception ex)
  456. {
  457. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  458. }
  459. }
  460. }
  461. /**
  462. * {survey.id}/qrecord/{index}.json
  463. {
  464. "opt": {
  465. "A": [
  466. "userid1",
  467. "userid2",
  468. "userid3"
  469. ],
  470. "B": [
  471. "userid1",
  472. "userid2",
  473. "userid3"
  474. ]
  475. },
  476. "other": {
  477. "userid1": "建议XXXX1",
  478. "userid2": "建议XXXX2"
  479. }
  480. }
  481. **/
  482. }