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

+ 0 - 63
TEAMModelAPI/Controllers/School/SchoolController.cs

@@ -74,69 +74,6 @@ namespace TEAMModelAPI.Controllers
             });
         }
 
-        /// <summary>
-        ///  获取学校教师列表
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        [HttpGet("get-teacher-list")]
-        [ApiToken(Auth = "1002", Name = "学校教师列表", RW = "R", Limit = false)]
-        public async Task<IActionResult> GetTeacherList()
-        {
-            var (id, school) = HttpContext.GetApiTokenInfo();
-            List<dynamic> teachers= new List<dynamic>();
-            string sql = $"select c.id,c.name ,c.picture,c.job ,c.subjectIds,c.roles from c where c.status='join' ";
-            await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<dynamic>
-                (queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Teacher-{school}") })) {
-                teachers.Add(item);
-            }
-            return Ok(new
-            {
-                teachers
-            });
-        }
-        /// <summary>
-        /// 获取学校教师信息
-        /// </summary>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        [HttpPost("get-teacher-info")]
-        [ApiToken(Auth = "1003", Name = "学校教师信息", RW = "R", Limit = false)]
-        public async Task<IActionResult> GetTeacherInfo(JsonElement json )
-        {
-            json.TryGetProperty("tmdid", out JsonElement _tmdid);
-            var (id, school) = HttpContext.GetApiTokenInfo();
-            Azure.Response responseSchoolTch =await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
-                .ReadItemStreamAsync($"{_tmdid}", new PartitionKey($"Teacher-{school}"));
-            Azure.Response responseTch = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher")
-                 .ReadItemStreamAsync($"{_tmdid}", new PartitionKey($"Base"));
-            Teacher teacher = null;
-            if (responseTch.Status == 200)
-            {
-                teacher = JsonDocument.Parse(responseTch.Content).RootElement.Deserialize<Teacher>();
-            }
-            else
-            {
-                return Ok(new { error = 3, msg = "账号未创建!" });
-            }
-            if (responseSchoolTch.Status == 200 && teacher!= null )
-            {
-                SchoolTeacher schoolTeacher= JsonDocument.Parse(responseSchoolTch.Content).RootElement.Deserialize<SchoolTeacher>();
-                if (schoolTeacher.status.Equals("join"))
-                {
-                    return Ok(new {teacher.id,teacher.name,teacher.picture,schoolTeacher.job,schoolTeacher.status,schoolTeacher.roles,schoolTeacher.subjectIds, school=teacher.schools?.Find(x=>x.schoolId.Equals(school)) } );
-                }
-                else
-                {
-                    return Ok(new { error = 2, msg = "教师未加入学校!" });
-                }
-
-            }
-            else {
-                return Ok(new { error = 1, msg = "教师未就职该学校!" });
-            }
-        }
        
       
        

+ 156 - 0
TEAMModelAPI/Controllers/School/TeacherController.cs

