CrazyIter_Bin 3 年之前
父節點
當前提交
f248f086c4

+ 2 - 0
TEAMModelAPI/ApiTokenAttribute.cs

@@ -108,6 +108,7 @@ namespace TEAMModelOS.Filter
                         id = jwt.Payload.Sub;//主题,又是应用APP
                         school = jwt.Payload.Azp;//学校编码
                         jti = jwt.Payload.Jti;//jwt唯一标识
+#if DEBUG
                         var permissions = jwt.Claims.Where(c => c.Type.Equals("auth"));
                         ///当前请求的api的设置的permission值是否包含在 从jwt的获取["1","2","3","4","5"]值中
                         if (!string.IsNullOrWhiteSpace(_auth) && permissions.Count() > 0)
@@ -117,6 +118,7 @@ namespace TEAMModelOS.Filter
                                 pass = true;
                             }
                         }
+#endif
 
                         if (!string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(school) && !string.IsNullOrEmpty(jti))
                         {

+ 263 - 9
TEAMModelAPI/Controllers/School/GroupListController.cs

@@ -63,7 +63,7 @@ namespace TEAMModelAPI.Controllers
         /// <returns></returns>
         [ProducesDefaultResponseType]
         [HttpPost("get-group-list")]
-        [ApiToken(Auth = "109", Name = "学校教师列表", RW = "R", Limit = false)]
+        [ApiToken(Auth = "109", Name = "学校名单列表", RW = "R", Limit = false)]
         public async Task<IActionResult> GetGroupList(JsonElement json)
         {
             var client = _azureCosmos.GetCosmosClient();
@@ -179,7 +179,7 @@ namespace TEAMModelAPI.Controllers
         /// <returns></returns>
         [ProducesDefaultResponseType]
         [HttpPost("import-class-members")]
-        [ApiToken(Auth = "112", Name = "导入行政班学生", RW = "W", Limit = false)]
+        [ApiToken(Auth = "111", Name = "导入行政班学生", RW = "W", Limit = false)]
         public async Task<IActionResult> ImportClassMembers(JsonElement json)
         {
             var (id, school) = HttpContext.GetApiTokenInfo();
@@ -192,10 +192,10 @@ namespace TEAMModelAPI.Controllers
                 if (period != null)
                 {
                     List<Student> webStudents = _students.ToObject<List<Student>>();
-                    List<Student> preStudents = await StudentService.GeStudentData(_azureCosmos, school, webStudents);
+                    List<Student> preStudents = await StudentService.GeStudentData(_azureCosmos, school, webStudents?.Select(x=>x.id));
                     var retUpsert = await StudentService.upsertStudents(_azureCosmos, _dingDing, _option, school, json.GetProperty("students").EnumerateArray());
                     await StudentService.CheckStudent(_serviceBus, _configuration, _azureCosmos, school, webStudents, preStudents);
-                    return this.Ok(new { code = $"Base-{school}", students = retUpsert.studs, retUpsert.classDuplNos, retUpsert.errorIds });
+                    return this.Ok(new { code = $"{school}", students = retUpsert.studs, retUpsert.classDuplNos, retUpsert.errorIds });
                 }
                 else 
                 {
@@ -205,6 +205,128 @@ namespace TEAMModelAPI.Controllers
             else {
                 return Ok(new { error = 1, msg = "学生列表格式错误" });
             }
+        }
+        /// <summary>
+        ///更新學生資料,批量密碼重置,基本資訊更新(姓名、教室ID、性別、學年及座號)
+        /// </summary>
+        /// <param name="request"></param>
+        /// <returns></returns>
+        [ProducesDefaultResponseType]
+        [HttpPost("update-class-members")]
+        [ApiToken(Auth = "112", Name = "更新行政班学生", RW = "W", Limit = false)]
+        public async Task<IActionResult> UpdateClassMembers(JsonElement json)
+        {
+            var (id, school) = HttpContext.GetApiTokenInfo();
+            if (!json.TryGetProperty("periodId", out JsonElement _periodId)) { return Ok(new { error = 2, msg = "学段信息错误!" }); }
+            if (json.TryGetProperty("students", out JsonElement _students)) { return Ok(new { error = 1, msg = "学生列表格式错误!" }); }
+            if (_students.ValueKind.Equals(JsonValueKind.Array))
+            {
+                School data = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(school, new PartitionKey("Base"));
+                Period period = data.period.Find(x => x.id.Equals($"{_periodId}"));
+                if (period != null)
+                {
+                    //更新學生資料,批量密碼重置,基本資訊更新(姓名、教室ID、性別、學年及座號)
+                    List<Student> webStudents = json.GetProperty("students").ToObject<List<Student>>();
+                    List<Student> preStudents = await StudentService.GeStudentData(_azureCosmos, school, webStudents?.Select(x => x.id));
+                    var retUpdate = await StudentService.updateStudents(_azureCosmos, _dingDing, _option, school, json.GetProperty("students").EnumerateArray());
+                    await StudentService.CheckStudent(_serviceBus, _configuration, _azureCosmos, school, webStudents, preStudents);
+                    return this.Ok(new { code = school, students = retUpdate.studs, retUpdate.classDuplNos, retUpdate.nonexistentIds, retUpdate.errorNos, retUpdate.errorClassId });
+                }
+                else
+                {
+                    return Ok(new { error = 2, msg = "学段信息错误!" });
+                }
+            }
+            else
+            {
+                return Ok(new { error = 1, msg = "学生列表格式错误" });
+            }
+        }
+        /// <summary>
+        ////將學生基本資料內的classId、no、groupId及groupName寫入null
+        /// </summary>
+        /// <param name="request"></param>
+        /// <returns></returns>
+        [ProducesDefaultResponseType]
+        [HttpPost("remove-class-members")]
+        [ApiToken(Auth = "113", Name = "移除行政班学生", RW = "W", Limit = false)]
+        public async Task<IActionResult> RemoveClassMembers(JsonElement json)
+        {
+            var (id, school) = HttpContext.GetApiTokenInfo();
+            if (!json.TryGetProperty("periodId", out JsonElement _periodId)) { return Ok(new { error = 2, msg = "学段信息错误!" }); }
+            if (json.TryGetProperty("students", out JsonElement _students)) { return Ok(new { error = 1, msg = "学生列表格式错误!" }); }
+            if (_students.ValueKind.Equals(JsonValueKind.Array))
+            {
+                School data = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(school, new PartitionKey("Base"));
+                Period period = data.period.Find(x => x.id.Equals($"{_periodId}"));
+                if (period != null)
+                {
+                    //將學生基本資料內的classId、no、groupId及groupName寫入null
+                    List<string> stus = json.GetProperty("students").ToObject<List<string>>();
+                    List<Student> webStudents = new List<Student>();
+                    foreach (string idstu in stus)
+                    {
+                        webStudents.Add(new Student { id = idstu, code = $"Base-{school}" });
+                    }
+                    List<Student>  preStudents = await StudentService.GeStudentData(_azureCosmos, school, webStudents?.Select(x => x.id));
+                    (List<string> studs, List<string> nonexistentIds, List<string> errorIds) retRemove = await StudentService.removeStudentClassInfo(    _azureCosmos, _dingDing, _option,school, json.GetProperty("students").EnumerateArray());
+                    await StudentService.CheckStudent(_serviceBus, _configuration, _azureCosmos, school, webStudents, preStudents);
+                    return Ok(new { code = $"{school}", ids = retRemove.studs, retRemove.nonexistentIds, retRemove.errorIds });
+                }
+                else
+                {
+                    return Ok(new { error = 2, msg = "学段信息错误!" });
+                }
+            }
+            else
+            {
+                return Ok(new { error = 1, msg = "学生列表格式错误" });
+            }
+        }
+
+        /// <summary>
+        /// 创建或更新教学班
+        /// </summary>
+        /// <param name="request"></param>
+        /// <returns></returns>
+        [ProducesDefaultResponseType]
+        [HttpPost("upsert-teach-group")]
+        [ApiToken(Auth = "114", Name = "创建或更新教学班", RW = "W", Limit = false)]
+        public async Task<IActionResult> UpsertTeachGroup(JsonElement json) {
+            var (id, school) = HttpContext.GetApiTokenInfo();
+            if (!json.TryGetProperty("groupList", out JsonElement _groupList)) { return Ok(new { error=1,msg="名单对象不存在"}); }
+            var list= _groupList.ToObject<GroupListDto>();
+            if (list != null  && list.Valid().isVaild) {
+                if (string.IsNullOrWhiteSpace(list.id))
+                {
+                    GroupList groupList = new GroupList()
+                    {
+                        id=Guid.NewGuid ().ToString(),
+                        code=$"GroupList-{school}",
+                        name=list.name,
+                        periodId=list.periodId,
+                        scope="school",
+                        school=school,
+                        type="teach",
+                        year=list.year,
+                        from=3
+                    };
+                    groupList = await GroupListService.CheckListNo(groupList, _azureCosmos, _dingDing, _option);
+                    
+                }
+                else {
+                    Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{list.id}", new PartitionKey($"GroupList-{school}"));
+                    if (response.Status==200)
+                    {
+                        JsonDocument jsonDocument = JsonDocument.Parse(response.Content);
+                        var groupList = jsonDocument.RootElement.ToObject<GroupList>();
+                        groupList.name=string.IsNullOrWhiteSpace(list.name)?groupList.name: list.name;
+                        
+                    }
+                    else { 
+                    }
+                }
+            }
             return Ok();
         }
 
@@ -215,14 +337,146 @@ namespace TEAMModelAPI.Controllers
         /// <returns></returns>
         [ProducesDefaultResponseType]
         [HttpPost("import-teach-members")]
-        [ApiToken(Auth = "111", Name = "导入教学班学生", RW = "W", Limit = false)]
+        [ApiToken(Auth = "115", Name = "导入教学班学生", RW = "W", Limit = false)]
         public async Task<IActionResult> ImportTeachMembers(JsonElement json)
         {
-            json.TryGetProperty("periodId", out JsonElement _periodId);
-            json.TryGetProperty("students", out JsonElement _students);
             var (id, school) = HttpContext.GetApiTokenInfo();
-            School data = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(school, new PartitionKey("Base"));
-            return Ok();
+            if (!json.TryGetProperty("groupId", out JsonElement _groupId)) {    return Ok(new { error = 2, msg = "名单错误!" }); } 
+            if(!json.TryGetProperty("members", out JsonElement _members)) return Ok(new { error = 1, msg = "名单列表格式错误" });
+            if (_members.ValueKind.Equals(JsonValueKind.Array))
+            {
+                //School data = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(school, new PartitionKey("Base"));
+                List<Member> members = _members.ToObject<List<Member>>();
+                ValidResult valid = members.Valid();
+                if (valid.isVaild)
+                {
+                    var tmds = members.Where(x => x.type == 1);
+                    var stus = members.Where(x => x.type == 2);
+                    List<Student> students = await StudentService.GeStudentData(_azureCosmos, school, stus?.Select(x => x.id));
+                    List<TmdInfo> infos = null;
+                    string tmdstr = "";
+                    try
+                    {
+                        var content = new StringContent(tmds.Select(x => x.id).ToJsonString(), Encoding.UTF8, "application/json");
+                        tmdstr = await _coreAPIHttpService.GetUserInfos(content);
+                        infos = tmdstr.ToObject<List<TmdInfo>>();
+                    }
+                    catch (Exception ex)
+                    {
+                        await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.Get("Default").location}用户转换失败:{_coreAPIHttpService.options.Get("Default").url}{tmdstr}\n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
+                        //return Ok(new { error =3, msg = "醍摩豆ID验证错误!" });
+                    }
+                    var unexist_student = stus.Select(x => x.id).Except(students.Select(y => y.id));
+                    var unexist_tmdids = tmds.Select(x => x.id).Except(infos.Select(y => y.id));
+                    Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{_groupId}", new PartitionKey($"GroupList-{school}"));
+                    if (response.Status == 200)
+                    {
+                        JsonDocument jsonDocument = JsonDocument.Parse(response.Content);
+                        var list =  jsonDocument.RootElement.ToObject<GroupList>();
+                        if (list.type.Equals("teach") && list.school.Equals(school))
+                        {
+                            if (infos.Any())
+                            {
+                                infos.ToList().ForEach(x => {
+                                    if (!list.members.Where(z => z.type == 1).Select(x => x.id).Contains(x.id))
+                                    {
+                                        GroupListService.JoinList(list, x.id , 1 , school);
+                                    }
+                                });
+                            }
+                            if (stus.Any()) 
+                            {
+                                stus.ToList().ForEach(x => {
+                                    if (!list.members.Where(z => z.type == 2).Select(x => x.id).Contains(x.id)) {
+                                        GroupListService.JoinList(list, x.id ,2 , school);
+                                    }    
+                                });
+                            }
+                            list = await GroupListService.CheckListNo(list, _azureCosmos, _dingDing, _option);
+                            list = await GroupListService.UpsertList(list, _azureCosmos, _configuration, _serviceBus);
+                            return Ok(new { unexist_student, unexist_tmdids, import_list=list });
+                        }
+                        else {
+                            return Ok(new { error = 3, msg = $"名单类型不是教学班或者不是当前学校的名单!{list.type},{list.school}" });
+                        }
+                    }
+                    else
+                    {
+                        return Ok(new { error = 2, msg = "名单错误!" });
+                    }
+                }
+                else
+                {
+                    return Ok(new { error = valid, msg = "名单列表格式错误!" });
+                }
+            }
+            else
+            {
+                return Ok(new { error = 1, msg = "名单列表格式错误" });
+            }
+        }
+
+        /// <summary>
+        /// 导入教学班学生
+        /// </summary>
+        /// <param name="request"></param>
+        /// <returns></returns>
+        [ProducesDefaultResponseType]
+        [HttpPost("remove-teach-members")]
+        [ApiToken(Auth = "116", Name = "移除教学班学生", RW = "W", Limit = false)]
+        public async Task<IActionResult> RemoveTeachMembers(JsonElement json) {
+            var (id, school) = HttpContext.GetApiTokenInfo();
+            json.TryGetProperty("stuids", out JsonElement _stuids);
+            json.TryGetProperty("tmdids", out JsonElement _tmdids);
+            if (json.TryGetProperty("groupId", out JsonElement _groupId)) { return Ok(new { error = 1, msg = "名单错误!" }); }
+            List<string> stuids = null;
+            if (_stuids.ValueKind.Equals(JsonValueKind.Array)) {
+                stuids = _stuids.ToObject<List<string>>();
+            }
+            List<string> tmdids = null;
+            if (_tmdids.ValueKind.Equals(JsonValueKind.Array))
+            {
+                tmdids = _tmdids.ToObject<List<string>>();
+            }
+            if (tmdids.Any() || stuids.Any())
+            {
+                // School data = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(school, new PartitionKey("Base"));
+                Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{_groupId}", new PartitionKey($"GroupList-{school}"));
+                if (response.Status == 200)
+                { 
+                    JsonDocument document= JsonDocument.Parse(response.Content);
+                    var  list= document.RootElement.Deserialize<GroupList>();
+                    List<string> remove_tmdids = new List<string>();
+                    if (tmdids.Any()) {
+                        tmdids.ForEach(x => {
+                            int len= list.members.RemoveAll(z => z.id.Equals(x) && z.type == 1);
+                            if (len > 0) {
+                                remove_tmdids.Add(x);
+                            }
+                        });
+                    }
+                    List<string> remove_stuids = new List<string>();
+                    if (stuids.Any())
+                    {
+                        stuids.ForEach(x => {
+                            int len = list.members.RemoveAll(z => z.id.Equals(x) && z.type == 2);
+                            if (len > 0)
+                            {
+                                remove_stuids.Add(x);
+                            }
+                        });
+                    }
+                    list = await GroupListService.UpsertList(list, _azureCosmos, _configuration, _serviceBus);
+                    return Ok(new { remove_stuids, remove_tmdids, list });
+                }
+                else {
+                    return Ok(new { error = 2, msg = "名单错误!" });
+                }
+            }
+            else 
+            {
+                 return Ok(new { error = 2, msg = "移除的名单人员为空!" }); 
+            }
         }
     }
 }

