CrazyIter_Bin 4 лет назад
Родитель
Сommit
4a23034404

+ 14 - 9
TEAMModelFunction/TriggerSurvey.cs

@@ -19,10 +19,12 @@ namespace TEAMModelFunction
                CosmosClient client, Document input, string code, long stime, long etime, string school)
         {
             Survey survey = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Survey>(input.Id, new Azure.Cosmos.PartitionKey($"{code}"));
-            //messageSurvey.ScheduledEnqueueTime = DateTimeOffset.FromUnixTimeMilliseconds(stime);
-            //string msgid = messageSurvey.MessageId;
             List<ChangeRecord> changeRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", survey.progress } });
-            //ChangeRecord surveyRecord = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ChangeRecord>(input.Id, new Azure.Cosmos.PartitionKey($"{survey.progress}"));
+            if (survey.ttl >= 1)
+            {
+                //TODO  处理TTL删除业务
+                return;
+            }
             switch (survey.progress)
             {
                 case "pending":
@@ -34,7 +36,6 @@ namespace TEAMModelFunction
                         long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageSurvey, DateTimeOffset.FromUnixTimeMilliseconds(stime));
                         changeRecords[0].sequenceNumber = start;
                         await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
-                        //await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(surveyRecord, surveyRecord.id, new Azure.Cosmos.PartitionKey($"{surveyRecord.code}"));
                     }
                     else
                     {
@@ -47,18 +48,16 @@ namespace TEAMModelFunction
                             msgId = messageSurvey.MessageId
                         };
                         await _azureStorage.Save<ChangeRecord>(changeRecord);
-                        //await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
                     }
                     break;
                 case "going":
-                    var tcode = code.Replace("Survey-", "");
                     ActivityData data;
                     if (survey.scope == "school" || survey.scope == "teacher")
                     {
                         data = new ActivityData
                         {
                             id = survey.id,
-                            code = $"Activity-{tcode}",
+                            code = $"Activity-{survey.owner}",
                             type = "survey",
                             name = survey.name,
                             startTime = survey.startTime,
@@ -66,7 +65,9 @@ namespace TEAMModelFunction
                             scode = survey.code,
                             scope = survey.scope,
                             classes = survey.classes,
-                            tmdids = survey.tmdids
+                            tmdids = survey.tmdids,
+                            progress = "going",
+                            owner = survey.owner
                         };
                         await client.GetContainer("TEAMModelOS", "School").UpsertItemAsync<ActivityData>(data, new Azure.Cosmos.PartitionKey(data.code));
                     }
@@ -83,7 +84,8 @@ namespace TEAMModelFunction
                             scode = survey.code,
                             scope = survey.scope,
                             classes = survey.classes,
-                            // tmdids = survey.tmdids
+                            progress = "going",
+                            owner = survey.owner
                         };
                         await client.GetContainer("TEAMModelOS", "Teacher").UpsertItemAsync<ActivityData>(data, new Azure.Cosmos.PartitionKey(data.code));
                     }
@@ -108,6 +110,9 @@ namespace TEAMModelFunction
                         };
                         await _azureStorage.Save<ChangeRecord>(changeRecord);
                     }
+                    break;
+                case "finish":
+
                     break;
             }
         }

+ 0 - 1
TEAMModelFunction/TriggerVote.cs

@@ -21,7 +21,6 @@ namespace TEAMModelFunction
         {
             Vote vote = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Vote>(input.Id, new Azure.Cosmos.PartitionKey($"{code}"));
             List<ChangeRecord> voteRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", vote.progress } });
-            //ChangeRecord voteRecord = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ChangeRecord>(input.Id, new Azure.Cosmos.PartitionKey($"{vote.progress}"));
             if (vote.ttl >= 1)
             {
                 //TODO  处理TTL删除业务

+ 8 - 0
TEAMModelOS.SDK/Models/Cosmos/Common/ActivityData.cs

@@ -42,9 +42,16 @@ namespace TEAMModelOS.SDK.Models.Cosmos
     //        "tmdids":[]
     //    }
     //]
+    ///简单阐述说明:
+    /// 1. 对于学校产生的活动 即scope=school  或scope=teacher  则对应活动原本的数据的owner 则直接为学校的编码,且ActivityData的code为Activity+学校编码 ActivityData数据存在School表
+    ///    如果scope=private,则活动是老师个人活动,owner=tmdid  ,ActivityData 数据存在Teacher表
+    /// 2. 学生端查询包含 tmdid登录者(可能包含加入学校的教师)以学生身份登入学生端,则需要知道 登录人加入的私人教室id  则输入条件是classes=['私人教室id'],
+    ///    
+    /// 
     /// </summary>
     public class ActivityData : CosmosEntity
     {
+       
         public ActivityData() {
             pk = "Activity";
         }
@@ -70,5 +77,6 @@ namespace TEAMModelOS.SDK.Models.Cosmos
         public List<string> classes { get; set; }
         public List<string> tmdids { get; set; }
         public string owner { get; set; }
+        public List<string> subjects { get; set; }
     }
 }

+ 1 - 1
TEAMModelOS.SDK/Models/Cosmos/Common/Vote.cs

@@ -21,7 +21,7 @@ namespace TEAMModelOS.SDK.Models
 
         }
         /// <summary>
-        /// 学校编码或教tmdid
+        /// 学校编码或教tmdid
         /// </summary>
         [Required(ErrorMessage = "owner 必须设置")]
         public string owner { get; set; }

+ 153 - 378
TEAMModelOS/Controllers/Common/SurveyController.cs

@@ -15,6 +15,9 @@ using TEAMModelOS.SDK.DI;
 using TEAMModelOS.SDK.DI.AzureCosmos.Inner;
 using TEAMModelOS.SDK.Extension;
 using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