@@ -0,0 +1,156 @@
+using Azure.Cosmos;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Options;
+using System;
+using System.Collections.Generic;
+using System.IdentityModel.Tokens.Jwt;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Text.Json;
+using System.Threading.Tasks;
+using TEAMModelOS.Models;
+using TEAMModelOS.Models.Dto;
+using TEAMModelOS.SDK.Models;
+using TEAMModelOS.SDK;
+using TEAMModelOS.SDK.DI;
+using TEAMModelOS.SDK.DI.AzureCosmos.Inner;
+using TEAMModelOS.SDK.Extension;
+using TEAMModelOS.SDK.Helper.Common.StringHelper;
+using System.Dynamic;
+using Azure;
+using TEAMModelOS.SDK.Models.Cosmos.Common;
+using Azure.Messaging.ServiceBus;
+using Microsoft.Extensions.Configuration;
+using TEAMModelOS.Filter;
+using Azure.Storage.Blobs.Models;
+using HTEXLib.COMM.Helpers;
+using Microsoft.AspNetCore.Authorization;
+using System.Net.Http;
+
+namespace TEAMModelAPI.Controllers
+{
+    [Route("school")]
+    [ApiController]
+    public class TeacherController : ControllerBase
+    {
+        private AzureCosmosFactory _azureCosmos;
+        private readonly DingDing _dingDing;
+        private readonly Option _option;
+        private readonly AzureServiceBusFactory _serviceBus;
+        private readonly AzureStorageFactory _azureStorage;
+        public IConfiguration _configuration { get; set; }
+        private readonly CoreAPIHttpService _coreAPIHttpService;
+        public TeacherController(CoreAPIHttpService coreAPIHttpService, AzureCosmosFactory azureCosmos, DingDing dingDing, IOptionsSnapshot<Option> option, AzureServiceBusFactory serviceBus, AzureStorageFactory azureStorage, IConfiguration configuration)
+        {
+            _azureCosmos = azureCosmos;
+            _dingDing = dingDing;
+            _option = option?.Value;
+            _serviceBus = serviceBus;
+            _configuration = configuration;
+            _azureStorage = azureStorage;
+            _coreAPIHttpService = coreAPIHttpService;
+        }
+
+        /// <summary>
+        ///  获取学校教师列表
+        /// </summary>
+        /// <param name="request"></param>
+        /// <returns></returns>
+        [ProducesDefaultResponseType]
+        [HttpGet("get-teacher-list")]
+        [ApiToken(Auth = "1501", Name = "学校教师列表", RW = "R", Limit = false)]
+        public async Task<IActionResult> GetTeacherList(JsonElement json)
+        {
+            
+            json.TryGetProperty("searchKey", out JsonElement _searchKey);
+            List<CoreUser> coreUsers = new List<CoreUser>();
+            IEnumerable<string> unexist = null ;
+            if (_searchKey.ValueKind.Equals(JsonValueKind.Array))
+            {
+                List<string> searchKey= _searchKey.ToObject<List<string>>();
+                var keys = searchKey.Where(x => !string.IsNullOrWhiteSpace(x));
+                var content = new StringContent(keys.ToJsonString(), Encoding.UTF8, "application/json");
+                string ujson = await _coreAPIHttpService.GetUserInfos(content);
+                if (!string.IsNullOrWhiteSpace(ujson))
+                {
+                    coreUsers = ujson.ToObject<List<CoreUser>>();
+                }
+                if (coreUsers.Any())
+                {
+                    unexist = searchKey.Except(coreUsers.Select(x => x.searchKey));
+                }
+                else {
+                    return Ok(new { error = 1, msg = "没有找到对应的教师信息!" });
+                }
+            }
+           
+         
+            var (id, school) = HttpContext.GetApiTokenInfo();
+            List<SchoolTeacher> teachers = new List<SchoolTeacher>();
+            string insql = "";
+            if (coreUsers.Any()) {
+                 insql = $" and c.id in  ({string.Join(",", coreUsers.Select(x => $"'{ x.id}'"))}) ";
+            }
+            string sql = $"select c.id,c.name ,c.picture,c.job ,c.subjectIds,c.roles from c where c.status='join' {insql}";
+            await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<SchoolTeacher>
+                (queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Teacher-{school}") }))
+            {
+                teachers.Add(item);
+            }
+            var teacherIds=   coreUsers.Select(x => x.id).Except(teachers.Select(x => x.id));
+            List<CoreUser> unjoined = coreUsers.FindAll(x => teacherIds.Contains(x.id));
+            
+            return Ok(new
+            {
+                teachers = teachers.Select(x => new {x.id,x.name,x.picture,x.job,x.subjectIds,x.roles }),
+                unjoined= unjoined.Select(x => new {x.id,x.name,x.picture,x.searchKey}),
+                unexist= unexist
+            }); 
+        }
+        /// <summary>
+        /// 获取学校教师信息
+        /// </summary>
+        /// <returns></returns>
+        [ProducesDefaultResponseType]
+        [HttpPost("get-teacher-info")]
+        [ApiToken(Auth = "1502", Name = "学校教师信息", RW = "R", Limit = false)]
+        public async Task<IActionResult> GetTeacherInfo(JsonElement json)
+        {
+            json.TryGetProperty("tmdid", out JsonElement _tmdid);
+            var (id, school) = HttpContext.GetApiTokenInfo();
+            Azure.Response responseSchoolTch = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
+                .ReadItemStreamAsync($"{_tmdid}", new PartitionKey($"Teacher-{school}"));
+            Azure.Response responseTch = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher")
+                 .ReadItemStreamAsync($"{_tmdid}", new PartitionKey($"Base"));
+            Teacher teacher = null;
+            if (responseTch.Status == 200)
+            {
+                teacher = JsonDocument.Parse(responseTch.Content).RootElement.Deserialize<Teacher>();
+            }
+            else
+            {
+                return Ok(new { error = 3, msg = "账号未创建!" });
+            }
+            if (responseSchoolTch.Status == 200 && teacher != null)
+            {
+                SchoolTeacher schoolTeacher = JsonDocument.Parse(responseSchoolTch.Content).RootElement.Deserialize<SchoolTeacher>();
+                if (schoolTeacher.status.Equals("join"))
+                {
+                    return Ok(new { teacher.id, teacher.name, teacher.picture, schoolTeacher.job, schoolTeacher.status, schoolTeacher.roles, schoolTeacher.subjectIds, school = teacher.schools?.Find(x => x.schoolId.Equals(school)) });
+                }
+                else
+                {
+                    return Ok(new { error = 2, msg = "教师未加入学校!" });
+                }
+
+            }
+            else
+            {
+                return Ok(new { error = 1, msg = "教师未就职该学校!" });
+            }
+        }
+
+    }
+}

+ 2 - 0
TEAMModelOS.SDK/Models/Cosmos/School/TeacherImport.cs

@@ -19,5 +19,7 @@ namespace TEAMModelOS.SDK.Models
         public string name { get; set; }
         public string status { get; set; }
         public long time { get; set; }
+        //导入时的key
+        public string key { get; set; }
     }
 }

