Преглед изворни кода

修复题目筛选条件计算bug.

CrazyIter_Bin пре 3 година
родитељ
комит
96c35252c9

+ 1 - 38
TEAMModelFunction/ActivityHttpTrigger.cs

@@ -392,44 +392,7 @@ namespace TEAMModelFunction
             }
             return new OkObjectResult(new { });
         }
-        /// <summary>
-        //获取题目摘要信息
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        //[AuthToken(Roles = "teacher")]
-        [FunctionName("fix-itemcond")]
-        public async Task<IActionResult> FixItemCond(
-            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
-            ILogger log)
-        {
-            try {
-                var client = _azureCosmos.GetCosmosClient();
-                List<ItemInfo> items = new List<ItemInfo>();
-                var queryslt = $"SELECT  value(c) FROM c where  c.pid = null ";
-                await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-hbcn") }))
-                {
-
-                    items.Add(item);
-                }
-                List<ItemCond> itemConds = new List<ItemCond>();
-                items.GroupBy(x => x.periodId).Select(y=>new {key= y.Key,list=y.ToList() }).ToList().ForEach(z => {
-                    ItemCond cond = new ItemCond() { id = z.key, code = $"ItemCond-hbcn", pk = "ItemCond", ttl = -1, count = 0, grades = new List<GradeCount>(), subjects = new List<SubjectCount>() };
-                    z.list.ForEach(y => {
-                        ItemService.CountItemCond(y, null, cond);
-                    });
-
-                    itemConds.Add(cond);
-                });
-                itemConds.ForEach(async cond =>
-                {
-                    await client.GetContainer("TEAMModelOS", "School").UpsertItemAsync<ItemCond>(cond, new PartitionKey(cond.code));
-                });
-                return new OkObjectResult(new { itemConds });
-            } catch (Exception ex) { await _dingDing.SendBotMsg($"TEAMModelFunction,ActivityHttpTrigger,fix-itemcond()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組); }
-            return new OkObjectResult(new { });
-        }
+        
         /// <summary>
         /// 设置问卷调查未初始化学生列表的业务
         /// </summary>

+ 1 - 1
TEAMModelFunction/CourseServiceBus.cs

@@ -37,7 +37,7 @@ namespace TEAMModelFunction
             var client = _azureCosmos.GetCosmosClient();
             try
             {
-                await _dingDing.SendBotMsg($"ServiceBus,CourseChange:{msg}", GroupNames.醍摩豆服務運維群組);
+                //await _dingDing.SendBotMsg($"ServiceBus,CourseChange:{msg}", GroupNames.醍摩豆服務運維群組);
                 var jsonMsg = JsonDocument.Parse(msg);
                 CourseChange courseChange = msg.ToObject<CourseChange>();
                 if (courseChange == null) {

+ 5 - 5
TEAMModelFunction/TriggerVote.cs

@@ -75,11 +75,11 @@ namespace TEAMModelFunction
                         case "going":
                             List<string> classes = ExamService.getClasses(vote.classes, vote.stuLists);
                             (List<TmdInfo> tmdids, List<StuInfo> students, List<ClassListInfo> classLists) = await TriggerStuActivity.GetStuList(client, _dingDing, classes, vote.school);
-                            await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}投票活动" +
-                                $"{tmdids.ToJsonString()}\n" +
-                                $"{students.ToJsonString()}\n" +
-                                $"{classLists.ToJsonString()}\n" +
-                                $"{classes.ToJsonString()}\n", GroupNames.成都开发測試群組);
+                            //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}投票活动" +
+                            //    $"{tmdids.ToJsonString()}\n" +
+                            //    $"{students.ToJsonString()}\n" +
+                            //    $"{classLists.ToJsonString()}\n" +
+                            //    $"{classes.ToJsonString()}\n", GroupNames.成都开发測試群組);
                             List<string> tmds = new List<string>();
                             if (tmdids.IsNotEmpty())
                             {

+ 12 - 0
TEAMModelOS.SDK/Context/Constant/ConstField.cs

@@ -0,0 +1,12 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace TEAMModelOS.SDK
+{
+    public class ConstField
+    {
+        public static readonly List<string> BlobPrefix = new List<string> { "exam", "vote", "survey", "item", "paper", "syllabus", "records", "doc", "image", "res", "video", "audio", "other", "thum", "train", "temp", "jyzx" };
+        public static readonly List<string> ContentPrefix = new List<string> { "doc", "image", "res", "video", "audio", "other"};
+    }
+}

+ 3 - 1
TEAMModelOS.SDK/Models/Cosmos/Common/ItemCond.cs

@@ -17,8 +17,10 @@ namespace TEAMModelOS.SDK.Models
         public List<GradeCount> grades { get; set; } = new List<GradeCount>();
 
         public List<SubjectCount> subjects { get; set; } = new List<SubjectCount>();
+
+        
         //key  学段id-科目id
-      //  public Dictionary<string, List<CondCount>> subjects { get; set; } = new Dictionary<string, List<CondCount>>();
+        //  public Dictionary<string, List<CondCount>> subjects { get; set; } = new Dictionary<string, List<CondCount>>();
     }
     //public class CondCount {
     //    public KeyValuePair<string, int> grade { get; set; } = new KeyValuePair<string, int>();

+ 21 - 0
TEAMModelOS.SDK/Models/Cosmos/Student/TmdUser.cs

@@ -0,0 +1,21 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace TEAMModelOS.SDK.Models
+{
+    public class TmdUser : CosmosEntity
+    {
+        public string name { get; set; }
+        public string picture { get; set; }
+        public string defaultSchool { get; set; }
+        public List<School> schools { get; set; }
+        public class School
+        {
+            public string schoolId { get; set; }
+            public string name { get; set; }
+            public string status { get; set; }
+            public long time { get; set; }
+        }
+    }
+}

+ 0 - 4
TEAMModelOS.SDK/Models/Cosmos/Teacher/Teacher.cs

@@ -12,8 +12,6 @@ namespace TEAMModelOS.SDK.Models
         public int size { get; set; }
         public string defaultSchool { get; set; }
         public List<School> schools { get; set; }
-       
-
         public class School
         {
             public string schoolId { get; set; }
@@ -22,6 +20,4 @@ namespace TEAMModelOS.SDK.Models
             public long time { get; set; }
         }
     }
-
-
 }