+using TEAMModelOS.Models;
+using Microsoft.Extensions.Options;
+using TEAMModelOS.Filter;
 
 namespace TEAMModelOS.Controllers
 {
@@ -31,14 +34,18 @@ namespace TEAMModelOS.Controllers
         private readonly AzureCosmosFactory _azureCosmos;
         private readonly SnowflakeId _snowflakeId;
         private readonly AzureServiceBusFactory _serviceBus;
-        public SurveyController(AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId)
+        private readonly DingDing _dingDing;
+        private readonly Option _option;
+        public SurveyController(AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing, IOptionsSnapshot<Option> option)
         {
             _snowflakeId= snowflakeId;
-            //  _timerWorkService = timerWorkService;
             _serviceBus = serviceBus;
-              _azureCosmos = azureCosmos;
+            _azureCosmos = azureCosmos;
+            _dingDing = dingDing;
+            _option = option?.Value;
         }
 
+
         /// <summary>
         /// 新增 或 修改投票活动
         /// </summary>
@@ -46,449 +53,217 @@ namespace TEAMModelOS.Controllers
         /// <returns></returns>
         [ProducesDefaultResponseType]
         [HttpPost("upsert")]
-        public async Task<IActionResult> Upsert(SurveyDto request)
-        {
-            //ResponseBuilder builder = ResponseBuilder.custom();
-            //新增
-            //string code = request.survey.code;
-            var client = _azureCosmos.GetCosmosClient();
-            Survey survey;            
-            //request.survey.school = request.survey.code;
-            request.survey.code =  "Survey-" + request.survey.code;
-            request.survey.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
-            /*if (request.survey.publishModel.Equals("0"))
-            {
-                //request.survey.startTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
-                request.survey.progress = "going";
-            }
-            else if (request.survey.publishModel.Equals("1"))
-            {
-
-                string msgId = _snowflakeId.NextId() + "";
-                long SequenceNumber = await _serviceBus.GetServiceBusClient().SendLeamMessage<Survey>(Constants.TopicName, request.survey.id, request.survey.code, request.survey.startTime, "going", msgId);
-                request.survey.sequenceNumber = SequenceNumber;
-
-            }*/
-            if (string.IsNullOrEmpty(request.survey.id))
-            {
-                request.survey.id = Guid.NewGuid().ToString();
-                //request.survey.status = 100;
-                request.survey.progress = "pending";
-                //await _serviceBus.GetServiceBusClient().cancelMessage(Constants.TopicName, info.sequenceNumber);
-               /* long SequenceNumber = await _serviceBus.GetServiceBusClient().SendLeamMessage<Survey>(Constants.TopicName, request.survey.id, request.survey.code, request.survey.startTime);
-                request.survey.sequenceNumber = SequenceNumber;*/
-                survey = await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(request.survey, new PartitionKey($"{request.survey.code}"));
-                /*if (request.survey.scope.Equals("school"))
-                {
-                    survey = await client.GetContainer("TEAMModelOS", "School").CreateItemAsync(request.survey, new PartitionKey($"Survey-{code}"));
-                }
-                else
-                {
-                    survey = await client.GetContainer("TEAMModelOS", "Teacher").CreateItemAsync(request.survey, new PartitionKey($"Survey-{code}"));
-                }*/
-                //await _serviceBus.GetServiceBusClient().SendLeamMessage<Survey>(Constants.TopicName, request.id, request.code, request.startTime);
-
-            }
-            else {
-                Survey info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Survey>(request.survey.id, new PartitionKey($"{request.survey.code}"));
-                if (info.progress.Equals("going"))
-                {
-                    return Ok(new { v = "活动正在进行中" });
-                }
-                //request.survey.code = info.code;
-                request.survey.progress = info.progress;
-                /*try {
-                    await _serviceBus.GetServiceBusClient().cancelMessage(Constants.TopicName, info.sequenceNumber);
-                    long SequenceNumber = await _serviceBus.GetServiceBusClient().SendLeamMessage<Survey>(Constants.TopicName, request.survey.id, request.survey.code, request.survey.startTime);
-                    request.survey.sequenceNumber = SequenceNumber;
-                } catch (Exception e) {
-                    return BadRequest();
-                    //await _dingDing.SendBotMsg($"ServiceBusㄛExamBus()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
-                }        */       
-                
-                survey = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(request.survey, info.id, new PartitionKey($"{info.code}"));
-                //request.survey.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
-                /*if (request.survey.scope.Equals("school"))
+        public async Task<IActionResult> Upsert(Survey request) {
+            try {
+                var client = _azureCosmos.GetCosmosClient();
+                request.code = request.pk + "-" + request.code;
+                request.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
+                if (string.IsNullOrEmpty(request.id))
                 {
-                    survey = await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(request.survey, request.survey.id, new PartitionKey($"{request.survey.code}"));
+                    request.id = Guid.NewGuid().ToString();
+                    request.progress = "pending";
+                    request = await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(request, new PartitionKey($"{request.code}"));
                 }
-                else
-                {
-                    survey = await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(request.survey, request.survey.id, new PartitionKey($"{request.survey.code}"));
-                }*/
-
-
-            }            
-            //Survey homeWork = await _azureCosmos.SaveOrUpdate<Survey>(request.survey);
-
-            //设定结束时间
-            //await _serviceBus.GetServiceBusClient().SendLeamMessage<Survey>(Constants.TopicName, request.survey.id, request.survey.code, request.survey.endTime);
-
-            //清除作业
-            /*if (!request.reset)
-            {
-                //查询之前是否有 关联关系表 HomeWorkStudent 有则删除
-                List<SurveyRecord> surveyRecords = await _azureCosmos.FindByDict<SurveyRecord>(new Dictionary<string, object> { { "id", request.survey.id } });
-                if (surveyRecords.IsNotEmpty())
-                {
-                    await _azureCosmos.DeleteAll(surveyRecords);
+                else {
+                    Survey info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Survey>(request.id, new PartitionKey($"{request.code}"));
+                    if (info.progress.Equals("going"))
+                    {
+                        return Ok(new { v = "活动正在进行中" });
+                    }
+                    request.progress = info.progress;
+                    request = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(request, info.id, new PartitionKey($"{info.code}"));
                 }
-
-                ////根据作业发布对象查找到每一个具体学生生成关联关系表 HomeWorkStudent
-                //List<Target> targets = request.@params.survey.target;
-                //List<SurveyRecord> surveykStudents = new List<SurveyRecord>();
-                //foreach (Target target in targets)
-                //{
-                   
-                //    List<ClassStudent> classroom = await azureCosmosDBV3Repository.FindByDict<ClassStudent>(new Dictionary<string, object> { { "id", target.classroomCode } });
-                //    if (classroom.IsNotEmpty() && classroom[0].code != null)
-                //    {
-                //        foreach (ClassStudent student in classroom)
-                //        {
-                //            SurveyRecord surveyStudent = new SurveyRecord();
-                //            surveyStudent.id = request.@params.survey.id;
-                //            surveyStudent.code = student.code;
-                //            surveyStudent.classroom.code = target.classroomCode;
-                //            surveyStudent.classroom.name = target.classroomName;
-                //            surveykStudents.Add(surveyStudent);
-                //        }
-                //    }
-                //}
-                //if (surveykStudents.IsNotEmpty())
-                //{
-                //    foreach (SurveyRecord surveyRecord in surveykStudents)
-                //    {
-                //        List<Student> student = await azureCosmosDBV3Repository.FindById<Student>(surveyRecord.code);
-                //        if (student.IsNotEmpty())
-                //        {
-                //            surveyRecord.name = student[0].name;
-                //            surveyRecord.code = student[0].TEAMModelId;
-                //        }
-                //    }
-                //    await azureCosmosDBV3Repository.SaveOrUpdateAll(surveykStudents);
-                //}
-            }*/
-            //return builder.Data(homeWork).build();
-            return Ok(survey);
+                return Ok(new { survey = request});
+            } catch (Exception ex) {
+                await _dingDing.SendBotMsg($"OS,{_option.Location},common/survey/save()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
+                return BadRequest(ex.StackTrace);
+            }
+           
         }
         /// <summary>
-        /// 查询投票活动
+        /// 查询问卷调查,用于列表,编辑,查看
         /// </summary>
+        /// <data>
+        ///Survey-学校/教师编码  活动分区        !"code":"hbcn"/1606285227 
+        ///时间筛选范围开始时间 默认30天之前   ?"stime":1608274766154  
+        ///时间筛选范围结束时间 默认当前时间   ?"etime":1608274766666 
+        ///每页大小     ?"count":10/null/Undefined  
+        ///分页Token    ?"continuationToken":Undefined/null/"[{\"token\":\"+RID:~omxMAP3ipcSEEwAAAAAAAA==#RT:2#TRC:20#ISV:2#IEO:65551#QCF:1#FPC:AYQTAAAAAAAAiRMAAAAAAAA=\",\"range\":{\"min\":\"\",\"max\":\"FF\"}}]"
+        /// 当前状态    ?"progress":Undefined/null/"" 表示两种状态都要查询/ "going"/"finish" 表示查询进行中/ 或者已完成 学生端只能查询正在进行或已经结束 going 已发布|finish 已结束  
+        /// </data>
         /// <param name="request"></param>
         /// <returns></returns>
         [ProducesDefaultResponseType]
-        [HttpPost("find-summary")]
-        public async Task<IActionResult> FindSummary(JsonElement requert)
+        [HttpPost("find")]
+        public async Task<IActionResult> Find(JsonElement requert)
         {
-
-            var client = _azureCosmos.GetCosmosClient();
-            if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
-            if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
-            //var (id, name, picture, _) = HttpContext.GetAuthTokenInfo();
-            List<object> surveys = new List<object>();
-            StringBuilder sql = new StringBuilder();
-            sql.Append("select c.id,c.code,c.name,c.startTime,c.endTime,c.description,c.progress from c ");
-            Dictionary<string, object> dict = new Dictionary<string, object>();
-            var emobj = requert.EnumerateObject();
-            while (emobj.MoveNext())
-            {
-                dict[emobj.Current.Name] = emobj.Current.Value;
-            }
-            //处理code
-            if (dict.TryGetValue("code", out object _))
-            {
-                dict.Remove("code");
-            }
-            AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
-            await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Survey-{code}") }))
-            {
-                using var json = await JsonDocument.ParseAsync(item.ContentStream);
-
-                if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
+            try {
+                //必须有学校或者教师编码
+                if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
+                //开始时间,默认最近三十天
+                var stimestamp = DateTimeOffset.UtcNow.AddDays(-30).ToUnixTimeMilliseconds();
+                if (requert.TryGetProperty("stime", out JsonElement stime))
                 {
-                    foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
+                    if (!stime.ValueKind.Equals(JsonValueKind.Undefined) && stime.TryGetInt64(out long data))
                     {
-                        surveys.Add(obj.ToObject<object>());
-                    }
-                }
-            }
-            /*if (scope.ToString().Equals("school"))
-            {
-                await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Survey-{code}") }))
+                        stimestamp = data;
+                    };
+                };
+                //默认当前时间
+                var etimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
+                if (requert.TryGetProperty("etime", out JsonElement etime))
                 {
-                    using var json = await JsonDocument.ParseAsync(item.ContentStream);
-
-                    if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
+                    if (!etime.ValueKind.Equals(JsonValueKind.Undefined) && etime.TryGetInt64(out long data))
                     {
-                        foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
-                        {
-                            surveys.Add(obj.ToObject<object>());
-                        }
-                    }
-                }
-            }
-            else
-            {
-                await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Survey-{code}") }))
+                        etimestamp = data;
+                    };
+
+                };
+                var progresssql = "";
+                if (!requert.TryGetProperty("progress", out JsonElement progress))
                 {
-                    using var json = await JsonDocument.ParseAsync(item.ContentStream);
 
-                    if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
+                    if (!progress.ValueKind.Equals(JsonValueKind.Undefined) && !progress.ValueKind.Equals(JsonValueKind.Null) && progress.ValueKind.Equals(JsonValueKind.String))
                     {
-                        foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
-                        {
-                            surveys.Add(obj.ToObject<object>());
-                        }
+                        progresssql = $" and c.progress='{progresssql}' ";
                     }
                 }
-            }*/
-
-            return Ok(new { surveys, surveys.Count });
-            /*ResponseBuilder builder = ResponseBuilder.custom();
-            Dictionary<string, object> dict = new Dictionary<string, object>();
-            var emobj = request.EnumerateObject();
-            while (emobj.MoveNext())
-            {
-                dict[emobj.Current.Name] = emobj.Current.Value;
-            }
-            List<Survey> data = new List<Survey>();
-            List<string> props = new List<string> { "id", "code", "name", "type", "status", "startTime" };
-            if (dict.Keys.Count > 0)
-            { 
-                
-                data = await _azureCosmos.FindByDict<Survey>(dict, props);
-            }
-            else
-            {
-                return builder.Error(ResponseCode.PARAMS_ERROR, "参数异常!").build();
-
-            }
-            return builder.Data(data).Extend(new Dictionary<string, object> { { "count", data.Count },{ "props", props } }).build();*/
-        }
-        /// <summary>
-        /// 查询投票活动
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        [HttpPost("find")]
-        public async Task<IActionResult> Find(JsonElement requert)
-        {
-            var client = _azureCosmos.GetCosmosClient();
-            if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
-            if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
-            //var (id, name, picture, _) = HttpContext.GetAuthTokenInfo();
-            List<object> surveys = new List<object>();
-            StringBuilder sql = new StringBuilder();
-            sql.Append("select c.id,c.code,c.name,c.questions,c.classes,c.startTime,c.endTime,c.description,c.progress,c.targetClassIds from c ");
-            Dictionary<string, object> dict = new Dictionary<string, object>();
-            var emobj = requert.EnumerateObject();
-            while (emobj.MoveNext())
-            {
-                dict[emobj.Current.Name] = emobj.Current.Value;
-            }
-            //处理code
-            if (dict.TryGetValue("code", out object _))
-            {
-                dict.Remove("code");
-            }
-            AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
-            await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Survey-{code}") }))
-            {
-                using var json = await JsonDocument.ParseAsync(item.ContentStream);
-
-                if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
+                string continuationToken = null;
+                //默认不指定返回大小
+                int? topcout = null;
+                if (requert.TryGetProperty("count", out JsonElement jcount))
                 {
-                    foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
+                    if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && jcount.TryGetInt32(out int data))
                     {
-                        surveys.Add(obj.ToObject<object>());
+                        topcout = data;
                     }
-                }
-            }
-            /*if (scope.ToString().Equals("school"))
-            {
-                await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Survey-{code}") }))
+                };
+                //是否需要进行分页查询,默认不分页
+                bool iscontinuation = false;
+                //如果指定了返回大小
+                if (requert.TryGetProperty("continuationToken", out JsonElement continuation))
                 {
-                    using var json = await JsonDocument.ParseAsync(item.ContentStream);
-
-                    if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
+                    //指定了cancellationToken 表示需要进行分页
+                    if (!continuation.ValueKind.Equals(JsonValueKind.Null) && !continuation.ValueKind.Equals(JsonValueKind.Undefined))
                     {
-                        foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
-                        {
-                            surveys.Add(obj.ToObject<object>());
-                        }
+                        continuationToken = continuation.GetString();
+                        iscontinuation = true;
                     }
-                }
-            }
-            else {
-                await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Survey-{code}") }))
+                };
+                List<object> surveys = 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())
                         {
-                            surveys.Add(obj.ToObject<object>());
+                            surveys.Add(obj.ToObject<JsonElement>());
+                        }
+                        //如果需要分页则跳出
+                        if (iscontinuation)
+                        {
+                            continuationToken = item.GetContinuationToken();
+                            break;
                         }
                     }
                 }
-            }*/
-
-
-            return Ok(new { surveys, surveys.Count });
-            /*ResponseBuilder builder = ResponseBuilder.custom();
-            Dictionary<string, object> dict = new Dictionary<string, object>();
-            var emobj = request.EnumerateObject();
-            while (emobj.MoveNext())
-            {
-                dict[emobj.Current.Name] = emobj.Current.Value;
-            }
-            List<Survey> data = new List<Survey>();
-            if (dict.Keys.Count > 0)
-            {
-                data = await _azureCosmos.FindByDict<Survey>(dict);
+                return Ok(new { surveys, continuationToken });
+            } catch (Exception ex) {
+                await _dingDing.SendBotMsg($"OS,{_option.Location},common/survey/find()\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
+                return BadRequest(ex.StackTrace);
             }
-            else
-            {
-                return builder.Error(ResponseCode.PARAMS_ERROR, "参数异常!").build();
-
-            }
-            return builder.Data(data).Extend(new Dictionary<string, object> { { "count", data.Count } }).build();*/
+          
         }
-
-        /// <summary>
-        /// 删除投票活动
+        ///<summary>
+        /// 查询问卷调查,用于创建者列表,编辑,查看,作答人员查看
         /// </summary>
+        /// <data>
+        ///    ! "id":"3c075347-75ef-4bcb-ae03-68678d02d5ef",
+        ///    ! "code":"Survey-hbcn"/"code":"Survey-1606285227"
+        /// </data>
         /// <param name="request"></param>
         /// <returns></returns>
         [ProducesDefaultResponseType]
-        [HttpPost("delete")]
-        public async Task<IActionResult> Delete(JsonElement request)
+        [HttpPost("find-id")]
+        public async Task<IActionResult> FindById(JsonElement requert)
         {
             try
             {
-                if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
-                if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
-                if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
                 var client = _azureCosmos.GetCosmosClient();
-                var response = await client.GetContainer("TEAMModelOS", "Common").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"{code}"));
-                return Ok(new { code = response.Status });
-                /*if (scope.ToString().Equals("school"))
+                //活动id
+                if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
+                //活动分区
+                if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
+                Survey survey = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Survey>(id.GetString(), new PartitionKey($"{code}"));
+                if (survey != null)
                 {
-                    var response = await client.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"{code}"));
-                    return Ok(new { code = response.Status });
+
+                    return Ok(new { survey });
                 }
                 else
                 {
-                    var response = await client.GetContainer("TEAMModelOS", "Teacher").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"{code}"));
-                    return Ok(new { code = response.Status });
-                }*/
-
+                    return BadRequest("id,code不存在!");
+                }
             }
