瀏覽代碼

问卷调查,投票活动采用实时结算方式计算结算数据。

CrazyIter_Bin 3 年之前
父節點
當前提交
4c681d74a6

+ 6 - 11
TEAMModelFunction/TriggerSurvey.cs

@@ -39,7 +39,7 @@ namespace TEAMModelFunction
                     adcode = $"Activity-{tdata.school}";
                     blobcntr = tdata.school;
                 }
-                else if (tdata.scope .Equals("private"))
+                else 
                 {
                     adcode = $"Activity-{tdata.creatorId}";
                     blobcntr = tdata.creatorId;
@@ -200,7 +200,7 @@ namespace TEAMModelFunction
                             List<QuestionRecord> questionRecords = new List<QuestionRecord>();
                             //结算每道题的答题情况
                             var ContainerClient = _azureStorage.GetBlobContainerClient(blobcntr);
-                            //List<Task<string>> tasks = new List<Task<string>>();
+                            List<Task<string>> tasks = new List<Task<string>>();
                             //获取
                             try
                             {
@@ -255,9 +255,9 @@ namespace TEAMModelFunction
                                         }
                                     }
                                     questionRecords.Add(question);
-                                    //tasks.Add(  _azureStorage.UploadFileByContainer(blobcntr, question.ToJsonString(), "survey", url));
+                                    tasks.Add(  _azureStorage.UploadFileByContainer(blobcntr, question.ToJsonString(), "survey", url));
                                 }
-                                // await Task.WhenAll(tasks);
+                                 await Task.WhenAll(tasks);
                             }
                             catch (Exception ex)
                             {
@@ -273,8 +273,8 @@ namespace TEAMModelFunction
                             }
                             else
                             {
-                                //_azureRedis.GetRedisClient(8).KeyDelete($"Survey:Record:{survey.id}");
-                                //_azureRedis.GetRedisClient(8).KeyDelete($"Survey:Submit:{survey.id}");
+                                _azureRedis.GetRedisClient(8).KeyDelete($"Survey:Record:{survey.id}");
+                                _azureRedis.GetRedisClient(8).KeyDelete($"Survey:Submit:{survey.id}");
                                 break;
                             }
 
@@ -319,9 +319,4 @@ namespace TEAMModelFunction
             }
         }
      **/
-    public class QuestionRecord { 
-        public int index { get; set; }
-        public Dictionary<string, HashSet<string>> opt { get; set; } = new Dictionary<string, HashSet<string>>();
-        public Dictionary<string, string> other { get; set; } = new Dictionary<string, string>();
-    }
 }

+ 3 - 3
TEAMModelFunction/TriggerVote.cs

@@ -37,7 +37,7 @@ namespace TEAMModelFunction
                     adcode = $"Activity-{tdata.school}";
                     blobcntr = tdata.school;
                 }
-                else if (tdata.scope.Equals("private"))
+                else  
                 {
                     adcode = $"Activity-{tdata.creatorId}";
                     blobcntr = tdata.creatorId;
@@ -224,8 +224,8 @@ namespace TEAMModelFunction
                             else
                             {
                                 //异动,且已经有结算记录则不必再继续。
-                                //_azureRedis.GetRedisClient(8).KeyDelete($"Vote:Record:{vote.id}");
-                                //_azureRedis.GetRedisClient(8).KeyDelete($"Vote:Count:{vote.id}");
+                                _azureRedis.GetRedisClient(8).KeyDelete($"Vote:Record:{vote.id}");
+                                _azureRedis.GetRedisClient(8).KeyDelete($"Vote:Count:{vote.id}");
                                 break;
                             }
                             await Task.WhenAll(tasks);

+ 13 - 0
TEAMModelOS.SDK/Models/Cosmos/Common/Inner/QuestionRecord.cs

@@ -0,0 +1,13 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace TEAMModelOS.SDK.Models
+{
+    public class QuestionRecord
+    {
+        public int index { get; set; }
+        public Dictionary<string, HashSet<string>> opt { get; set; } = new Dictionary<string, HashSet<string>>();
+        public Dictionary<string, string> other { get; set; } = new Dictionary<string, string>();
+    }
+}

+ 1 - 1
TEAMModelOS.SDK/Models/Cosmos/Common/Inner/VoteRecord.cs

@@ -2,7 +2,7 @@ using System;
 using System.Collections.Generic;
 using System.Text;
 
-namespace TEAMModelOS.SDK.Models.Cosmos.Common.Inner
+namespace TEAMModelOS.SDK.Models
 {
     public class VoteRecord
     {

+ 16 - 7
TEAMModelOS/Controllers/Common/SurveyController.cs

@@ -89,6 +89,7 @@ namespace TEAMModelOS.Controllers
                 if (string.IsNullOrEmpty(request.id))
                 {
                     request.id = Guid.NewGuid().ToString();
+                   
                     if (request.startTime > now)
                     {
                         request.progress = "pending";
@@ -98,31 +99,41 @@ namespace TEAMModelOS.Controllers
                         request.progress = "going";
                     }
                     var messageBlob = new ServiceBusMessage();
+                    string blobcntr = null;
                     if (request.scope.Equals("school"))
                     {
+                        blobcntr = request.school;
                         request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"survey/{request.id}");
                         messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "insert", root = $"survey/{request.id}", name = $"{request.school}" }.ToJsonString());
                     }
                     else
                     {
+                        blobcntr = request.creatorId;
                         request.size = await _azureStorage.GetBlobContainerClient(request.creatorId).GetBlobsSize($"survey/{request.id}");
                         messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "insert", root = $"survey/{request.id}", name = $"{request.creatorId}" }.ToJsonString());
                     }
                     messageBlob.ApplicationProperties.Add("name", "BlobRoot");
                     var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
                     await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