+ 22 - 9
TEAMModelOS/Controllers/Common/StudyController.cs

@@ -338,32 +338,45 @@ namespace TEAMModelOS.Controllers.Common
                     }
                     if (flag) {
                        
-                        study.status = 404;                        
+                        study.status = 404;
                         if (!string.IsNullOrEmpty(study.examId))
                         {
-                            ExamLite lite =  await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamLite>(study.examId, new PartitionKey($"ExamLite-{code}"));
-                            lite.status = 404;                           
+                            try { 
+                            ExamLite lite = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamLite>(study.examId, new PartitionKey($"ExamLite-{code}"));
+                            lite.status = 404;
                             await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(lite, lite.id, new PartitionKey($"ExamLite-{code}"));
+                            }
+                            catch (CosmosException ex)
+                            {
+                            }
                         }
                         if (!string.IsNullOrEmpty(study.surveyId))
                         {
+                            try { 
                             Survey survey = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Survey>(study.surveyId, new PartitionKey($"Survey-{code}"));
                             survey.status = 404;
                             await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(survey, survey.id, new PartitionKey($"Survey-{code}"));
-                            //await client.GetContainer("TEAMModelOS", "Common").DeleteItemStreamAsync(study.surveyId, new PartitionKey($"Survey-{code}"));
+                            }
+                            catch (CosmosException ex)
+                            {
+                            }
                         }
                         if (!string.IsNullOrEmpty(study.workId))
                         {
-                            Homework homework = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Homework>(study.workId, new PartitionKey($"Homework-{code}"));
-                            homework.status = 404;
-                            await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(homework, homework.id, new PartitionKey($"Homework-{code}"));
-                            //await client.GetContainer("TEAMModelOS", "Common").DeleteItemStreamAsync(study.workId, new PartitionKey($"Homework-{code}"));
+                            try
+                            {
+                                Homework homework = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Homework>(study.workId, new PartitionKey($"Homework-{code}"));
+                                homework.status = 404;
+                                await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(homework, homework.id, new PartitionKey($"Homework-{code}"));
+                            }
+                            catch (CosmosException ex)
+                            {
+                            }
                         }
                         await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(study, study.id, new PartitionKey($"{study.code}"));
                     }
 
                 }