-            catch
+            catch (Exception ex)
             {
-                return BadRequest();
+                await _dingDing.SendBotMsg($"OS,{_option.Location},common/survey/find-id()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
+                return BadRequest(ex.StackTrace);
             }
-            /* ResponseBuilder builder = ResponseBuilder.custom();
-             List<IdPk> idPks = await _azureCosmos.DeleteAll<Survey>(request);
-             if (idPks.IsNotEmpty())
-             {
-                 foreach (IdPk idPk in idPks)
-                 {
-                     List<SurveyRecord> surveys = await _azureCosmos.FindByDict<SurveyRecord>(new Dictionary<string, object> { { "id", idPk.id } });
-                     await _azureCosmos.DeleteAll(surveys);
-                 }
-                 //builder.Data(idPks);
-             }
-             else
-             {
-                 return Ok("删除失败!");
-                 //return builder.Error(ResponseCode.FAILED, "删除失败!").build();
-             }
-             return Ok(idPks);*/
-            //return builder.build();
-        }
-
-        // TODO 代码优化
-
-        /// <summary>
-        /// 撤消问卷
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        [HttpPost("cancel")]
-        public async Task<IActionResult> Cancel(JsonElement request)
-        {
-            //request.TryGetProperty("id", out JsonElement surveyId);
-            //ResponseBuilder builder = ResponseBuilder.custom();
-            //List<Survey> surveys = await _azureCosmos.FindByDict<Survey>(new Dictionary<string, object> { { "id", surveyId } });
-
-            //foreach (Survey survey in surveys)
-            //{
-            //    survey.status = 100;
-            //    survey.progress = "pending";
-            //}
-            //List<Survey> survey1 = await _azureCosmos.UpdateAll<Survey>(surveys);
 
-            ////查询之前是否有 关联关系表  有则删除
-            //List<SurveyRecord> surveyStudents = await _azureCosmos.FindByDict<SurveyRecord>(new Dictionary<string, object> { { "id", surveyId } });
-            //if (surveyStudents.IsNotEmpty())
-            //{
-            //    await _azureCosmos.DeleteAll(surveyStudents);
-            //}
-            return Ok();
         }
 
         /// <summary>