+                    request.recordUrl = $"/survey/{request.id}/record.json";
+                    var cods = new { records = new List<string>(), userids = new List<string>(), question = new List<QuestionRecord>() };
+                    await _azureStorage.UploadFileByContainer(blobcntr, cods.ToJsonString(), "survey", $"{request.id}/record.json");
                     request = await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(request, new PartitionKey($"{request.code}"));
                 }
-                else {
+                else
+                {
+                    string blobcntr = null;
                     var response = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(request.id, new PartitionKey($"{request.code}"));
                     var messageBlob = new ServiceBusMessage();
                     if (request.scope.Equals("school"))
                     {
+                        blobcntr = request.school;
                         request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"survey/{request.id}");
                         messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = $"survey/{request.id}", name = $"{request.school}" }.ToJsonString());
                     }
                     else
                     {
+                        blobcntr = request.creatorId;
                         request.size = await _azureStorage.GetBlobContainerClient(request.creatorId).GetBlobsSize($"survey/{request.id}");
                         messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = $"survey/{request.id}", name = $"{request.creatorId}" }.ToJsonString());
                     }
@@ -157,6 +168,9 @@ namespace TEAMModelOS.Controllers
                         {
                             request.progress = "going";
                         }
+                        request.recordUrl = $"/survey/{request.id}/record.json";
+                        var cods = new { records = new List<string>(), userids = new List<string>(), question = new List<QuestionRecord>() };
+                        await _azureStorage.UploadFileByContainer(blobcntr, cods.ToJsonString(), "survey", $"{request.id}/record.json");
                         request = await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(request, new PartitionKey($"{request.code}"));
                     }
                 }
@@ -535,10 +549,5 @@ namespace TEAMModelOS.Controllers
 
 
     }
-    public class QuestionRecord
-    {
-        public int index { get; set; }
-        public Dictionary<string, HashSet<string>> opt { get; set; } = new Dictionary<string, HashSet<string>>();
-        public Dictionary<string, string> other { get; set; } = new Dictionary<string, string>();
-    }
+  
 }

+ 15 - 24
TEAMModelOS/Controllers/Common/VoteController.cs

@@ -93,35 +93,44 @@ namespace TEAMModelOS.Controllers.Learn
                         request.progress = "pending";
                     }
                     else { 
-                        request.progress = "going"; 
+                        request.progress = "going";
                     }
+                    string blobcntr = null;
                     var messageBlob = new ServiceBusMessage();
                     if (request.scope.Equals("school"))
                     {
+                        blobcntr = request.school;
                         request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"vote/{request.id}");
                         messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "insert", root = $"vote/{request.id}", name = $"{request.school}" }.ToJsonString());                       
                     }
                     else
                     {
+                        blobcntr = request.creatorId;
                         request.size = await _azureStorage.GetBlobContainerClient(request.creatorId).GetBlobsSize($"vote/{request.id}");
                         messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "insert", root = $"vote/{request.id}", name = $"{request.creatorId}" }.ToJsonString());
                     }
                     messageBlob.ApplicationProperties.Add("name", "BlobRoot");
                     var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
                     await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
