TriggerSurvey.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. namespace TEAMModelFunction
  24. {
  25. public class TriggerSurvey
  26. {
  27. public static async void Trigger( AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
  28. CosmosClient client, Document input, TriggerData tdata,AzureRedisFactory _azureRedis, IConfiguration _configuration)
  29. {
  30. try {
  31. if ((tdata.status != null && tdata.status.Value == 404) || tdata.ttl > 0)
  32. {
  33. _azureRedis.GetRedisClient(8).KeyDelete($"Survey:Record:{tdata.id}");
  34. _azureRedis.GetRedisClient(8).KeyDelete($"Survey:Submit:{tdata.id}");
  35. return;
  36. }
  37. var adid = tdata.id;
  38. var adcode = "";
  39. string blobcntr = null;
  40. if (tdata.scope .Equals("school") )
  41. {
  42. adcode = $"Activity-{tdata.school}";
  43. blobcntr = tdata.school;
  44. }
  45. else
  46. {
  47. adcode = $"Activity-{tdata.creatorId}";
  48. blobcntr = tdata.creatorId;
  49. }
  50. Survey survey = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Survey>(input.Id, new Azure.Cosmos.PartitionKey($"{tdata.code}"));
  51. if (survey != null)
  52. {
  53. string PartitionKey = string.Format("{0}{1}{2}", survey.code, "-", survey.progress);
  54. List<ChangeRecord> changeRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", PartitionKey } });
  55. switch (survey.progress)
  56. {
  57. case "pending":
  58. var messageSurvey = new ServiceBusMessage(new { id = input.Id, progress = "going", code = tdata.code }.ToJsonString());
  59. messageSurvey.ApplicationProperties.Add("name", "Survey");
  60. if (changeRecords.Count > 0)
  61. {
  62. await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), changeRecords[0].sequenceNumber);
  63. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageSurvey, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
  64. changeRecords[0].sequenceNumber = start;
  65. await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
  66. }
  67. else
  68. {
  69. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageSurvey, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
  70. ChangeRecord changeRecord = new ChangeRecord
  71. {
  72. RowKey = input.Id,
  73. PartitionKey = PartitionKey,
  74. sequenceNumber = start,
  75. msgId = messageSurvey.MessageId
  76. };
  77. await _azureStorage.Save<ChangeRecord>(changeRecord);
  78. }
  79. break;
  80. case "going":
  81. List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
  82. if (survey.groupLists.Count >0) {
  83. var group = survey.groupLists;
  84. foreach (var gp in group)
  85. {
  86. foreach (KeyValuePair<string, List<string>> pp in gp)
  87. {
  88. ps.Add((pp.Key, pp.Value));
  89. }
  90. }
  91. }
  92. List<string> classes = ExamService.getClasses(survey.classes, survey.stuLists);
  93. (List<RMember> tmdIds, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(client, _dingDing, classes, survey.school);
  94. var addStudentsCls = tmdIds.FindAll(x => x.type == 2);
  95. var addTmdidsCls = tmdIds.FindAll(x => x.type == 1);
  96. #if DEBUG
  97. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查{tdata.id}写入学生表作为活动列表!", GroupNames.成都开发測試群組);
  98. #endif
  99. List<StuActivity> stuActivities = new List<StuActivity>();
  100. List<StuActivity> tmdActivities = new List<StuActivity>();
  101. List<StuActivity> tchActivities = new List<StuActivity>();
  102. if (addTmdidsCls.IsNotEmpty())
  103. {
  104. addTmdidsCls.ForEach(x => {
  105. tmdActivities.Add(new StuActivity
  106. {
  107. pk = "Activity",
  108. id = survey.id,
  109. code = $"Activity-{x.id}",
  110. type = "Survey",
  111. name = survey.name,
  112. startTime = survey.startTime,
  113. endTime = survey.endTime,
  114. scode = survey.code,
  115. scope = survey.scope,
  116. school = survey.school,
  117. creatorId = survey.creatorId,
  118. subjects = new List<string> { "" },
  119. blob = survey.blob,
  120. owner = survey.owner,
  121. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  122. taskStatus = -1,
  123. classIds=classes
  124. });
  125. });
  126. }
  127. if (addStudentsCls.IsNotEmpty())
  128. {
  129. addStudentsCls.ForEach(x => {
  130. stuActivities.Add(new StuActivity
  131. {
  132. pk = "Activity",
  133. id = survey.id,
  134. code = $"Activity-{x.code.Replace("Base-", "")}-{x.id}",
  135. type = "Survey",
  136. name = survey.name,
  137. startTime = survey.startTime,
  138. endTime = survey.endTime,
  139. scode = survey.code,
  140. scope = survey.scope,
  141. school = survey.school,
  142. creatorId = survey.creatorId,
  143. subjects = new List<string> { "" },
  144. blob = survey.blob,
  145. owner = survey.owner,
  146. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  147. taskStatus = -1,
  148. classIds = classes
  149. });
  150. });
  151. }
  152. (List<RMember> tchList, List<RGroupList> classInfos) = await GroupListService.GetStutmdidListids(client, _dingDing, survey.tchLists, survey.school,ps);
  153. // (List<TmdInfo> tmdInfos, List<ClassListInfo> classInfos) = await TriggerStuActivity.GetTchList(client, _dingDing, ids, $"{school}");
  154. //(List<TmdInfo> tchList, _) = await TriggerStuActivity.GetTchList(client, _dingDing, survey.tchLists, survey.school);
  155. List<Task> bustasks = new List<Task>();
  156. if (tchList.IsNotEmpty())
  157. {
  158. School school = null;
  159. if (string.IsNullOrEmpty(survey.school))
  160. {
  161. school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(survey.school, new Azure.Cosmos.PartitionKey("Base"));
  162. }
  163. tchList.ForEach(x => {
  164. tchActivities.Add(new StuActivity
  165. {
  166. pk = "Activity",
  167. id = survey.id,
  168. code = $"Activity-{x.id}",
  169. type = "Survey",
  170. name = survey.name,
  171. startTime = survey.startTime,
  172. endTime = survey.endTime,
  173. scode = survey.code,
  174. scope = survey.scope,
  175. school = survey.school,
  176. creatorId = survey.creatorId,
  177. subjects = new List<string> { "" },
  178. blob = survey.blob,
  179. owner = survey.owner,
  180. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  181. taskStatus = -1,
  182. classIds = survey.tchLists
  183. });
  184. if (school != null)
  185. {
  186. bustasks.Add(StatisticsService.SendServiceBus($"{school.standard}", $"{x.id}", $"{survey.school}", StatisticsService.TeacherSurvey, 0, _configuration, _serviceBus));
  187. }
  188. });
  189. }
  190. await ActivityService.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities, tchActivities);
  191. //向学生或醍摩豆账号发起通知
  192. #region
  193. //Notice notice = new Notice()
  194. //{
  195. // creation = survey.startTime,
  196. // expire = survey.endTime,
  197. // creatorId = survey.creatorId,
  198. // stuids = students,
  199. // tmdids = tmdids,
  200. // type = "notice",//问卷参加参加通知
  201. // priority = "normal",
  202. // //data = new { }.ToJsonString()
  203. // msgId = survey.id,
  204. // school = survey.school,
  205. // scope = survey.scope,
  206. // body = new Body { sid = survey.id, scode = survey.code, spk = survey.pk, biztype = "survey-join" }
  207. //};
  208. //var messageBlob = new ServiceBusMessage(notice.ToJsonString());
  209. //messageBlob.ApplicationProperties.Add("name", "Notice");
  210. //await _serviceBus.GetServiceBusClient().SendMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageBlob);
  211. #endregion
  212. #if DEBUG
  213. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查{tdata.id}写入完成!", GroupNames.成都开发測試群組);
  214. #endif
  215. var messageSurveyEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = tdata.code }.ToJsonString());
  216. messageSurveyEnd.ApplicationProperties.Add("name", "Survey");
  217. if (changeRecords.Count > 0)
  218. {
  219. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageSurveyEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
  220. await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), changeRecords[0].sequenceNumber);
  221. changeRecords[0].sequenceNumber = end;
  222. await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
  223. }
  224. else
  225. {
  226. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageSurveyEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
  227. ChangeRecord changeRecord = new ChangeRecord
  228. {
  229. RowKey = input.Id,
  230. PartitionKey = PartitionKey,
  231. sequenceNumber = end,
  232. msgId = messageSurveyEnd.MessageId
  233. };
  234. await _azureStorage.Save<ChangeRecord>(changeRecord);
  235. }
  236. #if DEBUG
  237. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查{tdata.id}将于:{tdata.etime}完成并结算!", GroupNames.成都开发測試群組);
  238. #endif
  239. if (bustasks.IsNotEmpty())
  240. {
  241. await Task.WhenAll(bustasks);
  242. }
  243. break;
  244. case "finish":
  245. #if DEBUG
  246. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查{tdata.id}开始结算{tdata.etime}!", GroupNames.成都开发測試群組);
  247. #endif
  248. var records = await _azureRedis.GetRedisClient(8).HashGetAllAsync($"Survey:Record:{survey.id}");
  249. var submits = await _azureRedis.GetRedisClient(8).SetMembersAsync($"Survey:Submit:{survey.id}");
  250. List<dynamic> recs = new List<dynamic>();
  251. foreach (var rcd in records)
  252. {
  253. var value = rcd.Value.ToString().ToObject<JsonElement>();
  254. recs.Add(new { index = rcd.Name.ToString(), ans = value });
  255. }
  256. List<dynamic> userids = new List<dynamic>();
  257. foreach (var submit in submits)
  258. {
  259. var value = submit.ToString();
  260. userids.Add(value);
  261. }
  262. List<QuestionRecord> questionRecords = new List<QuestionRecord>();
  263. //结算每道题的答题情况
  264. var ContainerClient = _azureStorage.GetBlobContainerClient(blobcntr);
  265. List<Task<string>> tasks = new List<Task<string>>();
  266. //获取
  267. List<SurveyRecord> surveyRecords = new List<SurveyRecord>();
  268. try
  269. {
  270. List<string> items = await ContainerClient.List($"survey/{survey.id}/urecord");
  271. foreach (string item in items)
  272. {
  273. var Download = await _azureStorage.GetBlobContainerClient(blobcntr).GetBlobClient(item).DownloadAsync();
  274. var json = await JsonDocument.ParseAsync(Download.Value.Content);
  275. var Record = json.RootElement.ToObject<SurveyRecord>();
  276. surveyRecords.Add(Record);
  277. }
  278. #if DEBUG
  279. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查问题结算数据{surveyRecords.ToJsonString()}", GroupNames.成都开发測試群組);
  280. #endif
  281. for (int index = 0; index < survey.answers.Count; index++)
  282. {
  283. string url = $"{survey.id}/qrecord/{index}.json";
  284. QuestionRecord question = new QuestionRecord() { index = index };
  285. foreach (SurveyRecord record in surveyRecords)
  286. {
  287. if (record.ans.Count == survey.answers.Count)
  288. {
  289. foreach (var an in record.ans[index])
  290. {
  291. //
  292. if (question.opt.ContainsKey(an))
  293. {
  294. if (question.opt[an] != null)
  295. {
  296. question.opt[an].Add(record.userid);
  297. }
  298. else
  299. {
  300. question.opt[an] = new HashSet<string>() { record.userid };
  301. }
  302. }
  303. else
  304. {
  305. if (survey.answers[index].Contains(an))
  306. {
  307. //如果是客观题code
  308. question.opt.Add(an, new HashSet<string> { record.userid });
  309. }
  310. else
  311. {
  312. //如果不是客观code
  313. question.other[record.userid] = an;
  314. }
  315. }
  316. }
  317. }
  318. }
  319. questionRecords.Add(question);
  320. tasks.Add( _azureStorage.UploadFileByContainer(blobcntr, question.ToJsonString(), "survey", url));
  321. }
  322. await Task.WhenAll(tasks);
  323. }
  324. catch (Exception ex)
  325. {
  326. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查问题结算异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  327. }
  328. var cods = new { records = recs, userids, question = questionRecords, urecord = surveyRecords };
  329. //问卷整体情况
  330. await _azureStorage.UploadFileByContainer(blobcntr, cods.ToJsonString(), "survey", $"{survey.id}/record.json");
  331. if (string.IsNullOrEmpty(survey.recordUrl))
  332. {
  333. survey.recordUrl = $"/survey/{survey.id}/record.json";
  334. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<Survey>(survey, survey.id, new Azure.Cosmos.PartitionKey(survey.code));
  335. }
  336. else
  337. {
  338. _azureRedis.GetRedisClient(8).KeyDelete($"Survey:Record:{survey.id}");
  339. _azureRedis.GetRedisClient(8).KeyDelete($"Survey:Submit:{survey.id}");
  340. break;
  341. }
  342. //更新结束状态
  343. //data.progress = "finish";
  344. //if (survey.scope .Equals("school"))
  345. //{
  346. // await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<ActivityData>(data, data.id, new Azure.Cosmos.PartitionKey(data.code));
  347. //}
  348. //else if (survey.scope .Equals("private"))
  349. //{
  350. // await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<ActivityData>(data, data.id, new Azure.Cosmos.PartitionKey(data.code));
  351. //}
  352. break;
  353. }
  354. }
  355. } catch (Exception ex) {
  356. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  357. }
  358. }
  359. }
  360. /**
  361. * {survey.id}/qrecord/{index}.json
  362. {
  363. "opt": {
  364. "A": [
  365. "userid1",
  366. "userid2",
  367. "userid3"
  368. ],
  369. "B": [
  370. "userid1",
  371. "userid2",
  372. "userid3"
  373. ]
  374. },
  375. "other": {
  376. "userid1": "建议XXXX1",
  377. "userid2": "建议XXXX2"
  378. }
  379. }
  380. **/
  381. }