-                //var response = await client.GetContainer("TEAMModelOS", "Common").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Study-{code}"));
                 return Ok(new { id });
 
             }

+ 101 - 22
TEAMModelOS/Controllers/School/SchoolController.cs

@@ -1553,41 +1553,62 @@ namespace TEAMModelOS.Controllers
         [ProducesDefaultResponseType]
         [HttpPost("teacher-import-manage")]
         [Authorize(Roles = "IES")]
-        [AuthToken( Roles ="admin,teacher")]
+        [AuthToken(Roles = "admin,teacher")]
         public async Task<IActionResult> TeacherImportManage(JsonElement request) {
             if (!request.TryGetProperty("opt", out JsonElement _opt)) { return BadRequest(); }
             if (!request.TryGetProperty("schoolId", out JsonElement _schoolId)) { return BadRequest(); }
-            if (!request.TryGetProperty("teachers", out JsonElement _teachers) || !_teachers.ValueKind.Equals(JsonValueKind.Array)) { return BadRequest(); }
-            TeacherImport teacherImport = null; 
+            
+            TeacherImport teacherImport = null;
+            List<SchoolTeacher> idsInSchool = new List<SchoolTeacher>();
+            List<CoreUser> coreUsers = new List<CoreUser>();
             switch ($"{_opt}") {
                 case "upsert":
-                    List<CoreUser> coreUsers = null;
+                    if (!request.TryGetProperty("teachers", out JsonElement _teachers) || !_teachers.ValueKind.Equals(JsonValueKind.Array)) { return BadRequest(); }
                     List<ImportTeacher> teachers = _teachers.ToObject<List<ImportTeacher>>();
-                    var ids = teachers.Where(x => !string.IsNullOrWhiteSpace(x.id)).Select(x => x.id);
-                    if (ids.Any()) {
-                        var content = new StringContent(ids.ToJsonString(), Encoding.UTF8, "application/json");
-                        string json =  await _coreAPIHttpService.GetUserInfos(content);
-                        if (!string.IsNullOrWhiteSpace(json)) {
-                            coreUsers = json.ToObject<List<CoreUser>>();
+                    var keys = teachers.Where(x => !string.IsNullOrWhiteSpace(x.key)).Select(x => x.key);
+                    long time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
+                    teachers.ForEach(x => { x.status = "import";x.time = time; });
+                    if (keys.Any()) {
+                        try
+                        {
+                            var content = new StringContent(keys.ToJsonString(), Encoding.UTF8, "application/json");
+                            string json = await _coreAPIHttpService.GetUserInfos(content);
+                            if (!string.IsNullOrWhiteSpace(json))
+                            {
+                                coreUsers = json.ToObject<List<CoreUser>>();
+                            }
+                        }
+                        catch (Exception ex)
+                        {
+                           await _dingDing.SendBotMsg($"{_option.Location},导入名单时,查验key信息错误{ex.Message}\n{ex.StackTrace}\n{keys.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
                         }
                     }
-                   
-                    string sql = $"select value(c.id) from c where c.id in ({string.Join(",",coreUsers.Select(x=>$"'{x.id}'"))}) ";
-                    List<string> idsInSchool = new List<string>();
-                    await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
-                        .GetItemQueryIterator<string>(queryText:sql,requestOptions:new QueryRequestOptions { PartitionKey= new PartitionKey($"Teacher-{_schoolId}")})) {
-                        idsInSchool.Add(item);
+                    if (coreUsers.Any()) {
+                        string sql = $"select c.id,c.status from c where c.id in ({string.Join(",", coreUsers.Select(x => $"'{x.id}'"))}) ";
+
+                        await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
+                            .GetItemQueryIterator<SchoolTeacher>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Teacher-{_schoolId}") }))
+                        {
+                            idsInSchool.Add(item);
+                        }
                     }
                     if (coreUsers.Any())
                     {
                         teachers.ForEach(t => {
-                            string id=  idsInSchool.Find(x => x.Equals(t.id));
-                            if (!string.IsNullOrWhiteSpace(id)) {
-                                t.status = "join";
+                            if (!string.IsNullOrWhiteSpace(t.key))
+                            {
+                                CoreUser coreUser = coreUsers.Find(x => x.searchKey.Equals(t.key));
+                                if (coreUser != null)
+                                {
+                                    t.id = coreUser.id;
+                                }
                             }
-                            CoreUser coreUser = coreUsers.Find(x => x.searchKey.Equals(t.id));
-                            if (coreUser != null) {
-                                t.id = coreUser.id;
+                            if (!string.IsNullOrWhiteSpace(t.id)) {
+                                SchoolTeacher teacher = idsInSchool.Find(x => x.id.Equals(t.id));
+                                if (teacher != null)
+                                {
+                                    t.status = teacher.status;
+                                }
                             }
                         });
                     }
@@ -1599,6 +1620,64 @@ namespace TEAMModelOS.Controllers
                     if (response.Status == 200)
                     {
                         teacherImport = JsonDocument.Parse(response.Content).RootElement.ToObject<TeacherImport>();
+                        var idsIn = teacherImport.teachers.Where(x => !string.IsNullOrWhiteSpace(x.id));
+                        var keyIn = teacherImport.teachers.Where(x => !string.IsNullOrWhiteSpace(x.key));
+                        List<string> skeys = keyIn.Any() ? keyIn.Select(x => x.key).ToList() : new List<string>();
+                        if (idsIn.Any())
+                        {
+                            skeys.AddRange(idsIn.Select(x=>x.id));
+                            string sqlInSchool = $"select c.id,c.status from c where c.id in ({string.Join(",", idsIn.Select(x => $"'{x.id}'"))}) ";
+                            await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
+                                .GetItemQueryIterator<SchoolTeacher>(queryText: sqlInSchool, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Teacher-{_schoolId}") }))
+                            {
+                                idsInSchool.Add(item);
+                            }
+                        }
+                        if (skeys.Any())
+                        {
+                            try {
+                                var content = new StringContent(skeys.ToJsonString(), Encoding.UTF8, "application/json");
+                                string json = await _coreAPIHttpService.GetUserInfos(content);
+                                if (!string.IsNullOrWhiteSpace(json))
+                                {
+                                    coreUsers = json.ToObject<List<CoreUser>>();
+                                }
+                            } catch (Exception ex) {
+                                //await _dingDing.SendBotMsg($"{_option.Location},导入名单时,查验key信息错误{ex.Message}\n{ex.StackTrace}\n{skeys.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
+                            }
+                        }
+                        if (coreUsers.Any()) {
+                            teacherImport.teachers.ForEach(t => {
+                                if (!string.IsNullOrWhiteSpace(t.key))
+                                {
+                                    CoreUser coreUser = coreUsers.Find(x => x.searchKey.Equals(t.key));
+                                    if (coreUser != null)
+                                    {
+                                        t.id = coreUser.id;
+                                    }
+                                }
+                                if (!string.IsNullOrWhiteSpace(t.id))
+                                {
+                                    CoreUser coreUser = coreUsers.Find(x => x.searchKey.Equals(t.id) || x.id.Equals(t.id));
+                                    if (coreUser != null)
+                                    {
+                                        t.id = coreUser.id;
+                                    }
+                                }
+                                if (!string.IsNullOrWhiteSpace(t.id))
+                                {
+                                    SchoolTeacher teacher = idsInSchool.Find(x => x.id.Equals(t.id));
+                                    if (teacher != null)
+                                    {
+                                        t.status = teacher.status;
+                                    }
+                                    else
+                                    {
+                                        t.status = "import";
+                                    }
+                                }
+                            });
+                        }
                     }
                     else {
                         teacherImport= new TeacherImport { id=$"{_schoolId}",code= "TeacherImport",pk= "TeacherImport",teachers= new List<ImportTeacher>() };