+ 25 - 14
TEAMModelOS.SDK/Models/Service/ItemService.cs

@@ -2,6 +2,8 @@ using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Threading.Tasks;
+using TEAMModelOS.SDK;
+using TEAMModelOS.SDK.Extension;
 using TEAMModelOS.SDK.Models;
 
 namespace TEAMModelOS.Services.Common
@@ -21,7 +23,7 @@ namespace TEAMModelOS.Services.Common
             {
                 string newKey = $"{newItem.subjectId}";
                 List<string> grade = newItem.gradeIds;
-                UpdateItemCond(cond, true, newKey, grade, newItem.type, newItem.level, newItem.field.HasValue ? newItem.field.Value : 0);
+                UpdateItemCond(cond, true, newKey, grade, newItem.type, newItem.level, newItem.field.HasValue ? newItem.field.Value : 0, newItem);
             }
             else if (newItem != null && odlItem != null)
             {
@@ -31,18 +33,18 @@ namespace TEAMModelOS.Services.Common
                     //先增加
                     string newKey = $"{newItem.subjectId}";
                     List<string> newGrade = newItem.gradeIds;
-                    UpdateItemCond(cond, true, newKey, newGrade, newItem.type, newItem.level, newItem.field.HasValue ? newItem.field.Value : 0);
+                    UpdateItemCond(cond, true, newKey, newGrade, newItem.type, newItem.level, newItem.field.HasValue ? newItem.field.Value : 0, newItem);
                     //后变更删除
                     string oldKey = $"{odlItem.subjectId}";
                     List<string> oldGrade = odlItem.gradeIds;
-                    UpdateItemCond(cond, false, oldKey, oldGrade, odlItem.type, odlItem.level, odlItem.field.HasValue ? odlItem.field.Value : 0);
+                    UpdateItemCond(cond, false, oldKey, oldGrade, odlItem.type, odlItem.level, odlItem.field.HasValue ? odlItem.field.Value : 0, newItem);
                 }
             }
             else if (newItem == null && odlItem != null)
             {
                 string oldKey = $"{odlItem.subjectId}";
                 List<string> oldGrade = odlItem.gradeIds;
-                UpdateItemCond(cond, false, oldKey, oldGrade, odlItem.type, odlItem.level, odlItem.field.HasValue ? odlItem.field.Value : 0);
+                UpdateItemCond(cond, false, oldKey, oldGrade, odlItem.type, odlItem.level, odlItem.field.HasValue ? odlItem.field.Value : 0,null);
             }
             else
             {
@@ -56,8 +58,9 @@ namespace TEAMModelOS.Services.Common
         /// </summary>
         /// <param name="cond"></param>
         /// <param name="opt"></param>
-        public static void UpdateItemCond(ItemCond cond, bool opt, string key, List<string> grade, string type, int level, int field)
+        public static void UpdateItemCond(ItemCond cond, bool opt, string key, List<string> grade, string type, int level, int field,ItemInfo newItem)
         {
+           
             int count = 0;
             if (opt)
             {
@@ -68,10 +71,15 @@ namespace TEAMModelOS.Services.Common
                 //未计入的则默认0
                 count = -1;
             }
-            grade.ForEach(x => {
+            foreach (var x in grade) {
                 bool none = true;
+                if (x == null)
+                {
+
+                }
                 for (int index = 0; index < cond.grades.Count; index++)
                 {
+
                     if (x == cond.grades[index].id)
                     {
                         cond.grades[index].count = cond.grades[index].count + count;
@@ -81,17 +89,19 @@ namespace TEAMModelOS.Services.Common
                 }
                 if (none)
                 {
+                    if (x == null) {
+                        Console.WriteLine(newItem.ToJsonString());
+                    }
                     cond.grades.Add(new GradeCount { id = x, count = count });
                 }
-            });
-         
-            SubjectCount subject = cond.subjects.Where(x => x.id == key).FirstOrDefault();
+            }
+            SubjectCount subject = cond.subjects.Find(x => x.id == key);
             if (subject == null)
             {
-                cond.subjects.Add(new SubjectCount() { id=key});
+                cond.subjects.Add(new SubjectCount() { id=key, count =0});
             }
-            cond.subjects.Where(x => x.id == key).ToList().ForEach(y => {
-               
+            var list = cond.subjects.FindAll(x => x.id == key).ToList();
+            foreach (var y in list) {
                 if (!y.types.ContainsKey(type))
                 {
                     var dict = new Dictionary<string, Dictionary<string, int>>
@@ -116,10 +126,11 @@ namespace TEAMModelOS.Services.Common
                 else
                 {
                     y.types[type]["level"][$"{level}"] = y.types[type]["level"][$"{level}"] + count;
-                    y.types[type]["field"][$"{level}"] = y.types[type]["field"][$"{field}"] + count;
+                  
+                    y.types[type]["field"][$"{field}"] = y.types[type]["field"][$"{field}"] + count;
                 }
                 y.count = y.count + count;
-            });
+            }
             cond.count = cond.subjects.Select(x => x.count).Sum();
         }
     }

+ 61 - 2
TEAMModelOS/Controllers/Core/BlobController.cs

@@ -162,7 +162,6 @@ namespace TEAMModelOS.Controllers.Core
             {
                 return BadRequest("文件名错误");
             };
-
         }
 
         /// <summary>
@@ -592,7 +591,7 @@ namespace TEAMModelOS.Controllers.Core
             }
             catch (Exception ex)
             {
-                await _dingDing.SendBotMsg($"IES5,{_option.Location},blob/bloblog-blob()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
+                await _dingDing.SendBotMsg($"IES5,{_option.Location},blob/bloblog-blob()\n{ex.Message}{ex.StackTrace}\n{request.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
             }
             return Ok(new { status = 200 });
         }
@@ -769,5 +768,65 @@ namespace TEAMModelOS.Controllers.Core
                 return BadRequest();
             }
         }