-        /// 查询学生问卷调查记录
+        /// 删除问卷调查   TODO 使用ttl删除,并处理相关事务逻辑
         /// </summary>
         /// <param name="request"></param>
         /// <returns></returns>
         [ProducesDefaultResponseType]
-        [HttpPost("find-record")]
-        public async Task<IActionResult> FindRecord(JsonElement requert)
+        [HttpPost("delete")]
+        [AuthToken(Roles = "admin,teacher")]
+        public async Task<IActionResult> Delete(JsonElement request)
         {
-            var client = _azureCosmos.GetCosmosClient();
-            if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
-            //var (id, name, picture, _) = HttpContext.GetAuthTokenInfo();
-
-            List<object> surveys = new List<object>();
-            var query = $"select c.id,c.code,c.name,c.type,c.status,c.startTime from c where {id}";
-            await foreach (var item in client.GetContainer("TEAMModelOS", "Student").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"SurveyRecord-{id}") }))
+            try
             {
-                using var json = await JsonDocument.ParseAsync(item.ContentStream);
+                var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
+                if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
+                if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
+                var client = _azureCosmos.GetCosmosClient();
 
-                if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
+                Survey survey = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Survey>(id.GetString(), new PartitionKey($"{code}"));
+                bool flag = false;
+                //必须是本人或者这个学校的管理者才能删除
+                if (survey.creatorId == userid)
                 {
-                    foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
+                    flag = true;
+                }
+                else
+                {
+                    if (survey.scope == "school" && survey.owner.Equals(school))
                     {
-                        surveys.Add(obj.ToObject<object>());
+                        flag = true;
                     }
                 }
+                if (flag)
+                {
+                    //使用ttl删除,并处理相关事务逻辑
+                    survey.ttl = 1;
+                    survey = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(survey, survey.id, new PartitionKey($"{survey.code}"));
+                    return Ok(new { flag });
+                }
+                else
+                {
+                    return Ok(new { flag });
+                }
             }
