TriggerSurvey.cs 30 KB

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