+
+        /// <summary>
+        /// 列出blob的
+        /// 
+        /// {"cntr":"","urls":["res/test/1.json","res/test/2.json"]}
+        /// {"scope":"school","cntr":"hbcn","blobs":[{"path":"other/test/1.json","id":"c107069d-4553-46c2-8c81-b3e6b4599393"},{"path":"res/test","id":"09d59b87-68c0-45fa-8221-9931a4190a2f"}]}
+        /// </summary>
+        /// <param name="request"></param>
+        /// <returns></returns>
+        [HttpPost("blob-list")]
+        [AuthToken(Roles = "teacher,admin,student")]
+        public async Task<IActionResult> BlobList(JsonElement json) {
+            var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
+            List<string> paths = new List<string>();
+            //文件的容器
+            if (!json.TryGetProperty("cntr", out JsonElement _cntr)) return BadRequest();
+            //业务存取类型 exam,vote,survey,item,paper,syllabus,records,content(doc,image,res,video,audio,other),thum,train,temp,jyzx
+            if (!json.TryGetProperty("type", out JsonElement _type)) return BadRequest();
+            //文件前缀prefix
+            switch (true)
+            {
+                case bool when $"{_type}".Equals("exam", StringComparison.OrdinalIgnoreCase)
+                    || $"{_type}".Equals("vote", StringComparison.OrdinalIgnoreCase)
+                    || $"{_type}".Equals("survey", StringComparison.OrdinalIgnoreCase)
+                    || $"{_type}".Equals("item", StringComparison.OrdinalIgnoreCase)
+                    || $"{_type}".Equals("paper", StringComparison.OrdinalIgnoreCase):
+                    string type = $"{_type}".Substring(0, 1).ToUpper() + $"{_type}".Substring(1);
+                    //业务存取id
+                    if (!json.TryGetProperty("id", out JsonElement _aid)) return BadRequest();
+                    //业务存取分区键
+                    if (!json.TryGetProperty("code", out JsonElement _acode)) return BadRequest();
+                    //业务存取分区键
+                    if (!json.TryGetProperty("scope", out JsonElement _ascope)) return BadRequest();
+                    break;
+                case bool when $"{_type}".Equals("doc", StringComparison.OrdinalIgnoreCase)
+                    || $"{_type}".Equals("image", StringComparison.OrdinalIgnoreCase)
+                    || $"{_type}".Equals("res", StringComparison.OrdinalIgnoreCase)
+                    || $"{_type}".Equals("video", StringComparison.OrdinalIgnoreCase)
+                    || $"{_type}".Equals("audio", StringComparison.OrdinalIgnoreCase)
+                    || $"{_type}".Equals("other", StringComparison.OrdinalIgnoreCase):
+                    //业务存取id
+                    if (!json.TryGetProperty("id", out JsonElement _bid)) return BadRequest();
+                    //业务存取分区键
+                    if (!json.TryGetProperty("code", out JsonElement _bcode)) return BadRequest();
+                    //业务存取分区键
+                    if (!json.TryGetProperty("scope", out JsonElement _bscope)) return BadRequest();
+                    break;
+                case bool when $"{_type}".Equals("records", StringComparison.OrdinalIgnoreCase)
+                    || $"{_type}".Equals("syllabus", StringComparison.OrdinalIgnoreCase)
+                    || $"{_type}".Equals("thum", StringComparison.OrdinalIgnoreCase)
+                    || $"{_type}".Equals("temp", StringComparison.OrdinalIgnoreCase)
+                    || $"{_type}".Equals("jyzx", StringComparison.OrdinalIgnoreCase)
+                    || $"{_type}".Equals("train", StringComparison.OrdinalIgnoreCase):
+                    break;
+                default:
+                    break;
+            }
+            var status = await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, $"{_cntr}", new List<string> { "aaa" });
+           return Ok(new { paths ,status=1});
+        }
     }
 }