-
-            return Ok(new { surveys, surveys.Count });
-            /*ResponseBuilder builder = ResponseBuilder.custom();
-            Dictionary<string, object> dict = new Dictionary<string, object>();
-            var emobj = request.EnumerateObject();
-            while (emobj.MoveNext())
-            {
-                dict[emobj.Current.Name] = emobj.Current.Value;
-            }
-            List<SurveyRecord> data = new List<SurveyRecord>();
-
-            if (dict.Keys.Count > 0)
-            {
-                data = await _azureCosmos.FindByDict<SurveyRecord>(dict);
-            }
-            else
+            catch (Exception e)
             {
-                return builder.Error(ResponseCode.PARAMS_ERROR, "参数异常!").build();
+                return BadRequest(e.StackTrace);
             }
-            return builder.Data(data).Extend(new Dictionary<string, object> { { "count", data.Count } }).build();*/
-        }        
-         
+        }
     }
 }

+ 5 - 6
TEAMModelOS/Controllers/Common/VoteController.cs

@@ -61,8 +61,8 @@ namespace TEAMModelOS.Controllers.Learn
         /// <param name="request"></param>
         /// <returns></returns>
         [ProducesDefaultResponseType]
-        [HttpPost("save")]
-        public async Task<IActionResult> Save(Vote request)
+        [HttpPost("upsert")]
+        public async Task<IActionResult> Upsert(Vote request)
         {
             try
             {
@@ -86,9 +86,8 @@ namespace TEAMModelOS.Controllers.Learn
                     }
                     request.progress = info.progress;
                     request = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(request, info.id, new PartitionKey($"{info.code}"));
-                   
                 }
-                return Ok(new { request });
+                return Ok(new { vote = request });
             }
             catch (Exception e)
             {
@@ -151,7 +150,7 @@ namespace TEAMModelOS.Controllers.Learn
                     if(!jcount.ValueKind.Equals(JsonValueKind.Undefined) && jcount.TryGetInt32(out int data))
                     {
                         topcout = data;
-                    };
+                    }
                 };
                 //是否需要进行分页查询,默认不分页
                 bool iscontinuation = false;
@@ -302,7 +301,7 @@ namespace TEAMModelOS.Controllers.Learn
         public async Task<IActionResult> UpsertRecord(JsonElement request)
         {
             var (userid, _, _, _) = HttpContext.GetAuthTokenInfo();
-            int msgid = await ActivityService.Decide(request, _azureCosmos, _azureRedis, userid);
+            int msgid = await ActivityStudentService.Decide(request, _azureCosmos, _azureRedis, userid);
             return Ok(new { msgid });
         }
 

+ 4 - 4
TEAMModelOS/Controllers/School/StudentCommonController.cs

@@ -44,12 +44,12 @@ namespace TEAMModelOS.Controllers
         /// </param>
         /// <returns></returns>
         [ProducesDefaultResponseType]
-        [HttpPost("find-activity")]
+        [HttpPost("stu-find-activity")]
         [AuthToken(Roles = "student")]
-        public async Task<IActionResult> FindTch(JsonElement request)
+        public async Task<IActionResult> FindStu(JsonElement request)
         {
-            var (id, _, _, _) = HttpContext.GetAuthTokenInfo();
-            (List<ActivityData> datas, string continuationToken) = await ActivityService.FindByRole("School", request, id, _azureCosmos,_azureRedis);
+            var (id, name, pic,school) = HttpContext.GetAuthTokenInfo();
+            (List<ActivityData> datas, string continuationToken) = await ActivityStudentService.FindAsStu("School", request, school, _azureCosmos,_azureRedis);
             return Ok(new { datas, continuationToken });
         }
         

+ 29 - 5
TEAMModelOS/Controllers/Teacher/TeacherCommonController.cs

@@ -31,7 +31,7 @@ namespace TEAMModelOS.Controllers
             _azureRedis = azureRedis;
         }
         /// <summary>