+                    string url = $"/vote/{request.id}/record.json";
+                    request.recordUrl = url;
+                    await _azureStorage.UploadFileByContainer(blobcntr, new { options = new List<string>(), records = new List<VoteRecord>() }.ToJsonString(), "vote", $"{request.id}/record.json");
                     request = await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(request, new PartitionKey($"{request.code}"));
                 }
                 else
                 {
                     var response = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(request.id, new PartitionKey($"{request.code}"));
                     var messageBlob = new ServiceBusMessage();
+                    string blobcntr = null;
                     if (request.scope.Equals("school"))
                     {
+                        blobcntr = request.school;
                         request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"vote/{request.id}");
                         messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = $"vote/{request.id}", name = $"{request.school}" }.ToJsonString());
                     }
                     else
                     {
+                        blobcntr = request.creatorId;
                         request.size = await _azureStorage.GetBlobContainerClient(request.creatorId).GetBlobsSize($"vote/{request.id}");
                         messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = $"vote/{request.id}", name = $"{request.creatorId}" }.ToJsonString());
                     }
@@ -157,6 +166,9 @@ namespace TEAMModelOS.Controllers.Learn
                         {
                             request.progress = "going";
                         }
+                        string url = $"/vote/{request.id}/record.json";
+                        request.recordUrl = url;
+                        await _azureStorage.UploadFileByContainer(blobcntr, new { options = new List<string>(), records = new List<VoteRecord>() }.ToJsonString(), "vote", $"{request.id}/record.json");
                         request = await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(request, new PartitionKey($"{request.code}"));
                     }
                 }
@@ -267,27 +279,6 @@ namespace TEAMModelOS.Controllers.Learn
                         votes.Add(item);
                     }
                 }
-                //List<object> votes = new List<object>();
-                //var client = _azureCosmos.GetCosmosClient();
-
-                //var query =$"select   c.id,c.name,c.code,c.startTime,c.endTime,c.progress from c where c.createTime >= {stimestamp} and c.createTime <= {etimestamp}  {progresssql } ";
-                //await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query,
-                //    requestOptions: new QueryRequestOptions() {MaxItemCount = topcout, PartitionKey = new PartitionKey($"Vote-{code}") }))
-                //{
-                //    using var json = await JsonDocument.ParseAsync(item.ContentStream);
-                //    if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
-                //    {
-                //        foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
-                //        {
-                //            votes.Add(obj.ToObject<JsonElement>());
-                //        }
-                //        //如果需要分页则跳出
-                //        if (iscontinuation) {
-                //            continuationToken = item.GetContinuationToken();
-                //            break;
-                //        }
-                //    }
-                //}
                 return Ok(new { votes, continuationToken });
             }
             catch (Exception ex)
@@ -501,7 +492,7 @@ namespace TEAMModelOS.Controllers.Learn
         public async Task<IActionResult> Decide(JsonElement request)
         {
             var (userid, _, _, _) = HttpContext.GetAuthTokenInfo();
-            int msgid = await ActivityStudentService.Decide(request, _azureCosmos, _azureRedis, userid);
+            int msgid = await ActivityStudentService.Decide(request, _azureCosmos, _azureRedis ,_azureStorage, userid);
             return Ok(new { msgid });
         }
         /// <summary>
@@ -528,7 +519,7 @@ namespace TEAMModelOS.Controllers.Learn
             //活动id
             if (request.TryGetProperty("userid", out JsonElement userid))
             {
-                int msgid = await ActivityStudentService.Decide(request, _azureCosmos, _azureRedis, $"{userid}");
+                int msgid = await ActivityStudentService.Decide(request, _azureCosmos, _azureRedis, _azureStorage, $"{userid}");
                 return Ok(new { msgid });
             }
             else { return Ok(new { msgid = 0 }); }

+ 124 - 10
TEAMModelOS/Services/Common/ActivityStudentService.cs

@@ -13,6 +13,7 @@ using TEAMModelOS.SDK.Models;
 using TEAMModelOS.SDK.Models.Cosmos.Common.Inner;
 using StackExchange.Redis;
 using TEAMModelOS.SDK.Models.Cosmos.Common;