+ 154 - 0
TEAMModelOS/Controllers/School/TmdUserController.cs

@@ -0,0 +1,154 @@
+using Azure.Cosmos;
+using Azure.Storage.Blobs.Models;
+using Azure.Storage.Sas;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Options;
+using System;
+using System.Collections.Generic;
+using System.Dynamic;
+using System.IdentityModel.Tokens.Jwt;
+using System.IO;
+using System.Linq;
+using System.Text.Json;
+using System.Threading.Tasks;
+using TEAMModelOS.Models;
+using TEAMModelOS.SDK.Models;
+using TEAMModelOS.SDK.DI;
+using TEAMModelOS.SDK.Extension;
+using TEAMModelOS.Filter;
+using TEAMModelOS.SDK.Models.Cosmos;
+using HTEXLib.COMM.Helpers;
+using TEAMModelOS.SDK.Models.Service;
+using Microsoft.Extensions.Configuration;
+using System.Net.Http;
+
+namespace TEAMModelOS.Controllers
+{
+    [ProducesResponseType(StatusCodes.Status200OK)]
+    [ProducesResponseType(StatusCodes.Status400BadRequest)]
+    //[Authorize(Roles = "IES5")]
+    [Route("tmduser/init")]
+    [ApiController]
+    public class TmdUserController: ControllerBase
+    {
+        private readonly AzureCosmosFactory _azureCosmos;
+        private readonly AzureStorageFactory _azureStorage;
+        private readonly DingDing _dingDing;
+        private readonly Option _option;
+        private readonly IConfiguration _configuration;
+
+        public TmdUserController(AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option, IConfiguration configuration)
+        {
+            _azureCosmos = azureCosmos;
+            _azureStorage = azureStorage;
+            _dingDing = dingDing;
+            _option = option?.Value;
+            _configuration = configuration;
+        }
+        [ProducesDefaultResponseType]
+        [HttpPost("get-school-info")]
+        public async Task<IActionResult> GetSchoolInfo(JsonElement request) {
+
+            if (!request.TryGetProperty("id_token", out JsonElement id_token)) return BadRequest();
+            if (!request.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
+            var jwt = new JwtSecurityToken(id_token.GetString());
+            if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.Ordinal)) return BadRequest();
+            var id = jwt.Payload.Sub;
+            var client = _azureCosmos.GetCosmosClient();
+            //權限token
+            jwt.Payload.TryGetValue("name", out object name);
+            jwt.Payload.TryGetValue("picture", out object picture);
+            return Ok();
+        }
+
+        [ProducesDefaultResponseType]
+        [HttpPost("get-tmduser-info")]
+        public async Task<IActionResult> GetTmdUserInfo(JsonElement request)
+        {
+            try
+            {
+                if (!request.TryGetProperty("id_token", out JsonElement id_token)) return BadRequest();
+                var jwt = new JwtSecurityToken(id_token.GetString());
+                if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.OrdinalIgnoreCase)) return BadRequest();
+                var id = jwt.Payload.Sub;
+                jwt.Payload.TryGetValue("name", out object name);
+                jwt.Payload.TryGetValue("picture", out object picture);
+                List<object> schools = new List<object>();
+                string defaultschool = null;
+                var client = _azureCosmos.GetCosmosClient();
+                try
+                {
+                    TmdUser tmdUser = await client.GetContainer("TEAMModelOS", "Student").ReadItemAsync<TmdUser>(id, new PartitionKey("Base"));
+                    tmdUser.name = $"{name}";
+                    tmdUser.picture = $"{picture}";
+                    if (tmdUser.schools.IsNotEmpty())
+                    {
+                        foreach (var sc in tmdUser.schools)
+                        {
+                             
+                            dynamic schoolExtobj = new ExpandoObject();
+                            var schoolJson = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{sc.schoolId}", new PartitionKey("Base"));
+                            var school = await JsonDocument.ParseAsync(schoolJson.ContentStream);
+                            schoolExtobj.schoolId = sc.schoolId;
+                            schoolExtobj.name = school.RootElement.GetProperty("name");
+                            schoolExtobj.status = sc.status;
+                            schoolExtobj.time = sc.time;
+                            schoolExtobj.picture = school.RootElement.GetProperty("picture");
+                            sc.name= $"{school.RootElement.GetProperty("name")}";
+                        }
+                        tmdUser.defaultSchool = string.IsNullOrEmpty(tmdUser.defaultSchool) ? tmdUser.schools[0].schoolId : tmdUser.defaultSchool;
+                    }
+                    await client.GetContainer("TEAMModelOS", "Student").ReplaceItemAsync<TmdUser>(tmdUser, id, new PartitionKey("Base"));
+                    //預設學校ID
+                    defaultschool = tmdUser.defaultSchool;
+                }
+                catch (CosmosException ex)
+                {
+                    if (ex.Status == 404)
+                    {
+                        //如果沒有,則初始化Teacher基本資料到Cosmos
+                        TmdUser teacher = new TmdUser
+                        {
+                            id = id,
+                            pk = "Base",
+                            code = "Base",
+                            name = name?.ToString(),
+                            picture = picture?.ToString(),
+                            defaultSchool = null,
+                            schools = new List<TmdUser.School>(),
+                        };
+                        var container = _azureStorage.GetBlobContainerClient(id);
+                        await container.CreateIfNotExistsAsync(PublicAccessType.None); //嘗試創建Teacher私有容器,如存在則不做任何事,保障容器一定存在
+                        teacher = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Student").CreateItemAsync<TmdUser>(teacher, new PartitionKey("Base"));
+                    }
+                }
+                //換取AuthToken,提供給前端
+                var auth_token = JwtAuthExtension.CreateAuthToken(_option.HostName, id, name?.ToString(), picture?.ToString(), _option.JwtSecretKey, roles: new[] { "student" });
+                if (!string.IsNullOrEmpty(defaultschool)) { 
+
+                }
+                return Ok(new { auth_token,  schools, defaultschool });
+
+            }
+            catch (CosmosException ex)
+            {
+                await _dingDing.SendBotMsg($"IES5,{_option.Location},Teacher/GetTeacherInfo()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
+                return BadRequest();
+            }
+            catch (Exception ex)
+            {
+                await _dingDing.SendBotMsg($"IES5,{_option.Location},Teacher/GetTeacherInfo()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
+                return BadRequest();
+            }
+        }
+    
+        private  async Task<(string uri,string  sas)> GetSchoolData(string shool) {
+
+            // BLOB(學校,唯讀)
+            var (blob_uri, blob_sas) = _azureStorage.GetBlobContainerSAS(shool, BlobContainerSasPermissions.Read);
+
+            return (blob_uri, blob_sas);
+        }
+    }
+}