-        /// 查询活动所有活动类型的列表,教师
+        /// 学生端查询活动所有活动类型的列表,教师以学生身份登入学生端获取活动列表接口
         /// </summary>
         /// <param name="request">
         ///加入的班级信息                      ?classes:[{"classid":"S-C-00001","scope":"school"},{"classid":"P-C-00004","scope":"private"}]
@@ -45,14 +45,38 @@ namespace TEAMModelOS.Controllers
         /// </param>
         /// <returns></returns>
         [ProducesDefaultResponseType]
-        [HttpPost("find-activity")]
+        [HttpPost("stu-find-activity")]
         [AuthToken(Roles = "teacher")] 
-        public async Task<IActionResult> FindTch(JsonElement requert)
+        public async Task<IActionResult> FindStu(JsonElement requert)
         {
             var (id, _, _, _) = HttpContext.GetAuthTokenInfo();
-            (List<ActivityData> datas, string continuationToken) = await ActivityService.FindByRole("Teacher", requert, id, _azureCosmos,_azureRedis);
+            (List<ActivityData> datas, string continuationToken) = await ActivityStudentService.FindAsStu("Teacher", requert, id, _azureCosmos,_azureRedis);
+            return Ok(new { datas, continuationToken });
+        }
+        /// <summary>
+        /// 教师端,查询活动所有活动类型的列表,班主任,任课教师等
+        /// 执教班级
+        /// </summary>
+        /// <param name="request">
+        ///执教的班级信息                      !classes:[{"classid":"S-C-00001","scope":"school"},{"classid":"P-C-00004","scope":"private"}]   TODO  需要排查 对象和班级字符串id设计原因 {"classid":"S-C-00001","scope":"school"}
+        ///执教的科目                          ?subjects:["subjectid1","subjectid2"]
+        ///活动类型                            ?"type":"vote"/"exam"/"homework"/"learn"/"survey"" // vote投票 survey问卷 exam评测 learn学习活动 homework作业活动
+        ///时间筛选范围开始时间 默认30天之前   ?"stime":1608274766154  
+        ///时间筛选范围结束时间 默认当前时间   ?"etime":1608274766666 
+        ///是否展示列表的 Tips                 ? "tips":true/false
+        ///每页大小     ?"count":10/null/Undefined  
+        ///分页Token    ?"continuationToken":Undefined/null/"[{\"token\":\"+RID:~omxMAP3ipcSEEwAAAAAAAA==#RT:2#TRC:20#ISV:2#IEO:65551#QCF:1#FPC:AYQTAAAAAAAAiRMAAAAAAAA=\",\"range\":{\"min\":\"\",\"max\":\"FF\"}}]"
+        ///当前状态     ?"progress":Undefined/null/"" 表示两种状态都要查询/ "going"/"finish" 表示查询进行中/ 或者已完成 学生端只能查询正在进行或已经结束 going 已发布|finish 已结束  
+        /// </param>
+        /// <returns></returns>
+        [ProducesDefaultResponseType]
+        [HttpPost("tch-find-activity")]
+        [AuthToken(Roles = "teacher")]
+        public async Task<IActionResult> FindTch(JsonElement requert)
+        {
+            var (id, _, _, school) = HttpContext.GetAuthTokenInfo();
+            (List<ActivityData> datas, string continuationToken) = await ActivityTeacherService.FindAsTch(  requert, school, _azureCosmos, _azureRedis);
             return Ok(new { datas, continuationToken });
         }
-       
     }
 }

+ 6 - 3
TEAMModelOS/JsonFile/Core/LangConfigV3.json

@@ -11,6 +11,7 @@
           "compose": "综合题",
           "single": "单选题",
           "multiple": "多选题",
+          "sortmultiple": "有序多选题",
           "judge": "判断题",
           "complete": "填空题",
           "subjective": "问答题",
@@ -21,7 +22,7 @@
         "Analysis": "解析",
         "Score": "配分",
         "Point": "知识点",
-        "Filed": "记忆|理解|应用|分析|创造|评价",
+        "Filed": "记忆|理解|应用|分析|评价|创造",
         "Judge": "对|错",
         "Ended": "结束",
         "Level": "难度"
@@ -35,6 +36,7 @@
           "compose": "綜合題",
           "single": "選擇題",
           "multiple": "複選題",
+          "sortmultiple": "有序複選題",
           "judge": "是非題",
           "complete": "填充題",
           "subjective": "問答題",
@@ -45,7 +47,7 @@
         "Analysis": "解析",
         "Score": "配分",
         "Point": "知識點",
-        "Filed": "記憶|理解|應用|分析|創造|評鑒",
+        "Filed": "記憶|理解|應用|分析|評鑒|創造",
         "Judge": "對|錯",
         "Ended": "結束",
         "Level": "難度"
@@ -59,6 +61,7 @@
           "compose": "QuestionGroup",
           "single": "MultipleChoice",
           "multiple": "MultipleAnswers",
+          "sortmultiple": "SortMultipleAnswers",
           "judge": "TrueFalse",
           "complete": "Blank",
           "subjective": "Essay",
@@ -69,7 +72,7 @@
         "Analysis": "Explain",
         "Score": "Score",
         "Point": "Point",
-        "Filed": "Remember|Understand|Apply|Analyze|Create|Evaluate",
+        "Filed": "Remember|Understand|Apply|Analyze|Evaluate|Create",
         "Judge": "True|False",
         "Ended": "Ended",
         "Level": "Level"

+ 27 - 7
TEAMModelOS/Services/Common/ActivityService.cs