+using TEAMModelOS.Controllers;
 
 namespace TEAMModelOS.Services.Common
 {
@@ -20,8 +21,8 @@ namespace TEAMModelOS.Services.Common
     {
 
        
-        public static async Task<int> Decide(JsonElement request,AzureCosmosFactory _azureCosmos,AzureRedisFactory _azureRedis,string userid ) {
-
+        public static async Task<int> Decide(JsonElement request,AzureCosmosFactory _azureCosmos,AzureRedisFactory _azureRedis , AzureStorageFactory _azureStorage, string userid ) {
+            Vote vote = null;
             DateTimeOffset now = DateTimeOffset.UtcNow;
             long curr = now.ToUnixTimeMilliseconds();
             byte msgid = 0;//0投票失败,1投票成功,2不在时间范围内,3不在发布范围内,4投票周期内重复投票,5周期内的可投票数不足,6未设置投票项
@@ -52,9 +53,8 @@ namespace TEAMModelOS.Services.Common
             {
                 //1.再次检查投票
                 var client = _azureCosmos.GetCosmosClient();
-                Vote vote = null;
                 ///TODO 检查是否在投票范围内,包括在tmdids 及班级  但是需要处理认证金钥中的班级问题
-                await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<Vote>(queryText: $"select c.id,c.code , c.progress,c.times,c.voteNum,c.startTime,c.endTime from c where c.id = '{id}'",
+                await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<Vote>(queryText: $"select c.id,c.code ,c.school,c.creatorId,c.scope , c.progress,c.times,c.voteNum,c.startTime,c.endTime from c where c.id = '{id}'",
                     requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{code}") }))
                 {
                     vote = item;
@@ -121,11 +121,50 @@ namespace TEAMModelOS.Services.Common
             {
                 throw new Exception(e.StackTrace);
             }
+            if (msgid == 1 && vote!= null) 
+            {
+                string blobcntr = null;
+                if (vote.scope.Equals("school"))
+                {
+                    blobcntr = vote.school;
+                }
+                else
+                {
+                    blobcntr = vote.creatorId;
+                }
+                //获取投票活动的所有投票记录
+                var records = await _azureRedis.GetRedisClient(8).HashGetAllAsync($"Vote:Record:{vote.id}");
+                //获取投票活动的选项及投票数
+                var counts = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Vote:Count:{vote.id}");
+                List<dynamic> countcds = new List<dynamic>();
+                if (counts != null && counts.Length > 0)
+                {
+                    foreach (var count in counts)
+                    {
+                        countcds.Add(new { code = count.Element.ToString(), count = (int)count.Score });
+                    }
+                }
+                List<Task<string>> tasks = new List<Task<string>>();
+                List<VoteRecord> recordsBlob = new List<VoteRecord>();
+                foreach (var rcd in records)
+                {
+                    var value = rcd.Value.ToString().ToObject<VoteRecord>();
+                    recordsBlob.Add(value);
+                }
+                //分组每个人的 
+                var gp = recordsBlob.GroupBy(x => x.userid).Select(x => new { key = x.Key, list = x.ToList() });
+                var userdata = gp.Where(x => x.key.Equals(userid)).FirstOrDefault();
+                if(userdata!=null)
+                {
+                    tasks.Add(_azureStorage.UploadFileByContainer(blobcntr, userdata.list.ToJsonString(), "vote", $"{vote.id}/urecord/{userdata.key}.json"));
+                }
+                //处理活动方的记录, 
+                string url = $"/vote/{vote.id}/record.json";
+                tasks.Add(_azureStorage.UploadFileByContainer(blobcntr, new { options = countcds, records = recordsBlob }.ToJsonString(), "vote", $"{vote.id}/record.json"));
+            }
             return msgid;
         }
 
-      
-
         public static async Task<byte> VoteIng(Vote vote, RedisValue value, byte msgid, Dictionary<string, int> option, string Field, long curr, AzureRedisFactory _azureRedis,string userid,string times,string endpoint)
         {
             if (!value.IsNullOrEmpty)
@@ -396,9 +435,9 @@ namespace TEAMModelOS.Services.Common
                     //判断投票时间是否在起止时间内
                     if (curr >= survey.startTime && curr <= survey.endTime)
                     {
-                        if (request.TryGetProperty("record", out JsonElement record)) 
+                        if (request.TryGetProperty("record", out JsonElement _record)) 
                         {
-                            var recs = record.ToObject<List<List<string>>>();
+                            var recs = _record.ToObject<List<List<string>>>();
                             if (recs.IsNotEmpty() && recs.Count == survey.answers.Count)
                             {
                                 //处理问卷调查表的每一题选项数
@@ -462,12 +501,88 @@ namespace TEAMModelOS.Services.Common
                                 {
                                     blobcntr = survey.school;
                                 }
-                                else if (survey.scope .Equals("private"))
+                                else  
                                 {
                                     blobcntr = survey.creatorId;
                                 }
                                 await _azureStorage.UploadFileByContainer(blobcntr, new SurveyRecord { ans= recs, userid=userid, time = curr }.ToJsonString(), "survey", $"{survey.id}/urecord/{userid}.json");
+                                ///bgn 20210805 huanghb 实时结算
                                 await azureRedis.GetRedisClient(8).SetAddAsync($"Survey:Submit:{survey.id}", userid);
+
+                                var submits = await azureRedis.GetRedisClient(8).SetMembersAsync($"Survey:Submit:{survey.id}");
+                                List<dynamic> userids = new List<dynamic>();
+                                foreach (var submit in submits)
+                                {
+                                    var value = submit.ToString();
+                                    userids.Add(value);
+                                }
+                                List<QuestionRecord> questionRecords = new List<QuestionRecord>();
+                                //结算每道题的答题情况
+                                var ContainerClient = _azureStorage.GetBlobContainerClient(blobcntr);
+                                List<Task<string>> tasks = new List<Task<string>>();
+                                List<string> items = await ContainerClient.List($"survey/{survey.id}/urecord");
+                                List<SurveyRecord> surveyRecords = new List<SurveyRecord>();
+                                foreach (string item in items)
+                                {
+                                    var Download = await _azureStorage.GetBlobContainerClient(blobcntr).GetBlobClient(item).DownloadAsync();
+                                    var json = await JsonDocument.ParseAsync(Download.Value.Content);
+                                    var Record = json.RootElement.ToObject<SurveyRecord>();
+                                    surveyRecords.Add(Record);
+                                }
+                                for (int index = 0; index < survey.answers.Count; index++)
+                                {
+                                    string url = $"{survey.id}/qrecord/{index}.json";
+                                    QuestionRecord question = new QuestionRecord() { index = index };
+                                    foreach (SurveyRecord record in surveyRecords)
+                                    {
+                                        if (record.ans.Count == survey.answers.Count)
+                                        {
+                                            foreach (var an in record.ans[index])
+                                            {
+                                                //
+                                                if (question.opt.ContainsKey(an))
+                                                {
+                                                    if (question.opt[an] != null)
+                                                    {
+                                                        question.opt[an].Add(record.userid);
+                                                    }
+                                                    else
+                                                    {
+                                                        question.opt[an] = new HashSet<string>() { record.userid };
+                                                    }
+                                                }
+                                                else
+                                                {
+                                                    if (survey.answers[index].Contains(an))
+                                                    {
+                                                        //如果是客观题code
+                                                        question.opt.Add(an, new HashSet<string> { record.userid });
+                                                    }
+                                                    else
+                                                    {
+                                                        //如果不是客观code
+                                                        question.other[record.userid] = an;
+                                                    }
+                                                }
+                                            }
+                                        }
+                                    }
+                                    questionRecords.Add(question);
+                                    tasks.Add(_azureStorage.UploadFileByContainer(blobcntr, question.ToJsonString(), "survey", url));
+                                }
+                                var records = await azureRedis.GetRedisClient(8).HashGetAllAsync($"Survey:Record:{survey.id}");
+                                List<dynamic> recds = new List<dynamic>();
+                                foreach (var rcd in records)
+                                {
+                                    var value = rcd.Value.ToString().ToObject<JsonElement>();
+                                    recds.Add(new { index = rcd.Name.ToString(), ans = value });
+                                }
+                                await Task.WhenAll(tasks);
+                                var cods = new { records = recds, userids, question = questionRecords };
+                                //问卷整体情况
+                                await _azureStorage.UploadFileByContainer(blobcntr, cods.ToJsonString(), "survey", $"{survey.id}/record.json");
+                                ///end 20210805 huanghb 实时结算
+
                                 msgid = 1;
                             }
                             else {
@@ -475,7 +590,6 @@ namespace TEAMModelOS.Services.Common
                                 msgid = 3;
                             }
                         }
-                        
                     }
                     else
                     {