+ 112 - 0
TEAMModelOS/Controllers/Teacher/CommentController.cs

@@ -248,6 +248,118 @@ namespace TEAMModelOS.Controllers
             }
 
         }
+
+
+        [ProducesDefaultResponseType]
+        [HttpPost("tch-activity-count")]
+        //[AuthToken(Roles = "teacher")]
+        public async Task<IActionResult> TchActivityCount(JsonElement requert) {
+            var (id, _, _, school) = HttpContext.GetAuthTokenInfo();
+            if (string.IsNullOrWhiteSpace(school))
+            {
+                if (requert.TryGetProperty("school", out JsonElement schoolcode))
+                {
+                    if (!schoolcode.ValueKind.Equals(JsonValueKind.Undefined) && !schoolcode.ValueKind.Equals(JsonValueKind.Null) && schoolcode.ValueKind.Equals(JsonValueKind.String))
+                    {
+                        school = schoolcode.GetString();
+                    }
+                }
+            }
+            if (string.IsNullOrWhiteSpace(id))
+            {
+                if (requert.TryGetProperty("userid", out JsonElement userid))
+                {
+                    if (!userid.ValueKind.Equals(JsonValueKind.Undefined) && !userid.ValueKind.Equals(JsonValueKind.Null) && userid.ValueKind.Equals(JsonValueKind.String))
+                    {
+                        id = userid.GetString();
+                    }
+                }
+            }
+            var pksql = "";
+            string type = null;
+            if (requert.TryGetProperty("pk", out JsonElement pk))
+            {
+                if (!pk.ValueKind.Equals(JsonValueKind.Undefined) && !pk.ValueKind.Equals(JsonValueKind.Null) && pk.ValueKind.Equals(JsonValueKind.String))
+                {
+                    pksql = $"  c.pk='{pk}' ";
+                    type = $"{pk}";
+                }
+            }
+            if (string.IsNullOrEmpty(type)) { return BadRequest("type is required!"); }
+            
+            //默认不指定返回大小
+            int? topcout = null;
+            if (requert.TryGetProperty("count", out JsonElement jcount))
+            {
+                if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
+                {
+                    topcout = data;
+                }
+            }
+         
+            
+            //班级
+            string joinSqlClasses = "";
+            string andSqlClasses = "";
+            List<string> classes = null;
+            if (requert.TryGetProperty("classes", out JsonElement jclasses))
+            {
+                if (jclasses.ValueKind is JsonValueKind.Array)
+                {
+                    classes = jclasses.ToObject<List<string>>();
+                    if (classes.IsNotEmpty())
+                    {
+                        joinSqlClasses = " join A1 in c.classes ";
+                        List<string> sqlList = new List<string>();
+                        classes.ForEach(x => { sqlList.Add($" '{x}' "); });
+                        string sql = string.Join(" , ", sqlList);
+                        andSqlClasses = $"   A1 in ({sql}) ";
+                    }
+                }
+            }
+            string classesSql = "";
+            if (!string.IsNullOrWhiteSpace(joinSqlClasses))
+            {
+                classesSql = $" and    {andSqlClasses }  ";
+            }
+            List<JsonElement> datas = new List<JsonElement>();
+            var client = _azureCosmos.GetCosmosClient();
+            //班主任 ,任课教师只需要查询两种校园活动 和班级活动 ,  不查询私人教室创建的活动。  
+            if (!string.IsNullOrWhiteSpace(school) && classes.IsNotEmpty())
+            {
+                string querySchool = $" SELECT distinct c.owner, c.id,c.code, c.classes,c.subjects,c.progress,c.scope,c.startTime,c.school,c.creatorId,c.name,c.pk ,c.endTime   FROM c {joinSqlClasses}   where   {pksql}    {classesSql}";
+                //查询数据归属学校的
+                await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(querySchool,  requestOptions: new QueryRequestOptions() { MaxItemCount = topcout, PartitionKey = new PartitionKey($"{type}-{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<JsonElement>());
+                        }
+                        
+                    }
+                }
+            }
+            string queryTeacher = $" SELECT distinct c.owner, c.id,c.code, c.classes,c.subjects,c.progress,c.scope,c.startTime,c.school,c.creatorId,c.name,c.pk ,c.endTime  FROM c   where   {pksql}  ";
+            //查询数据归属学校的
+            await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryTeacher,  requestOptions: new QueryRequestOptions() { MaxItemCount = topcout, PartitionKey = new PartitionKey($"{type}-{id}") }))
+            {
+                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<JsonElement>());
+                    }
+                }
+            }
+            return Ok();
+        }
+
+
+
         /// <summary>
         /// 教师端,查询活动所有活动类型的列表,班主任,任课教师等
         /// 执教班级