@@ -15,7 +15,7 @@ using StackExchange.Redis;
 
 namespace TEAMModelOS.Services.Common
 {
-    public static class ActivityService
+    public static class ActivityStudentService
     {
 
         /// <summary>
@@ -188,15 +188,16 @@ namespace TEAMModelOS.Services.Common
             return week;
         }
 
+
         /// <summary>
-        /// 
+        /// 学生端查询
         /// </summary>
         /// <param name="containerId">容器</param>
         /// <param name="requert"></param>
         /// <param name="id">登录者ID</param>
         /// <param name="_azureCosmos"></param>
         /// <returns></returns>
-        public static async Task<(List<ActivityData> datas, string continuationToken)> FindByRole(string containerId, JsonElement requert, string id, AzureCosmosFactory _azureCosmos,AzureRedisFactory _azureRedis)
+        public static async Task<(List<ActivityData> datas, string continuationToken)> FindAsStu(string containerId, JsonElement requert, string id, AzureCosmosFactory _azureCosmos,AzureRedisFactory _azureRedis)
         {
             //开始时间,默认最近三十天
             var stimestamp = DateTimeOffset.UtcNow.AddDays(-30).ToUnixTimeMilliseconds();
@@ -266,22 +267,40 @@ namespace TEAMModelOS.Services.Common
                 if (jclasses.ValueKind is JsonValueKind.Array ) {
                     classes = jclasses.ToObject<List<string>>();
                 }
-            } 
+            }
+            //班级
+           
+            string joinSqlSubjects = "";
+            string andSqlSubjects = "";
+            if (!requert.TryGetProperty("subjects", out JsonElement jsubjects))
+            {
+                if (jsubjects.ValueKind is JsonValueKind.Array)
+                {
+                    List<string> subjects  = jsubjects.ToObject<List<string>>();
+                    if (subjects.IsNotEmpty()) {
+                        joinSqlSubjects = " join A2 in c.subjects ";
+                        List<string> sqlList = new List<string>();
+                        subjects.ForEach(x => { sqlList.Add($" '{x}' "); });
+                        string sql = string.Join(" , ", sqlList);
+                        andSqlSubjects = $" and A2 in ('{sql}') ";
+                    }
+                }
+            }
             string query = null;
             if (classes.IsNotEmpty() )
             {
                 List<string> sqlList = new List<string>();
                 classes.ForEach( x => { sqlList.Add($" '{x}' "); });
                 string sql = string.Join(" , ", sqlList);
-                query = $" SELECT distinct  value c   FROM c   JOIN A0 IN c.classes join A1 in c.tmdids   where c.startTime >= {stimestamp} and c.startTime <= {etimestamp} and  c.pk='Activity' {typesql} {progresssql} and   (A0 in('{sql}') or A1 in ('{id}')) ";
+                query = $" SELECT distinct  value c   FROM c   JOIN A0 IN c.classes join A1 in c.tmdids {joinSqlSubjects}  where c.startTime >= {stimestamp} and c.startTime <= {etimestamp} and  c.pk='Activity' {typesql} {progresssql}  {andSqlSubjects}  and   (A0 in('{sql}') or A1 ='{id} ') ";
             }
             else {
-                query = $" SELECT distinct  value c   FROM c    join A1 in c.tmdids   where c.startTime >= {stimestamp} and c.startTime <= {etimestamp}  and c.pk='Activity' {typesql} {progresssql} and   A1 ='{id}' ";
+                query = $" SELECT distinct  value c   FROM c    join A1 in c.tmdids  {joinSqlSubjects}  where c.startTime >= {stimestamp} and c.startTime <= {etimestamp}  and c.pk='Activity' {typesql} {progresssql}  {andSqlSubjects}  and   A1 ='{id}' ";
             }
             
             List<ActivityData> datas = new List<ActivityData>();
             var client = _azureCosmos.GetCosmosClient();