+ 1 - 1
TEAMModelOS.SDK/Extension/JwtAuthExtension.cs

@@ -14,7 +14,7 @@ namespace TEAMModelOS.SDK.Extension
 {
     public static class JwtAuthExtension
     {
-        public static string CreateAuthToken(string issuer, string id, string name, string picture, string salt, string scope,string Website, string schoolID = "", string standard = "", string[] roles = null, string[] permissions = null, int expire = 1, string[] ddDepts = null, string ddsub = null)
+        public static string CreateAuthToken(string issuer, string id, string name, string picture, string salt, string scope,string Website, string schoolID = "", string standard = "", string[] roles = null, string[] permissions = null, int expire = 1)
         {
             // 設定要加入到 JWT Token 中的聲明資訊(Claims)  
             var payload = new JwtPayload {

+ 1 - 1
TEAMModelOS.SDK/Helper/Common/ValidatorHelper/ValidatorHelper.cs

@@ -8,7 +8,7 @@ namespace TEAMModelOS.SDK
 {
     public static class ValidatorHelper
     {
-        public static ValidResult IsValid(this Object obj) {
+        public static ValidResult Valid(this Object obj) {
             ValidResult result = new ValidResult();
             try {
                 var context = new ValidationContext(obj, null, null);

+ 13 - 2
TEAMModelOS.SDK/Models/Cosmos/Common/GroupList.cs

@@ -1,5 +1,6 @@
 using System;
 using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
 using System.Text;
 
 namespace TEAMModelOS.SDK.Models
@@ -37,7 +38,7 @@ namespace TEAMModelOS.SDK.Models
         /// <summary>
         /// 名单创建来源,0 默认,1 个人 ,2 学校,3 校内应用,4企业应用
         /// </summary>
-        public string from { get; set; }
+        public int from { get; set; } = 0;
     }
     public class RGroupList
     {
@@ -74,7 +75,8 @@ namespace TEAMModelOS.SDK.Models
         public int scount { get; set; }
         public List<RMember> members { get; set; } = new List<RMember>();
         public string leader { get; set; }
-        
+        public int from { get; set; } = 0;
+
     }
 
     public class  Member
@@ -82,12 +84,14 @@ namespace TEAMModelOS.SDK.Models
         /// <summary>
         /// 账号id
         /// </summary>
+        [Required(ErrorMessage = "{0} 名单的ID  必须填写")]
         public string id { get; set; }
         //学生所在的学校
         public string code { get; set; }
         /// <summary>
         ///类型 1 tmdid,2 student
         /// </summary>
+        [Range(1, 2)]
         public int type { get; set; }
         /// <summary>
         ///座号
@@ -101,6 +105,7 @@ namespace TEAMModelOS.SDK.Models
         public string groupId { get; set; }
         public string groupName { get; set; }
     }
+    
     public class RMember
     {
         /// <summary>
@@ -194,16 +199,20 @@ namespace TEAMModelOS.SDK.Models
         public int scount { get; set; }
         public string leader { get; set; }
         public HashSet<string> groupName { get; set; }
+        public int from { get; set; } = 0;
     }
    
     public class GroupListDto
     {
         public string pk { get; set; }
         public string id { get; set; }
+       
         public string code { get; set; }
+        [Required(ErrorMessage = "{0} 名单的名称必须填写")]
         public string name { get; set; }
         //标记该名单唯一code
         public string no { get; set; }
+        [Required(ErrorMessage = "{0} 名单的学段必须填写")]
         public string periodId { get; set; }
         //课程id,需要标记则标记
         //public string courseId { get; set; }
@@ -214,6 +223,7 @@ namespace TEAMModelOS.SDK.Models
         ///教学班teach ,行政班(学生搜寻classId动态返回)class ,教研组research,学科组(学科搜寻动态返回)subject,好友friend,管理manage,群组group等
         /// </summary>
         public string type { get; set; } = "teach";
+        [Range(2000, 3000)]
         public int year { get; set; }
         /// <summary>
         /// 醍摩豆id成员数量
@@ -224,6 +234,7 @@ namespace TEAMModelOS.SDK.Models
         /// </summary>
         public int scount { get; set; }
         public string leader { get; set; }
+        public int from { get; set; } = 0;
     }
     public class CourseGroupList
     {

+ 4 - 4
TEAMModelOS.SDK/Models/Service/StudentService.cs

@@ -26,12 +26,12 @@ namespace TEAMModelOS.SDK
         /// <param name="schoolId"></param>
         /// <param name="students"></param>
         /// <returns></returns>
-        public static async Task<List<Student>> GeStudentData(AzureCosmosFactory _azureCosmos ,string schoolId, List<Student> students)
+        public static async Task<List<Student>> GeStudentData(AzureCosmosFactory _azureCosmos ,string schoolId, IEnumerable<string> students)
         {
             List<Student> studentDatas = new List<Student>();
-            if (students.IsNotEmpty())
+            if (students.Any())
             {
-                string queryText = $"SELECT c.id, c.code ,c.classId  FROM c  WHERE c.id IN ({string.Join(",", students.Select(o => $"'{o.id}'"))})";
+                string queryText = $"SELECT c.id, c.code ,c.classId  FROM c  WHERE c.id IN ({string.Join(",", students.Select(o => $"'{o}'"))})";
                 await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
                 {
                     studentDatas.Add(item);
@@ -51,7 +51,7 @@ namespace TEAMModelOS.SDK
         /// <returns></returns>
         public static async Task<Dictionary<string, GroupChange>> CheckStudent(AzureServiceBusFactory _serviceBus,IConfiguration _configuration,AzureCosmosFactory _azureCosmos, string schoolId, List<Student> students, List<Student> prestudents)
         {
-            List<Student> aftstudents = await StudentService.GeStudentData(_azureCosmos, schoolId, students);
+            List<Student> aftstudents = await StudentService.GeStudentData(_azureCosmos, schoolId, students?.Select(x => x.id));
             Dictionary<string, GroupChange> dictChange = new Dictionary<string, GroupChange>();
             if (prestudents.Count >= aftstudents.Count)
             {

+ 3 - 0
TEAMModelOS/Controllers/Both/SyllabusController.cs

@@ -52,6 +52,7 @@ namespace TEAMModelOS.Controllers
         [ProducesDefaultResponseType]
         [HttpPost("check-link")]
         [Authorize(Roles = "IES")]
+        [AuthToken(Roles = "teacher,admin")]
         public async Task<IActionResult> CheckLink(JsonElement request) {
             if (!request.TryGetProperty("links", out JsonElement _links)) return BadRequest();
             if (!request.TryGetProperty("code", out JsonElement _code)) return BadRequest();
@@ -255,6 +256,7 @@ namespace TEAMModelOS.Controllers
         [ProducesDefaultResponseType]
         [HttpPost("find-id")]
         [Authorize(Roles = "IES")]
+        [AuthToken(Roles = "teacher,admin,student")]
         public async Task<IActionResult> Find(JsonElement request)
         {
             var client = _azureCosmos.GetCosmosClient();
@@ -349,6 +351,7 @@ namespace TEAMModelOS.Controllers
         [ProducesDefaultResponseType]
         [HttpPost("delete")]
         [Authorize(Roles = "IES")]
+        [AuthToken(Roles = "teacher,admin")]
         public async Task<IActionResult> Delete(JsonElement request)
         {
             try

+ 5 - 0
TEAMModelOS/Controllers/Both/VolumeController.cs

@@ -18,6 +18,7 @@ using TEAMModelOS.SDK.Models.Cosmos;
 using TEAMModelOS.SDK.Models.Cosmos.Common;
 using HTEXLib.COMM.Helpers;
 using Microsoft.AspNetCore.Authorization;
+using TEAMModelOS.Filter;
 
 namespace TEAMModelOS.Controllers
 {
@@ -56,6 +57,7 @@ namespace TEAMModelOS.Controllers
         //[AuthToken(Roles = "teacher")]
         [HttpPost("delete")]
         [Authorize(Roles = "IES")]
+        [AuthToken(Roles = "teacher,admin")]
         public async Task<IActionResult> Delete(JsonElement request)
         {
             try
@@ -148,6 +150,7 @@ namespace TEAMModelOS.Controllers
         //[AuthToken(Roles = "teacher")]
         [HttpPost("find")]
         [Authorize(Roles = "IES")]
+        [AuthToken(Roles = "teacher,admin,student")]
         public async Task<IActionResult> Find(JsonElement request) {
             try {
                 List<Volume> volumes = new List<Volume>();
@@ -191,6 +194,7 @@ namespace TEAMModelOS.Controllers
         //[AuthToken(Roles = "teacher")]
         [HttpPost("update-same-property")]
         [Authorize(Roles = "IES")]
+        [AuthToken(Roles = "teacher,admin")]
         public async Task<IActionResult> UpsertSameProperty(JsonElement request) {
             var client = _azureCosmos.GetCosmosClient();
             request.TryGetProperty("code", out JsonElement _code);
@@ -255,6 +259,7 @@ namespace TEAMModelOS.Controllers
         //[AuthToken(Roles = "teacher")]
         [HttpPost("upsert")]
         [Authorize(Roles = "IES")]
+        [AuthToken(Roles = "teacher,admin")]
         public async Task<IActionResult> Upsert(Volume request) {
 
             //var client = _azureCosmos.GetCosmosClient();

+ 1 - 1
TEAMModelOS/Controllers/School/KnowledgesController.cs

@@ -127,7 +127,7 @@ namespace TEAMModelOS.Controllers
             {
                 old_new = _old_new.ToObject<List<OldNew>>();
             }
-            ValidResult validResult = knowledge.IsValid();
+            ValidResult validResult = knowledge.Valid();
             if (!validResult.isVaild)
             {
                 return BadRequest(validResult);

+ 4 - 4
TEAMModelOS/Controllers/Student/StudentController.cs

@@ -152,7 +152,7 @@ namespace TEAMModelOS.Controllers
                     case "import":
                         //只有ClassNo可以比對
                         webStudents = request.GetProperty("students").ToObject<List<Student>>();
-                        preStudents= await StudentService.GeStudentData(_azureCosmos, schoolId.GetString(), webStudents);
+                        preStudents= await StudentService.GeStudentData(_azureCosmos, schoolId.GetString(), webStudents?.Select(x => x.id));
                         var retUpsert = await StudentService.upsertStudents( _azureCosmos, _dingDing, _option, schoolId.GetString(), request.GetProperty("students").EnumerateArray());
                         await CheckStudent( _serviceBus, _configuration, _azureCosmos, schoolId.GetString(), webStudents, preStudents);
                         return this.Ok(new { code = $"Base-{schoolId.GetString()}", students = retUpsert.studs, retUpsert.classDuplNos, retUpsert.errorIds });
@@ -163,14 +163,14 @@ namespace TEAMModelOS.Controllers
                     case "update":
                         //更新學生資料,批量密碼重置,基本資訊更新(姓名、教室ID、性別、學年及座號)
                         webStudents = request.GetProperty("students").ToObject<List<Student>>();
-                        preStudents = await StudentService.GeStudentData(_azureCosmos, schoolId.GetString(), webStudents);
+                        preStudents = await StudentService.GeStudentData(_azureCosmos, schoolId.GetString(), webStudents?.Select(x => x.id));
                         var retUpdate = await   StudentService.updateStudents( _azureCosmos, _dingDing, _option, schoolId.GetString(), request.GetProperty("students").EnumerateArray());
                         await StudentService.CheckStudent( _serviceBus, _configuration, _azureCosmos, schoolId.GetString(), webStudents,  preStudents);
                         return this.Ok(new { code = $"Base-{schoolId.GetString()}", students = retUpdate.studs, retUpdate.classDuplNos, retUpdate.nonexistentIds, retUpdate.errorNos, retUpdate.errorClassId });
                     case "delete":
                         //刪除學生資料及從教室學生名單內移除該學生
                         webStudents = request.GetProperty("students").ToObject<List<Student>>();
-                        preStudents = await StudentService.GeStudentData(_azureCosmos, schoolId.GetString(), webStudents);
+                        preStudents = await StudentService.GeStudentData(_azureCosmos, schoolId.GetString(), webStudents?.Select(x => x.id));
                         var sucDelIds = await StudentService.deleteStudents( _azureCosmos, _dingDing, _option, schoolId.GetString(), request.GetProperty("students").EnumerateArray());
                         await StudentService.CheckStudent( _serviceBus, _configuration, _azureCosmos,schoolId.GetString(), webStudents,  preStudents);
                         return this.Ok(new { code = $"Base-{schoolId.GetString()}", ids = sucDelIds });
@@ -181,7 +181,7 @@ namespace TEAMModelOS.Controllers
                         foreach (string idstu in stus) {
                             webStudents.Add(new Student { id= idstu, code=$"Base-{schoolId}"});
                         }
-                        preStudents = await StudentService.GeStudentData(_azureCosmos, schoolId.GetString(), webStudents);
+                        preStudents = await StudentService.GeStudentData(_azureCosmos, schoolId.GetString(), webStudents?.Select(x => x.id));
                         (List<string> studs, List<string> nonexistentIds, List<string> errorIds) retRemove = await StudentService.removeStudentClassInfo(
                              _azureCosmos, _dingDing, _option, 
                             schoolId.GetString(), request.GetProperty("students").EnumerateArray());

+ 1 - 1
TEAMModelOS/Controllers/Teacher/FavoriteController.cs

@@ -52,7 +52,7 @@ namespace TEAMModelOS.Controllers
             {
                 if (!data.TryGetProperty("favorite", out JsonElement _favorite)) return BadRequest() ;
                 Favorite request = _favorite.ToObject<Favorite>();
-                var val = request.IsValid();
+                var val = request.Valid();
                 if (!val.isVaild  || string.IsNullOrEmpty(request.id)) {
                     return BadRequest(val);
                 }

+ 25 - 0
TEAMModelOS/Controllers/XTest/TestController.cs

@@ -666,6 +666,31 @@ namespace TEAMModelOS.Controllers
            // return Ok(new { activity, ip, token.AccessToken,token.TokenType,token.IdToken, mm });
             return Ok(json);
         }
+
+        /// 删除
+        /// </summary>
+        /// <param name="request"></param>
+        /// <returns></returns>
+        [ProducesDefaultResponseType]
+        [HttpPost("check-online-record")]
+        public async Task<IActionResult> CheckOnlinerecord(JsonElement request)
+        {
+            string sql = $"select c.id,c.name ,b.schoolId as code   from c join b in c.schools where b.areaId='9ae614ba-0771-4502-a56e-0537bc5207c3'";
+            List<IdNameCode> codes = new List<IdNameCode>();
+            await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<IdNameCode>(sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") })) {
+                codes.Add(item);
+            }
+            List<dynamic> data = new List<dynamic>(); ;
+            foreach (IdNameCode code in codes) {
+                try {
+                    TeacherTrain train = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<TeacherTrain>(code.id, new PartitionKey($"TeacherTrain-{code.code}"));
+                    data.Add(new { code.id,code.name,code.code, train.totalTime, train.onlineTime, train.classTime, train.offlineTime });
+                } catch (Exception ex) {
+                    data.Add(new { code.id, code.name, code.code, totalTime=0, onlineTime=0,classTime=0, offlineTime=0 });
+                }
+            }
+            return Ok(new { data });
+        }
     }
 
 }

+ 1 - 0
TEAMModelOS/TEAMModelOS.csproj

@@ -13,6 +13,7 @@
   <ItemGroup>
     <Folder Include="logfile\" />
     <Folder Include="Lib\" />
+    <Folder Include="wwwroot\" />
   </ItemGroup>
 
   <ItemGroup>

+ 23 - 23
TEAMModelOS/appsettings.Development.json

@@ -20,37 +20,37 @@
     //"HttpTrigger": "http://localhost:7071/api/"
   },
   "Azure": {
-    "Storage": {
-      //"ConnectionString": "DefaultEndpointsProtocol=https;AccountName=teammodelstorage;AccountKey=Yq7D4dE6cFuer2d2UZIccTA/i0c3sJ/6ITc8tNOyW+K5f+/lWw9GCos3Mxhj47PyWQgDL8YbVD63B9XcGtrMxQ==;EndpointSuffix=core.chinacloudapi.cn",
-      "ConnectionString": "DefaultEndpointsProtocol=https;AccountName=teammodeltest;AccountKey=O2W2vadCqexDxWO+px+QK7y1sHwsYj8f/WwKLdOdG5RwHgW/Dupz9dDUb4c1gi6ojzQaRpFUeAAmOu4N9E+37A==;EndpointSuffix=core.chinacloudapi.cn"
-    },
-    "Cosmos": {
-      //"ConnectionString": "AccountEndpoint=https://teammodel.documents.azure.com:443/;AccountKey=opemBAZi0yATewIlhxDYoIEUqncT5qJh3pUBZsBkTqEkuLYTuu3VS7oaDGJlPp8ASwm5SVSrK2caJsjgmqRw9g==;"
-      "ConnectionString": "AccountEndpoint=https://cdhabookdep-free.documents.azure.cn:443/;AccountKey=JTUVk92Gjsx17L0xqxn0X4wX2thDPMKiw4daeTyV1HzPb6JmBeHdtFY1MF1jdctW1ofgzqkDMFOtcqS46by31A==;"
-    },
-    "Redis": {
-      "ConnectionString": "52.130.252.100:6379,password=habook,ssl=false,abortConnect=False,writeBuffer=10240"
-    },
-    "ServiceBus": {
-      "ConnectionString": "Endpoint=sb://teammodelos.servicebus.chinacloudapi.cn/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=Sy4h4EQ8zP+7w/lOLi1X3tGord/7ShFHimHs1vC50Dc=",
-      "ActiveTask": "dep-active-task",
-      "ItemCondQueue": "dep-itemcond"
-    }
-
     //"Storage": {
-    //  "ConnectionString": "DefaultEndpointsProtocol=https;AccountName=teammodelos;AccountKey=Dl04mfZ9hE9cdPVO1UtqTUQYN/kz/dD/p1nGvSq4tUu/4WhiKcNRVdY9tbe8620nPXo/RaXxs+1F9sVrWRo0bg==;EndpointSuffix=core.chinacloudapi.cn"
+    //  //"ConnectionString": "DefaultEndpointsProtocol=https;AccountName=teammodelstorage;AccountKey=Yq7D4dE6cFuer2d2UZIccTA/i0c3sJ/6ITc8tNOyW+K5f+/lWw9GCos3Mxhj47PyWQgDL8YbVD63B9XcGtrMxQ==;EndpointSuffix=core.chinacloudapi.cn",
+    //  "ConnectionString": "DefaultEndpointsProtocol=https;AccountName=teammodeltest;AccountKey=O2W2vadCqexDxWO+px+QK7y1sHwsYj8f/WwKLdOdG5RwHgW/Dupz9dDUb4c1gi6ojzQaRpFUeAAmOu4N9E+37A==;EndpointSuffix=core.chinacloudapi.cn"
     //},
     //"Cosmos": {
-    //  "ConnectionString": "AccountEndpoint=https://teammodelos.documents.azure.cn:443/;AccountKey=clF73GwPECfP1lKZTCvs8gLMMyCZig1HODFbhDUsarsAURO7TcOjVz6ZFfPqr1HzYrfjCXpMuVD5TlEG5bFGGg==;"
+    //  //"ConnectionString": "AccountEndpoint=https://teammodel.documents.azure.com:443/;AccountKey=opemBAZi0yATewIlhxDYoIEUqncT5qJh3pUBZsBkTqEkuLYTuu3VS7oaDGJlPp8ASwm5SVSrK2caJsjgmqRw9g==;"
+    //  "ConnectionString": "AccountEndpoint=https://cdhabookdep-free.documents.azure.cn:443/;AccountKey=JTUVk92Gjsx17L0xqxn0X4wX2thDPMKiw4daeTyV1HzPb6JmBeHdtFY1MF1jdctW1ofgzqkDMFOtcqS46by31A==;"
     //},
     //"Redis": {
-    //  "ConnectionString": "CoreRedisCN.redis.cache.chinacloudapi.cn:6380,password=LyJWP1ORJdv+poXWofAF97lhCEQPg1wXWqvtzXGXQuE=,ssl=True,abortConnect=False"
+    //  "ConnectionString": "52.130.252.100:6379,password=habook,ssl=false,abortConnect=False,writeBuffer=10240"
     //},
     //"ServiceBus": {
-    //  "ConnectionString": "Endpoint=sb://coreiotservicebuscnpro.servicebus.chinacloudapi.cn/;SharedAccessKeyName=TEAMModelOS;SharedAccessKey=llRPBMDJG9w1Nnifj+pGhV0g4H2REcq0PjvX2qqpcOg=",
-    //  "ActiveTask": "active-task",
-    //  "ItemCondQueue": "itemcond"
+    //  "ConnectionString": "Endpoint=sb://teammodelos.servicebus.chinacloudapi.cn/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=Sy4h4EQ8zP+7w/lOLi1X3tGord/7ShFHimHs1vC50Dc=",
+    //  "ActiveTask": "dep-active-task",
+    //  "ItemCondQueue": "dep-itemcond"
     //}
+
+    "Storage": {
+      "ConnectionString": "DefaultEndpointsProtocol=https;AccountName=teammodelos;AccountKey=Dl04mfZ9hE9cdPVO1UtqTUQYN/kz/dD/p1nGvSq4tUu/4WhiKcNRVdY9tbe8620nPXo/RaXxs+1F9sVrWRo0bg==;EndpointSuffix=core.chinacloudapi.cn"
+    },
+    "Cosmos": {
+      "ConnectionString": "AccountEndpoint=https://teammodelos.documents.azure.cn:443/;AccountKey=clF73GwPECfP1lKZTCvs8gLMMyCZig1HODFbhDUsarsAURO7TcOjVz6ZFfPqr1HzYrfjCXpMuVD5TlEG5bFGGg==;"
+    },
+    "Redis": {
+      "ConnectionString": "CoreRedisCN.redis.cache.chinacloudapi.cn:6380,password=LyJWP1ORJdv+poXWofAF97lhCEQPg1wXWqvtzXGXQuE=,ssl=True,abortConnect=False"
+    },
+    "ServiceBus": {
+      "ConnectionString": "Endpoint=sb://coreiotservicebuscnpro.servicebus.chinacloudapi.cn/;SharedAccessKeyName=TEAMModelOS;SharedAccessKey=llRPBMDJG9w1Nnifj+pGhV0g4H2REcq0PjvX2qqpcOg=",
+      "ActiveTask": "active-task",
+      "ItemCondQueue": "itemcond"
+    }
   },
   "HaBookAuth": {
     "CoreId": {