+ 119 - 0
TEAMModelOS/Controllers/XTest/FixDataController.cs

@@ -39,6 +39,125 @@ namespace TEAMModelOS.Controllers.XTest
             _azureStorage = azureStorage;
             _dingDing = dingDing;
         }
+        [ProducesDefaultResponseType]
+        //[AuthToken(Roles = "teacher")]
+        [HttpPost("fix-item")]
+        public async Task<IActionResult> FixItem(JsonElement data) {
+            var client = _azureCosmos.GetCosmosClient();
+            List<ItemInfo> items = new List<ItemInfo>();
+            var queryslt = $"SELECT  value(c) FROM c where  c.pid = null ";
+            List<ItemInfo> noPeriodId = new List<ItemInfo>();
+            List<ItemInfo> noSubjectId = new List<ItemInfo>();
+            List<ItemInfo> noGradeIds = new List<ItemInfo>();
+            School school=  await client.GetContainer("TEAMModelOS", "School").ReadItemAsync<School>("hbcn", partitionKey: new PartitionKey("Base"));
+            Random random = new Random();
+            await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-hbcn") }))
+            {
+                if (string.IsNullOrEmpty(item.periodId))
+                {
+                    noPeriodId.Add(item);
+                }
+                if (string.IsNullOrEmpty(item.subjectId))
+                {
+                    noSubjectId.Add(item);
+                }
+                if (!item.gradeIds.IsNotEmpty())
+                {
+                    noGradeIds.Add(item);
+                }
+                bool errorData = false;
+                foreach (var x in item.gradeIds) {
+                    if (string.IsNullOrEmpty(x)) {
+                        errorData = true;
+                    }
+                }
+                if (errorData) {
+                    List<string> grds = new List<string>();
+                    item.gradeIds.ForEach(x => {
+                        if (string.IsNullOrEmpty(x))
+                        {
+                            grds.Add($"{random.Next(0, 5)}");
+                        }
+                        else {
+                            grds.Add(x);
+                        }
+                    });
+                    item.gradeIds = grds;
+                    await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<ItemInfo>(item, item.id, new PartitionKey(item.code));
+                }
+                items.Add(item);
+            }
+            List<ItemInfo> unMatch = new List<ItemInfo>();
+            foreach (var item in items)
+            {
+                bool match = false;
+                school.period.ForEach(x =>
+                {
+                    if (item.periodId.Equals(x.id))
+                    {
+                        if (x.subjects.Select(y => y.id).Contains(item.subjectId))
+                        {
+                            match = true;
+                        }
+                    }
+                });
+                if (!match)
+                {
+                    unMatch.Add(item);
+                }
+            }
+            if (noGradeIds.IsNotEmpty()) {
+                var ids = noGradeIds.Select(x => x.id);
+                await client.GetContainer("TEAMModelOS", "School").DeleteItemsAsync<ItemInfo>(ids.ToList(), $"Item-hbcn");
+                foreach(var rm in noGradeIds)
+                {
+                    items.Remove(rm);
+                }
+            }
+            if (noPeriodId.IsNotEmpty())
+            {
+                var ids = noPeriodId.Select(x => x.id);
+                await client.GetContainer("TEAMModelOS", "School").DeleteItemsAsync<ItemInfo>(ids.ToList(), $"Item-hbcn");
+                foreach (var rm in noPeriodId)
+                {
+                    items.Remove(rm);
+                }
+            }
+            if (noSubjectId.IsNotEmpty())
+            {
+                var ids = noSubjectId.Select(x => x.id);
+                await client.GetContainer("TEAMModelOS", "School").DeleteItemsAsync<ItemInfo>(ids.ToList(), $"Item-hbcn");
+                foreach (var rm in noSubjectId)
+                {
+                    items.Remove(rm);
+                }
+            }
+            if (unMatch.IsNotEmpty())
+            {
+                var ids = unMatch.Select(x => x.id);
+                await client.GetContainer("TEAMModelOS", "School").DeleteItemsAsync<ItemInfo>(ids.ToList(), $"Item-hbcn");
+                foreach (var rm in unMatch)
+                {
+                    items.Remove(rm);
+                }
+            }
+            List<ItemCond> itemConds = new List<ItemCond>();
+            items.GroupBy(x => x.periodId).Select(y => new { key = y.Key, list = y.ToList() }).ToList().ForEach(z =>
+            {
+                ItemCond cond = new ItemCond() { id = z.key, code = $"ItemCond-hbcn", pk = "ItemCond", ttl = -1, count = z.list.Count, grades = new List<GradeCount>(), subjects = new List<SubjectCount>() };
+                z.list.ForEach(y =>
+                {
+                    ItemService.CountItemCond(y, null, cond);
+                });
+                itemConds.Add(cond);
+            });
+            itemConds.ForEach(async cond =>
+            {
+                await client.GetContainer("TEAMModelOS", "School").UpsertItemAsync<ItemCond>(cond, new PartitionKey(cond.code));
+            });
+            return Ok(new { noGradeIds, itemConds });
+        }
+
         /// <summary>
         /// 修复名单的scope,school,creatorid
         /// </summary>