-            await foreach (var item in client.GetContainer("TEAMModelOS", containerId).GetItemQueryStreamIterator(query, continuationToken: continuationToken, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout, PartitionKey = new PartitionKey($"Common-{id}") }))
+            await foreach (var item in client.GetContainer("TEAMModelOS", containerId).GetItemQueryStreamIterator(query, continuationToken: continuationToken, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout, PartitionKey = new PartitionKey($"Activity-{id}") }))
             {
                 using var json = await JsonDocument.ParseAsync(item.ContentStream);
                 if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
@@ -309,6 +328,7 @@ namespace TEAMModelOS.Services.Common
             if (tips)
             {
                 DoActivityTips activityTips;
+                //TODO 处理活动tips 的res
                 dynamic res = default;
                 foreach (var data in datas)
                 {

+ 237 - 0
TEAMModelOS/Services/Common/ActivityTeacherService.cs

@@ -0,0 +1,237 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text.Json;
+using System.Threading.Tasks;
+using TEAMModelOS.SDK.Models.Cosmos;
+using TEAMModelOS.SDK.Extension;
+using Azure.Cosmos;
+using TEAMModelOS.SDK.DI;
+using HTEXLib.COMM.Helpers;
+using System.Text;
+using TEAMModelOS.SDK.Models;
+using TEAMModelOS.SDK.Models.Cosmos.Common.Inner;
+using StackExchange.Redis;
+
+namespace TEAMModelOS.Services.Common
+{
+    public class ActivityTeacherService
+    { 
+        
+        /// <summary>
+        /// 活动委托
+        /// </summary>
+        /// <param name="data"></param>
+        /// <returns></returns>
+        delegate dynamic DoActivityTips(ActivityData data, AzureCosmosFactory _azureCosmos, string id, AzureRedisFactory _azureRedis);
+
+        /// <summary>
+        /// 教师端查询
+        /// </summary>
+        /// <param name="containerId">容器</param>
+        /// <param name="requert"></param>
+        /// <param name="id">登录者ID</param>
+        /// <param name="_azureCosmos"></param>
+        /// <returns></returns>
+        public static async Task<(List<ActivityData> datas, string continuationToken)> FindAsTch(JsonElement requert, string school, AzureCosmosFactory _azureCosmos, AzureRedisFactory _azureRedis)
+        {
+            //开始时间,默认最近三十天
+            var stimestamp = DateTimeOffset.UtcNow.AddDays(-30).ToUnixTimeMilliseconds();
+
+
+            if (!requert.TryGetProperty("stime", out JsonElement stime))
+            {
+                if (stime.TryGetInt64(out long data))
+                {
+                    stimestamp = data;
+                }
+            }
+
+            var progresssql = "";
+            if (!requert.TryGetProperty("progress", out JsonElement progress))
+            {
+
+                if (!progress.ValueKind.Equals(JsonValueKind.Undefined) && !progress.ValueKind.Equals(JsonValueKind.Null) && progress.ValueKind.Equals(JsonValueKind.String))
+                {
+                    progresssql = $" and c.progress='{progresssql}' ";
+                }
+            }
+            var typesql = "";
+            if (!requert.TryGetProperty("type", out JsonElement type))
+            {
+
+                if (!type.ValueKind.Equals(JsonValueKind.Undefined) && !type.ValueKind.Equals(JsonValueKind.Null) && type.ValueKind.Equals(JsonValueKind.String))
+                {
+                    typesql = $" and c.type='{typesql}' ";
+                }
+            }
+            //默认当前时间,  未开始的不能查询
+            var etimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
+            //if (!requert.TryGetProperty("etime", out JsonElement etime))
+            //{
+            //    if (etime.TryGetInt64(out long data))
+            //    {
+            //        etimestamp = data;
+            //    };
+            //};
+            string continuationToken = null;
+            //默认不指定返回大小
+            int? topcout = null;
+            if (!requert.TryGetProperty("count", out JsonElement jcount))
+            {
+                if (jcount.TryGetInt32(out int data))
+                {
+                    topcout = data;
+                }
+            }
+            //是否需要进行分页查询,默认不分页
+            bool iscontinuation = false;
+            //如果指定了返回大小
+            if (!requert.TryGetProperty("continuationToken", out JsonElement continuation))
+            {
+                //指定了cancellationToken 表示需要进行分页
+                if (!continuation.ValueKind.Equals(JsonValueKind.Null) && continuation.ValueKind.Equals(JsonValueKind.String))
+                {
+                    continuationToken = continuation.GetString();
+                    iscontinuation = true;
+                }
+            }
+            //班级
+            List<string> classes = null;
+            if (!requert.TryGetProperty("classes", out JsonElement jclasses))
+            {
+                if (jclasses.ValueKind is JsonValueKind.Array)
+                {
+                    classes = jclasses.ToObject<List<string>>();
+                }
+            }
+            //班级
+            string joinSqlSubjects = "";
+            string andSqlSubjects = "";
+            if (!requert.TryGetProperty("subjects", out JsonElement jsubjects))
+            {
+                if (jsubjects.ValueKind is JsonValueKind.Array)
+                {
+                    List<string> subjects = jsubjects.ToObject<List<string>>();
+                    if (subjects.IsNotEmpty())
+                    {
+                        joinSqlSubjects = " join A2 in c.subjects ";
+                        List<string> sqlList = new List<string>();
+                        subjects.ForEach(x => { sqlList.Add($" '{x}' "); });
+                        string sql = string.Join(" , ", sqlList);
+                        andSqlSubjects = $" and A2 in ('{sql}') ";
+                    }
+                }
+            }
+            string query = null;
+            if (classes.IsNotEmpty())
+            {
+                List<string> sqlList = new List<string>();
+                classes.ForEach(x => { sqlList.Add($" '{x}' "); });
+                string sql = string.Join(" , ", sqlList);
+                query = $" SELECT distinct  value c   FROM c   JOIN A0 IN c.classes join A1 in c.tmdids {joinSqlSubjects}  where c.startTime >= {stimestamp} and c.startTime <= {etimestamp} and  c.pk='Activity' {typesql} {progresssql}  {andSqlSubjects}  and   (A0 in('{sql}') or A1 ='{school} ') ";
+            }
+            else
+            {
+                query = $" SELECT distinct  value c   FROM c    join A1 in c.tmdids  {joinSqlSubjects}  where c.startTime >= {stimestamp} and c.startTime <= {etimestamp}  and c.pk='Activity' {typesql} {progresssql}  {andSqlSubjects}  and   A1 ='{school}' ";
+            }
+
+            List<ActivityData> datas = new List<ActivityData>();
+            var client = _azureCosmos.GetCosmosClient();
+            //班主任 ,任课教师只需要查询两种校园活动 和班级活动 ,  不查询私人教室创建的活动。  
+            await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(query, continuationToken: continuationToken, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout, PartitionKey = new PartitionKey($"Activity-{school}") }))
+            {
+                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())
+                    {
+                        datas.Add(obj.ToObject<ActivityData>());
+                    }
+                    //如果需要分页则跳出
+                    if (iscontinuation)
+                    {
+                        continuationToken = item.GetContinuationToken();
+                        break;
+                    }
+                }
+            }
+            bool tips = false;
+            if (!requert.TryGetProperty("tips", out JsonElement jtips))
+            {
+                if (!jtips.ValueKind.Equals(JsonValueKind.Null) && !jtips.ValueKind.Equals(JsonValueKind.True))
+                {
+                    tips = jtips.GetBoolean();
+                }
+            }
+            if (tips)
+            {
+                DoActivityTips activityTips;
+                dynamic res = default;
+                foreach (var data in datas)
+                {
+                    //处理参与度,
+                    switch (data.type)
+                    {
+                        //投票
+                        case "vote":
+                            activityTips = DoVoteTips;
+                            //msgid, //0不能投票,1可以投票,2不在时间范围内,3周期内的可投票数不足
+                            //voteCount 可用投票数
+                            res = activityTips(data, _azureCosmos, school, _azureRedis);
+                            break;
+                        //问卷
+                        case "survey":
+                            //msgid 0 已作答, 1未作答,2,未完成
+                            activityTips = DoSurveyTips;
+                            res = activityTips(data, _azureCosmos, school, _azureRedis);
+                            break;
+                        //评测
+                        case "exam":
+                            //msgid 0 已作答, 1未作答,2,未完成, 用时间控制 相关发布状态,并且展示相应的结果
+                            activityTips = DoExamTips;
+                            res = activityTips(data, _azureCosmos, school, _azureRedis);
+                            break;
+                        //学习活动
+                        case "learn":
+                            //msgid 0 已完成, 1未开始,2,未完成
+                            activityTips = DoLearnTips;
+                            res = activityTips(data, _azureCosmos, school, _azureRedis);
+                            break;
+                        //作业活动
+                        case "homework":
+                            //msgid 0 已作答, 1未作答,2,未完成,3已批改,且有错误,4已批改,已完成
+                            //index:0,1,5 错误题序
+                            activityTips = DoHomeworkTips;
+                            res = activityTips(data, _azureCosmos, school, _azureRedis);
+                            break;
+                        default: break;
+                    }
+                }
+            }
+            return (datas, continuationToken);
+        }
+
+        private async static Task<dynamic> DoVoteTips(ActivityData commonData, AzureCosmosFactory _azureCosmos, string userid, AzureRedisFactory _azureRedis)
+        {
+            return null;
+        }
+
+        private static dynamic DoHomeworkTips(ActivityData commonData, AzureCosmosFactory _azureCosmos, string id, AzureRedisFactory _azureRedis)
+        {
+            return null;
+        }
+        private static dynamic DoLearnTips(ActivityData commonData, AzureCosmosFactory _azureCosmos, string id, AzureRedisFactory _azureRedis)
+        {
+            return null;
+        }
+        private static dynamic DoExamTips(ActivityData commonData, AzureCosmosFactory _azureCosmos, string id, AzureRedisFactory _azureRedis)
+        {
+            return null;
+        }
+        private static dynamic DoSurveyTips(ActivityData commonData, AzureCosmosFactory _azureCosmos, string id, AzureRedisFactory _azureRedis)
+        {
+            return null;
+        }
+    }
+}