TriggerSurvey.cs 29 KB

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