Explorar o código

Merge branch 'develop' of http://52.130.252.100:10000/TEAMMODEL/TEAMModelOS into develop

jeff hai 1 ano
pai
achega
5c61b8aeeb
Modificáronse 100 ficheiros con 1355 adicións e 13409 borrados
  1. 0 635
      TEAMModelAPI/Controllers/Business/CourseController.cs
  2. 0 565
      TEAMModelAPI/Controllers/Business/ExamController.cs
  3. 0 506
      TEAMModelAPI/Controllers/Business/GroupListController.cs
  4. 0 172
      TEAMModelAPI/Controllers/Business/RoomController.cs
  5. 0 91
      TEAMModelAPI/Controllers/Business/SchoolController.cs
  6. 0 351
      TEAMModelAPI/Controllers/Business/TeacherController.cs
  7. 0 26
      TEAMModelAPI/Program.cs
  8. 0 31
      TEAMModelAPI/Properties/launchSettings.json
  9. 0 142
      TEAMModelAPI/Startup.cs
  10. 0 14
      TEAMModelAPI/TEAMModelAPI.csproj
  11. 0 72
      TEAMModelAPI/appsettings.Development.json
  12. 0 22
      TEAMModelAPI/appsettings.json
  13. 0 2
      TEAMModelAPI/说明.md
  14. 6 1
      TEAMModelBI/ClientApp/src/store/index.js
  15. 96 1
      TEAMModelBI/ClientApp/src/view/product/index.vue
  16. 19 5
      TEAMModelBI/ClientApp/src/view/userInquire/details.vue
  17. 27 1
      TEAMModelBI/ClientApp/src/view/userInquire/index.vue
  18. 1 1
      TEAMModelBI/Controllers/BITest/Ies5TestController.cs
  19. 0 264
      TEAMModelFunction/.gitignore
  20. 0 548
      TEAMModelFunction/ActivityHttpTrigger.cs
  21. 0 342
      TEAMModelFunction/CourseServiceBus.cs
  22. 0 89
      TEAMModelFunction/LessonHttpTrigger.cs
  23. 0 155
      TEAMModelFunction/MonitorCosmosDB.cs
  24. 0 1033
      TEAMModelFunction/MonitorServicesBus.cs
  25. 0 175
      TEAMModelFunction/Properties/ServiceDependencies/TEAMModelOSFunction - Zip Deploy/profile.arm.json
  26. 0 113
      TEAMModelFunction/Properties/ServiceDependencies/TEAMModelOSFunction - Zip 部署/profile.arm.json
  27. 0 113
      TEAMModelFunction/Properties/ServiceDependencies/TEAMModelOSFunction - 压缩部署/profile.arm.json
  28. 0 175
      TEAMModelFunction/Properties/ServiceDependencies/teammodelosfunction-test - Zip Deploy/profile.arm.json
  29. 0 175
      TEAMModelFunction/Properties/ServiceDependencies/teammodelosfunction__test - 压缩部署/profile.arm.json
  30. 0 8
      TEAMModelFunction/Properties/launchSettings.json
  31. 0 3
      TEAMModelFunction/Properties/serviceDependencies.json
  32. 0 3
      TEAMModelFunction/Properties/serviceDependencies.local.json
  33. 0 611
      TEAMModelFunction/ScsApisHttpTrigger.cs
  34. 0 34
      TEAMModelFunction/Startup.cs
  35. 0 43
      TEAMModelFunction/TEAMModelFunction.csproj
  36. 0 427
      TEAMModelFunction/TriggerCorrect.cs
  37. 0 997
      TEAMModelFunction/TriggerExam.cs
  38. 0 170
      TEAMModelFunction/TriggerExamLite.cs
  39. 0 229
      TEAMModelFunction/TriggerHomework.cs
  40. 0 175
      TEAMModelFunction/TriggerStudy.cs
  41. 0 398
      TEAMModelFunction/TriggerSurvey.cs
  42. 0 318
      TEAMModelFunction/TriggerVote.cs
  43. 0 19
      TEAMModelFunction/host.json
  44. 0 21
      TEAMModelFunction/local.settings.json
  45. 0 35
      TEAMModelGrpc/Dockerfile
  46. 0 46
      TEAMModelGrpc/GrpcHealthCheck/GrpcHealthChecksEndpointRouteBuilderExtensions.cs
  47. 0 56
      TEAMModelGrpc/GrpcHealthCheck/GrpcHealthChecksPublisher.cs
  48. 0 52
      TEAMModelGrpc/GrpcHealthCheck/GrpcHealthChecksServiceExtensions.cs
  49. 0 52
      TEAMModelGrpc/Program.cs
  50. 0 17
      TEAMModelGrpc/Properties/launchSettings.json
  51. 0 26
      TEAMModelGrpc/Protos/BlobSASService.proto
  52. 0 162
      TEAMModelGrpc/Protos/ClassroomService.proto
  53. 0 33
      TEAMModelGrpc/Protos/ClassroomStudentService.proto
  54. 0 189
      TEAMModelGrpc/Protos/CourseService.proto
  55. 0 194
      TEAMModelGrpc/Protos/HomeWorkService.proto
  56. 0 167
      TEAMModelGrpc/Protos/KnowledgeService.proto
  57. 0 124
      TEAMModelGrpc/Protos/SyllabusService.proto
  58. 0 168
      TEAMModelGrpc/Protos/VolumeService.proto
  59. 0 21
      TEAMModelGrpc/Protos/greet.proto
  60. 0 10
      TEAMModelGrpc/Services/IBusinessService.cs
  61. 0 149
      TEAMModelGrpc/Startup.cs
  62. 0 48
      TEAMModelGrpc/TEAMModelGrpc.csproj
  63. 0 2263
      TEAMModelGrpc/TEAMModelOS.GRPC.xml
  64. 0 61
      TEAMModelGrpc/appsettings.Development.json
  65. 0 67
      TEAMModelGrpc/appsettings.json
  66. BIN=BIN
      TEAMModelGrpc/habook.pfx
  67. 0 12
      TEAMModelGrpc/nuget.config
  68. 1 1
      TEAMModelOS.FunctionV4/CosmosDB/TriggerExam.cs
  69. 1 2
      TEAMModelFunction/Properties/ServiceDependencies/teammodelos-func-v4 - Zip Deploy/profile.arm.json
  70. 1 1
      TEAMModelOS.FunctionV4/TEAMModelOS.FunctionV4.csproj
  71. 1 1
      TEAMModelOS.FunctionV4/local.settings.json
  72. 8 1
      TEAMModelOS.SDK/Models/Cosmos/Common/Activity.cs
  73. 2 2
      TEAMModelOS.SDK/Models/Cosmos/School/Elegant.cs
  74. 1 1
      TEAMModelOS.SDK/TEAMModelOS.SDK.csproj
  75. 70 0
      TEAMModelOS.TEST/Program.cs
  76. 1 1
      TEAMModelOS.sln
  77. 6 0
      TEAMModelOS/ClientApp/public/lang/en-US.js
  78. 7 1
      TEAMModelOS/ClientApp/public/lang/zh-CN.js
  79. 6 0
      TEAMModelOS/ClientApp/public/lang/zh-TW.js
  80. 2 0
      TEAMModelOS/ClientApp/src/api/index.js
  81. 6 0
      TEAMModelOS/ClientApp/src/api/schoolDashborad.js
  82. 2 2
      TEAMModelOS/ClientApp/src/common/BaseLayout.vue
  83. 2 2
      TEAMModelOS/ClientApp/src/view/areaMgmt/AreaEcharts/gradePie.vue
  84. 166 28
      TEAMModelOS/ClientApp/src/view/dashboard/school/SchoolDashboard.vue
  85. 0 0
      TEAMModelOS/ClientApp/src/view/elegant/BaseElegantCloud.vue
  86. 219 0
      TEAMModelOS/ClientApp/src/view/elegant/BaseElegantDash.vue
  87. 127 0
      TEAMModelOS/ClientApp/src/view/elegant/BaseTypeBar.vue
  88. 116 0
      TEAMModelOS/ClientApp/src/view/elegant/BaseTypePie.vue
  89. 216 0
      TEAMModelOS/ClientApp/src/view/elegant/BaseUploadLine.vue
  90. 128 91
      TEAMModelOS/ClientApp/src/view/elegant/Elegant.vue
  91. 7 0
      TEAMModelOS/ClientApp/src/view/evaluation/components/BaseExerciseList.vue
  92. 0 2
      TEAMModelOS/ClientApp/src/view/evaluation/types/BaseJudge.vue
  93. 2 1
      TEAMModelOS/ClientApp/src/view/evaluation/types/BaseMultiple.vue
  94. 2 1
      TEAMModelOS/ClientApp/src/view/evaluation/types/BaseSingle.vue
  95. 67 13
      TEAMModelOS/ClientApp/src/view/iot/areaiot.vue
  96. 1 1
      TEAMModelOS/ClientApp/src/view/iot/echarts/bar/bar.vue
  97. 15 9
      TEAMModelOS/ClientApp/src/view/iot/echarts/barandLine/specialBarline.vue
  98. 3 4
      TEAMModelOS/ClientApp/src/view/iot/schooliot.vue
  99. 20 16
      TEAMModelOS/Controllers/Common/ActivityController.cs
  100. 0 0
      TEAMModelOS/Controllers/Common/ExamController.cs

+ 0 - 635
TEAMModelAPI/Controllers/Business/CourseController.cs

@@ -1,635 +0,0 @@
-using Microsoft.AspNetCore.Mvc;
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Threading.Tasks;
-using TEAMModelOS.Models;
-using TEAMModelOS.SDK;
-using TEAMModelOS.SDK.DI;
-using System.Text.Json;
-using TEAMModelOS.SDK.Models;
-using TEAMModelOS.SDK.Extension;
-using Azure.Cosmos;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.Options;
-using System.IO;
-using System.Dynamic;
-using System.Net.Http;
-using System.Net;
-using Newtonsoft.Json;
-using System.Linq;
-using StackExchange.Redis;
-using static TEAMModelOS.SDK.Models.Teacher;
-using Microsoft.Extensions.Configuration;
-using TEAMModelOS.Filter;
-using Microsoft.AspNetCore.Authorization;
-using HTEXLib.COMM.Helpers;
-using TEAMModelOS.SDK.Models.Service;
-using System.ComponentModel.DataAnnotations;
-
-namespace TEAMModelAPI.Controllers
-{
-    [ProducesResponseType(StatusCodes.Status200OK)]
-    [ProducesResponseType(StatusCodes.Status400BadRequest)]
-    [ApiController]
-    [Route("{scope}")]
-    public class CourseController : ControllerBase
-    {
-        public AzureCosmosFactory _azureCosmos;
-        private readonly AzureStorageFactory _azureStorage;
-        private readonly AzureRedisFactory _azureRedis;
-        private readonly DingDing _dingDing;
-        private readonly Option _option;
-        private readonly IConfiguration _configuration;
-        private readonly CoreAPIHttpService _coreAPIHttpService;
-        private readonly AzureServiceBusFactory _serviceBus;
-        //1 2 3 4 5 6 7
-        private List<string> weekDays = new List<string> { "MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN" };
-        public CourseController(CoreAPIHttpService coreAPIHttpService, AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, DingDing dingDing, IOptionsSnapshot<Option> option, IConfiguration configuration, AzureServiceBusFactory serviceBus)
-        {
-            _azureCosmos = azureCosmos;
-            _azureStorage = azureStorage;
-            _azureRedis = azureRedis;
-            _dingDing = dingDing;
-            _option = option?.Value;
-            _configuration = configuration;
-            _coreAPIHttpService = coreAPIHttpService;
-            _serviceBus = serviceBus;
-        }
-        [ProducesDefaultResponseType]
-        [HttpPost("get-course-list")]
-        [ApiToken(Auth = "1301", Name = "获取课程列表信息", RWN = "R", Limit = false)]
-        public async Task<IActionResult> GetCourseList(JsonElement json)
-        {
-            var client = _azureCosmos.GetCosmosClient();
-            var (id, school) = HttpContext.GetApiTokenInfo();
-            json.TryGetProperty("periodId", out JsonElement periodId);
-            json.TryGetProperty("subjectId", out JsonElement subjectId);
-            StringBuilder sql = new StringBuilder($"SELECT c.id,c.name,c.subject,c.period,c.scope,c.no,c.school FROM c where 1=1 ");
-            if (!string.IsNullOrWhiteSpace($"{periodId}"))
-            {
-                sql.Append($" and c.period.id='{periodId}'");
-            }
-            if (!string.IsNullOrWhiteSpace($"{subjectId}"))
-            {
-                sql.Append($" and c.subject.id='{subjectId}'");
-            }
-            List<dynamic> courses = new List<dynamic>();
-            await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
-                    GetItemQueryIterator<dynamic>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{school}") }))
-            {
-                courses.Add(item);
-            }
-            return Ok(new { courses });
-        }
-
-        [ProducesDefaultResponseType]
-        [HttpPost("get-course-info")]
-        [ApiToken(Auth = "1302", Name = "课程详细信息", RWN = "R", Limit = false)]
-        public async Task<IActionResult> GetCourseInfo(JsonElement json)
-        {
-            var (id, school) = HttpContext.GetApiTokenInfo();
-            json.TryGetProperty("courseId", out JsonElement courseId);
-            Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
-               .ReadItemStreamAsync($"{courseId}", new PartitionKey($"Course-{school}"));
-            if (response.Status == 200)
-            {
-                JsonDocument document = JsonDocument.Parse(response.Content);
-                Course course = document.RootElement.Deserialize<Course>();
-                return Ok(new { course.name, course.id, course.subject, course.period, course.scope, course.school, course.no, course.desc, course.schedule });
-            }
-            else
-            {
-                return Ok(new { error = 1, msg = "课程不存在!" });
-            }
-        }
-
-        /// <summary>
-        ///  获取指定学段作息
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        [HttpPost("get-period-timetable")]
-        [ApiToken(Auth = "1303", Name = "试卷和评测的条件信息", RWN = "R", Limit = false)]
-        public async Task<IActionResult> GetPaperExamCondition(JsonElement json)
-        {
-            json.TryGetProperty("periodId", out JsonElement _periodId);
-            var (id, school) = HttpContext.GetApiTokenInfo();
-            School data = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(school, new PartitionKey("Base"));
-            var period = data.period.Find(x => x.id.Equals($"{_periodId}"));
-            if (period != null)
-            {
-              
-                return Ok(new { period.subjects, period.timetable, period.grades, period.majors , weekDays });
-            }
-            else
-            {
-                return Ok(new { error = 1, msg = "学段不存在!" });
-            }
-        }
-
-
-        [ProducesDefaultResponseType]
-        [HttpPost("upsert-course-infos")]
-        [ApiToken(Auth = "1304", Name = "课程详细信息", RWN = "W", Limit = false)]
-        public async Task<IActionResult> UpsertCourseInfo(CourseDtoImpt json)
-        {
-            var (id, school) = HttpContext.GetApiTokenInfo();
-            List<CourseDto> courseDtos = json.courses;
-            List<Dictionary<string, string>> errorData = new List<Dictionary<string, string>>();
-            List<Course> courses = new List<Course>() ;
-             
-            School data = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(school, new PartitionKey("Base"));
-            foreach (var courseDto in courseDtos) {
-                var period = data.period.Find(x => x.id.Equals($"{courseDto.periodId}"));
-                if (period != null)
-                {
-                    //同名学科
-                    var subject = period.subjects.Find(x => x.id.Equals($"{courseDto.subjectId}"));
-                    if (subject == null) {
-                        subject = period.subjects.Find(x => x.name.Equals($"{courseDto.subjectName}"));
-                    }
-                    if (subject == null) {
-                        subject = new Subject { id = courseDto.subjectId, name = subject.name, type = 1 };
-                        period.subjects.Add(subject);
-                        await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(data, data.id, new PartitionKey("Base"));
-                    }
-                    Course course = null;
-                    if (string.IsNullOrWhiteSpace(courseDto?.id))
-                    {
-                        course = new Course
-                        {
-                            pk = "Course",
-                            id = Guid.NewGuid().ToString(),
-                            code = $"Course-{school}",
-                            name = courseDto.name,
-                            subject = new SubjectSimple { id = subject.id, name = subject.name },
-                            period = new PeriodSimple { id = period.id, name = period.name },
-                            school = school,
-                            desc = courseDto.desc,
-                            scope = "school",
-                            no = courseDto.no,
-                        };
-                        await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).CreateItemAsync(course, new PartitionKey(course.code));
-                    }
-                    else
-                    {
-                        Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{course.id}", new PartitionKey($"Course-{school}"));
-                        if (response.Status == 200)
-                        {
-                            JsonDocument jsonDocument = JsonDocument.Parse(response.Content);
-                            course = jsonDocument.RootElement.ToObject<Course>();
-                            course.pk = "Course";
-                            course.name = string.IsNullOrWhiteSpace(courseDto.name) ? course.name : courseDto.name;
-                            course.subject = new SubjectSimple { id = subject.id, name = subject.name };
-                            course.period = new PeriodSimple { id = period.id, name = period.name };
-                            course.school = school;
-                            course.desc = string.IsNullOrWhiteSpace(courseDto.desc) ? course.desc : courseDto.desc;
-                            course.scope = "school";
-                            course.no = string.IsNullOrWhiteSpace(courseDto.no) ? course.no : courseDto.no;
-                            await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(course, course.id, new PartitionKey(course.code));
-                        }
-                        else
-                        {
-                            course = new Course
-                            {
-                                pk = "Course",
-                                id = Guid.NewGuid().ToString(),
-                                code = $"Course-{school}",
-                                name = courseDto.name,
-                                subject = new SubjectSimple { id = subject.id, name = subject.name },
-                                period = new PeriodSimple { id = period.id, name = period.name },
-                                school = school,
-                                desc = courseDto.desc,
-                                scope = "school",
-                                no = courseDto.no,
-                            };
-                            await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).CreateItemAsync(course, new PartitionKey(course.code));
-                        }
-                    }
-                    if (course != null) { courses.Add(course); }
-                }
-                else
-                {
-                    errorData.Add(new Dictionary<string, string> { { "course", courseDto.name }, { "periodId", courseDto.periodId } });
-                    //return Ok(new { error = 2, msg = "学段不存在!" });
-                }
-            }
-            
-            return Ok(new { courses = courses ,errorData});
-        }
-        //[Required(ErrorMessage = "{0} 课程的科目id必须填写"), RegularExpression(@"[0-9a-zA-Z]{8}(-[0-9a-zA-Z]{4}){3}-[0-9a-zA-Z]{12}",ErrorMessage ="科目的uuid格式错误!")]
-
-        public class ImportCourseDto {
-            public List<ImportCourse> courses { get; set; } = new List<ImportCourse>();
-        }
-
-
-        public class ImportCourse {
-            [Required(ErrorMessage = "课程id  必须设置"), RegularExpression(@"[0-9a-zA-Z]{8}(-[0-9a-zA-Z]{4}){3}-[0-9a-zA-Z]{12}", ErrorMessage = "科目的uuid格式错误!")]
-            public string courseId { get; set; }
-            [Required(ErrorMessage = "课程名称  必须设置")]
-            public string courseName { get; set; }
-            [Required(ErrorMessage = "课程科目id  必须设置"), RegularExpression(@"[0-9a-zA-Z]{8}(-[0-9a-zA-Z]{4}){3}-[0-9a-zA-Z]{12}", ErrorMessage = "科目的uuid格式错误!")]
-            public string subjectId { get; set; }
-            [Required(ErrorMessage = "课程科目名称 必须设置")]
-            public string subjectName { get; set; }
-            [Required(ErrorMessage = "课程学段id  必须设置"), RegularExpression(@"[0-9a-zA-Z]{8}(-[0-9a-zA-Z]{4}){3}-[0-9a-zA-Z]{12}", ErrorMessage = "学段的uuid格式错误!")]
-            public string periodId { get; set; }
-            public List<Schedule> schedules { get; set; }
-        
-        }
-
-        
-        [ProducesDefaultResponseType]
-        [HttpPost("upsert-course-schedule")]
-        [ApiToken(Auth = "1305", Name = "更新课程的排课信息", RWN = "W", Limit = false)]
-        public async Task<IActionResult> UpsertCourseSchedule(ImportCourseDto json)
-        {
-            var (id, school) = HttpContext.GetApiTokenInfo();
-            List<ImportCourse> importCourses = json.courses;
-            HashSet<string> courseIds= importCourses .Select(x => x.courseId).ToHashSet();
-            if (courseIds.Count < 1) { return Ok(new { error = 1, msg = "课程参数错误!" }); }
-
-            //string sql = $"select value(c) from c  where c.id in({string.Join(",",courseIds.Select(x=>$"'{x}'"))})";
-            string sql = $"select value(c) from c ";//直接获取全校的课程
-            List<Course> courses = new List<Course>();
-            await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
-                .GetItemQueryIterator<Course>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Course-{school}") })) {
-                courses.Add(item);
-            }
-            List<Subject> addSubjects = new List<Subject>();
-            School data = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(school, new PartitionKey("Base"));
-            //不存在的课程,可以被直接创建
-            var unexistCourseIds = courseIds.Except(courses.Select(x => x.id));
-            foreach (var item in unexistCourseIds) {
-                ImportCourse importCourse= importCourses.Find(x => x.courseId.Equals(item));
-                if (importCourse != null) {
-                    Period period= data.period.Find(x => x.id.Equals(importCourse.periodId));
-                    if (period != null) {
-                        //同名学科
-                        var subject = period.subjects.Find(x => x.id.Equals($"{importCourse.subjectId}"));
-                        if (subject == null)
-                        {
-                            subject = period.subjects.Find(x => x.name.Equals($"{importCourse.subjectName}"));
-                        }
-                        if (subject == null) {
-                            subject = new Subject { id = importCourse.subjectId, name = importCourse.subjectName, type = 1 };
-                            period.subjects.Add(subject);
-                            addSubjects.Add(subject);
-                            await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(data, data.id, new PartitionKey("Base"));
-                        }
-                        Course course = new Course
-                        {
-                            id = importCourse.courseId,
-                            code = $"Course-{school}",
-                            pk = "Course",
-                            name = importCourse.courseName,
-                            period = new PeriodSimple { id = period.id, name = period.name },
-                            subject = new SubjectSimple { id = subject.id, name = subject.name },
-                            school = school,
-                            scope = "school",
-                            year = DateTimeOffset.Now.Year,
-                            schedule = new List<Schedule>(),
-                        };
-                        await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).CreateItemAsync(course, new PartitionKey(course.code));
-                        courses.Add(course);
-                    }
-                }
-            }
-            //importCourses =importCourses .Where(x => !unexistCourseIds .Contains(x.courseId));
-
-            //排查 课程学段,课程排课作息,课程排课的星期几是否准确
-            List<ScheduleTimeDto> import_schedules_hastime = new List<ScheduleTimeDto>() ;
-            List<ScheduleNoTimeDto> import_schedules_nottime = new List<ScheduleNoTimeDto>();
-            //保存没有选用名单的排课。
-            List<Schedule> schedules_noList= new List<Schedule>() ;
-            List<ScheduleTimeDto> weeksError = new List<ScheduleTimeDto>();
-
-
-            importCourses .ToList().ForEach(x => {
-                x.schedules.ForEach(z => {
-
-                    if (!string.IsNullOrWhiteSpace(z.classId) || !string.IsNullOrWhiteSpace(z.stulist))
-                    {
-                        string classId = null;
-                        //行政班不为空,教学班为空,则名单取行政班
-                        classId = !string.IsNullOrWhiteSpace(z.classId) && string.IsNullOrWhiteSpace(z.stulist) ? z.classId : classId;
-                        //行政班为空,教学班不为空,则名单取教学班
-                        classId = string.IsNullOrWhiteSpace(z.classId) && !string.IsNullOrWhiteSpace(z.stulist) ? z.stulist : classId;
-                        //行政班,教学班都不为空,且相同,则任取一个,取的是行政班
-                        classId = !string.IsNullOrWhiteSpace(z.classId) && !string.IsNullOrWhiteSpace(z.stulist) && z.classId.Equals(z.stulist) ? z.classId : classId;
-                        //行政班,教学班都不为空,且不同,则取null
-                        classId = !string.IsNullOrWhiteSpace(z.classId) && !string.IsNullOrWhiteSpace(z.stulist) && !z.classId.Equals(z.stulist) ? null : classId;
-                        if (!string.IsNullOrWhiteSpace(classId))
-                        {
-                            if (z.time.IsNotEmpty())
-                            {
-                                z.time.ForEach(t =>
-                                {
-                                    ScheduleTimeDto scheduleDto = new ScheduleTimeDto
-                                    {
-                                        courseId = x.courseId,
-                                        roomId = z.room,
-                                        classId = z.classId,
-                                        stulist = z.stulist,
-                                        teacherId = z.teacherId,
-                                        timeId = t.id,
-                                        week = t.week,
-                                        keyTeacher = $"{z.teacherId}_{t.week}_{t.id}",
-                                        keyGroupId = $"{classId}_{t.week}_{t.id}",
-                                        keyRoomIds = string.IsNullOrWhiteSpace(z.room) ? null : $"{z.room}_{t.week}_{t.id}"
-                                    };
-                                    //星期几自检 1 2 3 4 5 6 7
-                                    if (weekDays.Contains(t.week))
-                                    {
-                                        import_schedules_hastime.Add(scheduleDto);
-                                    }
-                                    else
-                                    {
-                                        weeksError.Add(scheduleDto);
-                                    }
-
-                                });
-                            }
-                            else {
-                                //允许导入没有排课时间表的课程。
-                                import_schedules_nottime.Add(new ScheduleNoTimeDto
-                                {
-                                    courseId = x.courseId,
-                                    roomId = z.room,
-                                    classId = z.classId,
-                                    stulist = z.stulist,
-                                    teacherId = z.teacherId,
-                                });
-                            }
-                        }
-                        else { schedules_noList.Add(z); }
-                    }
-                    else {
-                        schedules_noList.Add(z);
-                    }
-                });
-            });
-            //导入的排课自检。
-            //教师自检
-            var check_teacher = import_schedules_hastime.GroupBy(x => x.keyTeacher).Select(g => new { key = g.Key, list = g.ToList() });
-            IEnumerable<ScheduleTimeDto> teacherWarning = new List<ScheduleTimeDto>();
-            teacherWarning = check_teacher.Where(x => x.list.Count > 1).SelectMany(x => x.list);
-            //import_schedules.RemoveAll(x => import_teacherConfuse.Contains(x));
-            //名单自检
-            var check_groupId = import_schedules_hastime.GroupBy(x => x.keyGroupId).Select(g => new { key = g.Key, list = g.ToList() });
-            IEnumerable<ScheduleTimeDto> groupIdWarning = new List<ScheduleTimeDto>();
-            groupIdWarning = check_groupId.Where(x => x.list.Count > 1).SelectMany(x => x.list);
-            //import_schedules.RemoveAll(x => import_groupIdConfuse.Contains(x));
-            //物理教室自检
-            var check_roomIds = import_schedules_hastime.Where(r=>!string.IsNullOrWhiteSpace(r.keyRoomIds)).GroupBy(x => x.keyRoomIds).Select(g => new { key = g.Key, list = g.ToList() });
-            IEnumerable<ScheduleTimeDto> roomIdsWarning = new List<ScheduleTimeDto>();
-            roomIdsWarning = check_roomIds.Where(x => x.list.Count > 1).SelectMany(x => x.list);
-            //import_schedules.RemoveAll(x => import_roomIdsConfuse.Contains(x));
-
-          
-            //打散数据库已经有的排课信息
-            List<ScheduleTimeDto> database_schedules = new List<ScheduleTimeDto>();
-            courses.ForEach(x => {
-                x.schedule.ForEach(z => {
-                    if (!string.IsNullOrWhiteSpace(z.teacherId) &&(!string.IsNullOrWhiteSpace(z.classId) || !string.IsNullOrWhiteSpace(z.stulist)))
-                    {
-                        string classId = null;
-                        //行政班不为空,教学班为空,则名单取行政班
-                        classId = !string.IsNullOrWhiteSpace(z.classId) && string.IsNullOrWhiteSpace(z.stulist) ? z.classId : classId;
-                        //行政班为空,教学班不为空,则名单取教学班
-                        classId = string.IsNullOrWhiteSpace(z.classId) && !string.IsNullOrWhiteSpace(z.stulist) ? z.stulist : classId;
-                        //行政班,教学班都不为空,且相同,则任取一个,取的是行政班
-                        classId = !string.IsNullOrWhiteSpace(z.classId) && !string.IsNullOrWhiteSpace(z.stulist) && z.classId.Equals(z.stulist) ? z.classId : classId;
-                        //行政班,教学班都不为空,且不同,则取null
-                        classId = !string.IsNullOrWhiteSpace(z.classId) && !string.IsNullOrWhiteSpace(z.stulist) && !z.classId.Equals(z.stulist) ? null : classId;
-                        if (!string.IsNullOrWhiteSpace(classId))
-                        {
-                            z.time.ForEach(t =>
-                            {
-                                ScheduleTimeDto scheduleDto = new ScheduleTimeDto
-                                {
-                                    courseId = x.id,
-                                    roomId = z.room,
-                                    classId = z.classId,
-                                    stulist = z.stulist,
-                                    teacherId = z.teacherId,
-                                    timeId = t.id,
-                                    week = t.week,
-                                    keyTeacher = $"{z.teacherId}_{t.week}_{t.id}",
-                                    keyGroupId = $"{classId}_{t.week}_{t.id}",
-                                    keyRoomIds = string.IsNullOrWhiteSpace(z.room) ? null : $"{z.room}_{t.week}_{t.id}"
-                                };
-                                database_schedules.Add(scheduleDto);
-                            });
-                        }
-                    }
-                });
-            });
-            List<ScheduleTimeDto> teacherError = new List<ScheduleTimeDto>();
-            List<ScheduleTimeDto> groupIdError = new List<ScheduleTimeDto>();
-            List<ScheduleTimeDto> roomIdsError = new List<ScheduleTimeDto>();
-            //数据库排查
-            import_schedules_hastime.ForEach(x => {
-                //检查教师的排课是否冲突,不同的课程不能出现 教师冲突的情况, 相同课程可能是需要更新的。
-                if (database_schedules.FindAll(s => s.keyTeacher.Equals(x.keyTeacher)  && !x.courseId.Equals(s.courseId)).IsNotEmpty()) 
-                {
-                    teacherError.Add(x);
-                } 
-                //检查名单的排课是否冲突
-                if (database_schedules.FindAll(s => s.keyGroupId.Equals(x.keyGroupId) && !x.courseId.Equals(s.courseId)).IsNotEmpty())
-                {
-                    groupIdError.Add(x);
-                }
-                //检查教室的排课是否冲突
-                if (database_schedules.FindAll(s => s.keyRoomIds.Equals(x.keyRoomIds) && !x.courseId.Equals(s.courseId)).IsNotEmpty())
-                {
-                    roomIdsError.Add(x);
-                }
-            });
-            //移除 教师,名单,教室冲突的排课
-            import_schedules_hastime.RemoveAll(x => teacherError.Contains(x));
-            import_schedules_hastime.RemoveAll(x => groupIdError.Contains(x));
-            import_schedules_hastime.RemoveAll(x => roomIdsError.Contains(x));
-            //最终导入之前,必须检查,课程是否存在(notInCourseIds),教师是否存在,名单是否存在,并重新排列行政班,教学班,
-            //排课时间段id是否正确,星期几是否正确(import_weeksConfuse),教室是否正确
-           
-            //检查教师存在的
-            HashSet<string> teachers = import_schedules_hastime.Select(x => x.teacherId).ToHashSet();
-            teachers.Union(import_schedules_nottime.Select(x => x.teacherId));
-            IEnumerable<string> unexistTeacherIds= null;
-            if (teachers.Count > 0) {
-                List<string> teacherIds = new List<string>();
-                string sqlTeacher = $"select value(c.id) from c where c.id in ({string.Join(",",teachers.Select(x=>$"'{x}'"))})";
-                await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
-                    .GetItemQueryIterator<string>(queryText: sqlTeacher, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Teacher-{school}") })) 
-                {
-                    teacherIds.Add(item);
-                }
-                unexistTeacherIds= teachers.Except(teacherIds);
-                //移除不存在的教师
-                import_schedules_hastime.RemoveAll(x => unexistTeacherIds.Contains(x.teacherId));
-                import_schedules_nottime.RemoveAll(x => unexistTeacherIds.Contains(x.teacherId));
-            }
-            //检查教室存在的
-            HashSet<string> roomIds = import_schedules_hastime.Select(x => x.roomId).ToHashSet();
-            roomIds.Union(import_schedules_nottime.Select(x => x.roomId));
-            IEnumerable<string> unexistRoomIds = null;
-            if (roomIds.Count > 0)
-            {
-                List<string> rooms = new List<string>();
-                string sqlRoom = $"select value(c.id) from c where c.id in ({string.Join(",", roomIds.Select(x => $"'{x}'"))})";
-                await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
-                    .GetItemQueryIterator<string>(queryText: sqlRoom, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Room-{school}") }))
-                {
-                    rooms.Add(item);
-                }
-                unexistRoomIds= roomIds.Except(rooms);
-                //移除不存在的教室
-                import_schedules_hastime.RemoveAll(x => unexistRoomIds.Contains(x.roomId));
-                import_schedules_nottime.RemoveAll(x => unexistRoomIds.Contains(x.roomId));
-            }
-            //检查名单存在的
-            List<string> groupIds = new List<string>();
-            var classIdsHasTime = import_schedules_hastime.Where(x => !string.IsNullOrWhiteSpace(x.classId)).Select(x => x.classId).ToHashSet();
-            if (classIdsHasTime.Any()) {
-                groupIds.AddRange(classIdsHasTime);
-            }
-            var stulistsHasTime = import_schedules_hastime.Where(x => !string.IsNullOrWhiteSpace(x.stulist)).Select(x => x.stulist).ToHashSet();
-            if (stulistsHasTime.Any())
-            {
-                groupIds.AddRange(stulistsHasTime);
-            }
-            var classIdsNotTime = import_schedules_nottime.Where(x => !string.IsNullOrWhiteSpace(x.classId)).Select(x => x.classId).ToHashSet();
-            if (classIdsNotTime.Any())
-            {
-                groupIds.AddRange(classIdsNotTime);
-            }
-            var stulistsNotTime = import_schedules_nottime.Where(x => !string.IsNullOrWhiteSpace(x.stulist)).Select(x => x.stulist).ToHashSet();
-            if (stulistsNotTime.Any())
-            {
-                groupIds.AddRange(stulistsNotTime);
-            }
-
-            List<GroupListDto> groupListDtos= await GroupListService.GetGroupListListids(_azureCosmos.GetCosmosClient(), _dingDing, groupIds, school);
-            IEnumerable<string> unexistGroupIds = groupIds.Except(groupListDtos.Select(x=>x.id));
-            //移除不存在的名单id
-            import_schedules_hastime.RemoveAll(x => unexistGroupIds.Contains(x.classId));
-            import_schedules_hastime.RemoveAll(x => unexistGroupIds.Contains(x.stulist));
-            import_schedules_nottime.RemoveAll(x => unexistGroupIds.Contains(x.classId));
-            import_schedules_nottime.RemoveAll(x => unexistGroupIds.Contains(x.stulist));
-
-            HashSet<Course> update_course = new HashSet<Course>();
-            HashSet<string> unexistTimeIds = new HashSet<string>();
-            //处理包含时间排课的课程
-            import_schedules_hastime.ForEach(schedule => {
-                Course course = courses.Find(x => x.id.Equals(schedule.courseId));
-                if (string.IsNullOrWhiteSpace(course?.period?.id))
-                {
-                    Period period = data.period.Find(p => p.id.Equals(course.period.id));
-                    TimeTable timeTable = period?.timetable.Find(x => x.id.Equals(schedule.timeId));
-                    if (timeTable != null)
-                    {
-                        string groupId= string.IsNullOrWhiteSpace(schedule.classId)?schedule.stulist:schedule.classId;
-                        GroupListDto groupList= groupListDtos.Find(g => g.id.Equals(groupId));
-                        string classId = null;
-                        string stulist = null;
-                        if (groupList.type.Equals("class")) {
-                            classId = groupList.id;
-
-
-                        }
-                        else {
-                            stulist = groupList.id;
-                        }
-                        var course_schedule =course.schedule.Find(x => x.teacherId.Equals(schedule.teacherId));
-                        if (course_schedule != null)
-                        {
-                            course_schedule.classId = classId;
-                            course_schedule.stulist = stulist ;
-                            course_schedule.room = schedule.roomId;
-                            var time=  course_schedule.time.Find(t => t.id.Equals(schedule.timeId) && t.week.Equals(schedule.week));
-                            if (time != null)
-                            {
-                                time.id=schedule.timeId;
-                                time.week=schedule.week;
-                            }
-                            else {
-                                course_schedule.time.Add(new TimeInfo { id = schedule.timeId, week = schedule.week });
-                            }
-                        }
-                        else {
-                            course.schedule.Add(new Schedule { teacherId = schedule.teacherId,classId = classId, stulist = stulist, room = schedule.roomId, time = new List<TimeInfo> { new TimeInfo { id=schedule.timeId,week=schedule.week} } });
-                        }
-                        update_course.Add(course);
-                    }
-                    else {
-                        //课程,所在学段对应的作息时间不正确
-                        unexistTimeIds.Add(schedule.timeId);
-                    }
-                }
-            });
-            //处理没有时间排课的课程
-            import_schedules_nottime.ForEach(schedule => {
-                Course course = courses.Find(x => x.id.Equals(schedule.courseId));
-                if (string.IsNullOrWhiteSpace(course?.period?.id))
-                {
-                    Period period = data.period.Find(p => p.id.Equals(course.period.id));
-                    string groupId = string.IsNullOrWhiteSpace(schedule.classId) ? schedule.stulist : schedule.classId;
-                    GroupListDto groupList = groupListDtos.Find(g => g.id.Equals(groupId));
-                    string classId = null;
-                    string stulist = null;
-                    if (groupList.type.Equals("class"))
-                    {
-                        classId = groupList.id;
-                    }
-                    else
-                    {
-                        stulist = groupList.id;
-                    }
-                    var course_schedule = course.schedule.Find(x => x.teacherId.Equals(schedule.teacherId));
-                    if (course_schedule != null)
-                    {
-                        course_schedule.classId = classId;
-                        course_schedule.stulist = stulist;
-                        course_schedule.room = schedule.roomId;
-                    }
-                    else
-                    {
-                        course.schedule.Add(new Schedule { teacherId=schedule.teacherId, classId = classId, stulist = stulist, room = schedule.roomId});
-                    }
-                    update_course.Add(course);
-                }
-            });
-
-            foreach (var item in update_course) {
-                await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
-            }
-            return Ok(new {
-                import= new //导入数据自检信息
-                {
-                    teacherWarning,//自检-教师冲突的排课
-                    groupIdWarning,//自检-名单冲突的排课
-                    roomIdsWarning,//自检-物理教室冲突的排课
-                    weeksError //自检-错误的星期几编码
-                },
-                database= new //数据库比对信息
-                {
-                    teacherError,//数据比对-教师冲突的排课
-                    groupIdError,//数据比对-名单冲突的排课
-                    roomIdsError,//数据比对-物理教室冲突的排课
-                    unexistCourseIds ,//不存在的课程
-                    unexistTeacherIds,//不存在的教师
-                    unexistGroupIds,//不存在的名单
-                    unexistRoomIds,//不存在的教室
-                    unexistTimeIds  //不存在的作息
-                },
-                updateCourse= update_course,
-                addSubjects= addSubjects
-            });
-        }
-        
-    }
-}

+ 0 - 565
TEAMModelAPI/Controllers/Business/ExamController.cs

@@ -1,565 +0,0 @@
-using Microsoft.AspNetCore.Mvc;
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Threading.Tasks;
-using TEAMModelOS.Models;
-using TEAMModelOS.SDK;
-using TEAMModelOS.SDK.DI;
-using System.Text.Json;
-using TEAMModelOS.SDK.Models;
-using TEAMModelOS.SDK.Extension;
-using Azure.Cosmos;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.Options;
-using System.IO;
-using System.Dynamic;
-using System.Net.Http;
-using System.Net;
-using Newtonsoft.Json;
-using System.Linq;
-using StackExchange.Redis;
-using static TEAMModelOS.SDK.Models.Teacher;
-using Microsoft.Extensions.Configuration;
-using TEAMModelOS.Filter;
-using Microsoft.AspNetCore.Authorization;
-using HTEXLib.COMM.Helpers;
-using HTEXLib.Translator;
-using TEAMModelOS.Models.Dto;
-
-namespace TEAMModelAPI.Controllers
-{
-    [ProducesResponseType(StatusCodes.Status200OK)]
-    [ProducesResponseType(StatusCodes.Status400BadRequest)]
-    [ApiController]
-    [Route("{scope}")]
-    public class ExamController : ControllerBase
-    {
-        public AzureCosmosFactory _azureCosmos;
-        private readonly AzureStorageFactory _azureStorage;
-        private readonly AzureRedisFactory _azureRedis;
-        private readonly DingDing _dingDing;
-        private readonly Option _option;
-        private readonly IConfiguration _configuration;
-        public DOXC2HTMLTranslator _DOXC2HTMLTranslator { get; set; }
-        //public PPTX2HTEXTranslator _PPTX2HTEXTranslator { get; set; }
-        public HTML2ITEMV3Translator _HTML2ITEMV3Translator { get; set; }
-        public ExamController(AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, DingDing dingDing, IOptionsSnapshot<Option> option, IConfiguration configuration)
-        {
-            _azureCosmos = azureCosmos;
-            _azureStorage = azureStorage;
-            _azureRedis = azureRedis;
-            _dingDing = dingDing;
-            _option = option?.Value;
-            _configuration = configuration;
-        }
-        /// <summary>
-        ///  获取试卷和评测的条件信息
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        [HttpPost("get-paper-exam-condition")]
-        [ApiToken(Auth = "1101", Name = "试卷和评测的条件信息", RWN = "R", Limit = false)]
-        public async Task<IActionResult> GetPaperExamCondition(JsonElement json)
-        {
-            json.TryGetProperty("periodId", out JsonElement _periodId);
-            var (id, school) = HttpContext.GetApiTokenInfo();
-            School data = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(school, new PartitionKey("Base"));
-            var exmaType = new { type = new List<string> { "regular", "simulation", "normal" } };//regula ,正规考,  simulation 模拟靠考,normal 普通考
-            var exmaMode = new { type = new List<string> { "0", "1", "2" } };//0 线上评测,  1 课中评测 ,2 阅卷评测
-            var period = data.period.Find(x => x.id.Equals($"{_periodId}"));
-            if (period != null)
-            {
-                return Ok(new { period.subjects, period.analysis, period.grades, exmaType, exmaMode });
-            }
-            else
-            {
-                return Ok(new { error = 1, msg = "学段不存在!" });
-            }
-        }
-        [ProducesDefaultResponseType]
-        [HttpPost("import-exam")]
-        [ApiToken(Auth = "1102", Name = "汇入评测基础数据", Limit = false)]
-        public async Task<IActionResult> importExam(JsonElement request)
-        {
-            //获取评测的ID
-            if (!request.TryGetProperty("exam", out JsonElement exam)) return BadRequest();
-            if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
-            try
-            {
-                var client = _azureCosmos.GetCosmosClient();
-                ExamInfo info = exam.ToObject<ExamInfo>();
-                info.progress = "going";
-                await client.GetContainer(Constant.TEAMModelOS, "Common").UpsertItemAsync(info, new PartitionKey($"Exam-{code}"));
-                return Ok(new { info });
-            }
-            catch (Exception e)
-            {
-                await _dingDing.SendBotMsg($"OS,{_option.Location},analysis/import-exam()\n{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
-                return BadRequest();
-            }
-        }
-        [ProducesDefaultResponseType]
-        [HttpPost("upsert-record")]
-        [ApiToken(Auth = "1103", Name = "批量汇入作答数据", Limit = false)]
-        public async Task<IActionResult> upsertRecord(JsonElement request)
-        {
-
-            if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
-            if (!request.TryGetProperty("students", out JsonElement students)) return BadRequest();
-            if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
-            //根据不同评测的类型返回对应的编码
-            if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
-            try
-            {
-                var client = _azureCosmos.GetCosmosClient();
-                //List<string> ids = students.ToObject<List<string>>();
-                List<students> stus = students.ToObject<List<students>>();
-                ExamInfo info = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.GetString(), new PartitionKey($"Exam-{code}"));
-                string classCode = info.scope.Equals("school") ? info.school : info.creatorId;
-                List<ExamClassResult> examClassResults = new();
-                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
-                           queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
-                           requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{classCode}") }))
-                {
-                    examClassResults.Add(item);
-                }
-                int n = 0;
-                foreach (ExamSubject subject in info.subjects)
-                {
-                    if (!subject.id.Equals(subjectId.GetString()))
-                    {
-                        n++;
-                    }
-                    else
-                    {
-                        break;
-                    }
-                }
-                //获取试卷信息
-                PaperSimple standerAnswers = new PaperSimple();
-                List<List<string>> standard = new List<List<string>>();
-                List<double> points = new List<double>();
-                standerAnswers = info.papers[n];
-                standard = standerAnswers.answers;
-                points = standerAnswers.point;
-                int rule = standerAnswers.multipleRule;
-                List<string> value = new List<string>();
-                await foreach (var s in stuTask(stus, examClassResults, standard, points, rule, info, subjectId.GetString(), client))
-                {
-                    if (s.code == 1)
-                    {
-                        value.Add(s.value);
-                    }
-                }
-                if (value.Count > 0)
-                {
-                    return Ok(new { code = 1, msg = "学生ID异常", value = value });
-                }
-                else
-                {
-                    return Ok(new { code = 0 });
-                }
-
-            }
-            catch (Exception e)
-            {
-                await _dingDing.SendBotMsg($"OS,{_option.Location},activity/upsert-record()\n{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
-                return BadRequest();
-            }
-
-        }
-        private async IAsyncEnumerable<(int code, string value)> stuTask(List<students> stus, List<ExamClassResult> examClassResults, List<List<string>> standard,
-            List<double> points, int rule, ExamInfo info, string subjectId, CosmosClient client)
-        {
-            foreach (var s in stus)
-            {
-                string value = "";
-                int code = 0;
-                List<List<string>> ans = s.answer;
-                bool isExist = examClassResults.Exists(e => e.studentIds.Contains(s.id));
-                if (!isExist)
-                {
-                    value = s.id;
-                    code = 1;
-                }
-                else
-                {
-                    foreach (ExamClassResult result in examClassResults)
-                    {
-                        if (!result.studentIds.Contains(s.id))
-                        {
-                            continue;
-                        }
-                        else
-                        {
-                            int newIndex = result.studentIds.IndexOf(s.id);
-                            StringBuilder builder = new StringBuilder();
-                            builder.Append(result.examId).Append('/');
-                            builder.Append(result.subjectId).Append('/');
-                            builder.Append(s.id).Append('/');
-                            builder.Append("ans.json");
-                            result.studentAnswers[newIndex].Clear();
-                            result.studentAnswers[newIndex].Add(builder.ToString());
-                            result.status[newIndex] = 0;
-                            for (int i = 0; i < ans.Count; i++)
-                            {
-                                if (ans[i] == null)
-                                {
-                                    continue;
-                                    //ans[i] = new List<string>();
-                                }
-                                var ac = ans[i].Count;
-                                var sc = standard[i].Count;
-                                //记录次数
-                                int n = 0;
-                                //算分处理
-                                if (sc > 0)
-                                {
-                                    result.ans[newIndex][i] = ans[i];
-                                    if (ac == sc && sc == 1)
-                                    {
-                                        foreach (string right in ans[i])
-                                        {
-                                            if (standard[i].Contains(right))
-                                            {
-                                                result.studentScores[newIndex][i] = points[i];
-                                            }
-                                            else
-                                            {
-                                                result.studentScores[newIndex][i] = 0;
-                                            }
-                                        }
-
-                                    }
-                                    else
-                                    {
-                                        if (rule > 0)
-                                        {
-                                            int falseCount = 0;
-                                            if (ac > 0)
-                                            {
-                                                foreach (string obj in ans[i])
-                                                {
-                                                    if (!standard[i].Contains(obj))
-                                                    {
-                                                        falseCount++;
-                                                    }
-                                                }
-                                                switch (rule)
-                                                {
-                                                    case 1:
-                                                        if (ac == sc)
-                                                        {
-                                                            if (falseCount == 0)
-                                                            {
-                                                                result.studentScores[newIndex][i] = points[i];
-                                                            }
-                                                            else
-                                                            {
-                                                                result.studentScores[newIndex][i] = 0;
-                                                            }
-                                                        }
-                                                        else
-                                                        {
-                                                            result.studentScores[newIndex][i] = 0;
-                                                        }
-                                                        break;
-                                                    case 2:
-                                                        if (falseCount > 0)
-                                                        {
-                                                            result.studentScores[newIndex][i] = 0;
-                                                        }
-                                                        else
-                                                        {
-                                                            if (ac == sc)
-                                                            {
-                                                                result.studentScores[newIndex][i] = points[i];
-                                                            }
-                                                            else
-                                                            {
-                                                                result.studentScores[newIndex][i] = points[i] / 2;
-                                                            }
-
-                                                        }
-                                                        break;
-                                                    case 3:
-                                                        if (falseCount > 0)
-                                                        {
-                                                            result.studentScores[newIndex][i] = 0;
-                                                        }
-                                                        else
-                                                        {
-                                                            if (ac == sc)
-                                                            {
-                                                                result.studentScores[newIndex][i] = points[i];
-                                                            }
-                                                            else
-                                                            {
-                                                                result.studentScores[newIndex][i] = System.Math.Round((double)ac / sc * points[i], 1);
-                                                            }
-
-                                                        }
-                                                        break;
-                                                    case 4:
-                                                        if (ac == sc)
-                                                        {
-                                                            result.studentScores[newIndex][i] = points[i];
-                                                        }
-                                                        else
-                                                        {
-                                                            double persent = (double)(sc - 2 * falseCount) / sc;
-                                                            if (persent <= 0)
-                                                            {
-                                                                result.studentScores[newIndex][i] = 0;
-                                                            }
-                                                            else
-                                                            {
-                                                                result.studentScores[newIndex][i] = System.Math.Round(persent * points[i], 1);
-                                                            }
-                                                        }
-                                                        break;
-                                                }
-                                            }
-                                            else
-                                            {
-                                                result.studentScores[newIndex][i] = 0;
-                                            }
-
-                                        }
-                                    }
-                                }
-                            }
-                            bool flag = true;
-                            foreach (List<double> scores in result.studentScores)
-                            {
-                                foreach (double score in scores)
-                                {
-                                    if (score == -1)
-                                    {
-                                        flag = false;
-                                        break;
-                                    }
-                                }
-                            }
-                            if (flag)
-                            {
-                                result.progress = true;
-                                info.subjects.ForEach(s =>
-                                {
-                                    if (s.id.Equals(subjectId.ToString()))
-                                    {
-                                        s.classCount += 1;
-                                    }
-                                });
-                                await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(info, info.id.ToString(), new PartitionKey($"{info.code}"));
-                            }
-                            result.sum[newIndex] = result.studentScores[newIndex].Sum();
-                            await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
-                            break;
-                        }
-                    }
-                }
-                yield return (code, value);
-            }
-        }
-        [ProducesDefaultResponseType]
-        [HttpPost("parse-word")]
-        [ApiToken(Auth = "1104", Name = "录入试卷数据", Limit = false)]
-        public async Task<IActionResult> ParseWord([FromForm] FileDto fileDto)
-        {
-            if (!FileType.GetExtention(fileDto.file.FileName).ToLower().Equals("docx"))
-            {
-                return BadRequest(new Dictionary<string, object> { { "msg", "type is not docx!" }, { "code", 404 } });
-            }
-
-            try
-            {
-               
-                var client = _azureCosmos.GetCosmosClient();
-                var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(fileDto.examId, new PartitionKey($"Exam-{fileDto.code}"));
-                ExamInfo examInfo;
-                if (response.Status == 200)
-                {
-                    using var json = await JsonDocument.ParseAsync(response.ContentStream);
-                    examInfo = json.ToObject<ExamInfo>();
-
-                }
-                else
-                {
-                    return Ok(new { error = 404, msg = "请先导入评测信息" });
-                }
-                foreach (PaperSimple paper in examInfo.papers)
-                {
-                    if (paper.id.Contains(fileDto.subjectId))
-                    {
-                        return Ok(new { error = 500, msg = "该试卷信息已存在" });
-                    }
-                }
-                PaperSimple simple = new();
-                var doc = _DOXC2HTMLTranslator.Translate(fileDto.file.OpenReadStream());
-                (List<HTEXLib.DOCX.Models.ItemInfo> tests, List<string> error) = _HTML2ITEMV3Translator.Translate(doc);
-                List<Task<string>> tasks = new List<Task<string>>();
-                PaperDto paperDto = new()
-                {
-                    id = Guid.NewGuid().ToString(),
-                    name = fileDto.name,
-                    code = fileDto.code,
-                    scope = "school",
-                    multipleRule = fileDto.multipleRule,
-                    gradeIds = fileDto.gradeIds,
-                    subjectId = fileDto.subjectId,
-                    periodId = fileDto.periodId
-                };
-                foreach (HTEXLib.DOCX.Models.ItemInfo item in tests)
-                {
-                    Slides slides = new();
-                    ItemDto dto = new();
-                    Scoring scoring = new();
-                    dto.id = Guid.NewGuid().ToString();
-                    dto.exercise.answer = item.answer;
-                    dto.exercise.explain = item.explain;
-                    dto.exercise.type = item.type;
-                    dto.exercise.opts = item.option.Count;
-                    dto.exercise.knowledge = item.knowledge;
-                    dto.exercise.field = item.field;
-                    dto.exercise.level = item.level;
-                    dto.exercise.subjectId = fileDto.subjectId;
-                    dto.exercise.periodId = fileDto.periodId;
-                    dto.exercise.gradeIds = fileDto.gradeIds;
-                    slides.url = dto.id + ".json";
-                    slides.type = dto.exercise.type;
-                    scoring.ans = dto.exercise.answer;
-                    scoring.score = dto.exercise.score;
-                    scoring.knowledge = dto.exercise.knowledge;
-                    scoring.field = dto.exercise.field;
-                    slides.scoring = scoring;
-                    //添加试卷信息
-                    paperDto.slides.Add(slides);
-                    if (!slides.type.Equals("compose"))
-                    {
-                        simple.point.Add(dto.exercise.score);
-                        simple.answers.Add(dto.exercise.answer);
-                        simple.knowledge.Add(dto.exercise.knowledge);
-                        simple.type.Add(dto.exercise.type);
-                        simple.field.Add((int)dto.exercise.field);
-                    }
-                    if (item.children.Count > 0)
-                    {
-                        foreach (HTEXLib.DOCX.Models.ItemInfo its in item.children)
-                        {
-                            Slides cslides = new();
-                            Scoring cscoring = new();
-                            ItemDto dtoChildren = new ItemDto();
-                            dtoChildren.id = Guid.NewGuid().ToString();
-                            dtoChildren.pid = dto.id;
-                            dtoChildren.exercise.answer = its.answer;
-                            dtoChildren.exercise.explain = its.explain;
-                            dtoChildren.exercise.type = its.type;
-                            dtoChildren.exercise.opts = its.option.Count;
-                            dtoChildren.exercise.knowledge = its.knowledge;
-                            dtoChildren.exercise.field = its.field;
-                            dtoChildren.exercise.level = its.level;
-                            dtoChildren.exercise.scope = "school";
-                            dtoChildren.exercise.score = its.score;
-                            dtoChildren.exercise.subjectId = fileDto.subjectId;
-                            dtoChildren.exercise.periodId = fileDto.periodId;
-                            dtoChildren.exercise.gradeIds = fileDto.gradeIds;
-                            dtoChildren.exercise.children.Add(dtoChildren.id);
-                            info info1 = new();
-                            info1.uid = dtoChildren.id;
-                            info1.question = its.question;
-                            info1.option = its.option;
-                            dtoChildren.item.Add(info1);
-                            dto.exercise.children.Add(dtoChildren.id);
-                            //处理子题的slides
-                            cslides.url = dtoChildren.id + ".json";
-                            cslides.type = dtoChildren.exercise.type;
-                            cscoring.ans = dtoChildren.exercise.answer;
-                            cscoring.score = dtoChildren.exercise.score;
-                            cscoring.knowledge = dtoChildren.exercise.knowledge;
-                            cscoring.field = dtoChildren.exercise.field;
-                            cslides.scoring = scoring;
-                            paperDto.slides.Add(cslides);
-                            //添加试卷信息
-                            simple.point.Add(dtoChildren.exercise.score);
-                            simple.answers.Add(dto.exercise.answer);
-                            simple.knowledge.Add(dto.exercise.knowledge);
-                            simple.type.Add(dto.exercise.type);
-                            simple.field.Add((int)dto.exercise.field);
-
-                            StringBuilder stringBuilder = new StringBuilder();
-                            stringBuilder.Append(fileDto.examId).Append("/");
-                            stringBuilder.Append("paper").Append("/");
-                            stringBuilder.Append(fileDto.subjectId).Append("/");
-                            stringBuilder.Append(dtoChildren.id + ".json");
-
-                            tasks.Add(_azureStorage.GetBlobContainerClient(fileDto.code).UploadFileByContainer( dtoChildren.ToJsonString(), "exam", stringBuilder.ToString(), false));
-                        }
-                    }
-                    info @info = new();
-                    @info.uid = dto.id;
-                    @info.question = item.question;
-                    @info.option = item.option;
-                    dto.item.Add(@info);
-                    dto.exercise.scope = "school";
-                    dto.exercise.score = item.score;
-                    StringBuilder builder = new StringBuilder();
-                    builder.Append(fileDto.examId).Append('/');
-                    builder.Append("paper").Append('/');
-                    builder.Append(fileDto.subjectId).Append('/');
-                    builder.Append(dto.id + ".json");
-                    tasks.Add(_azureStorage.GetBlobContainerClient(fileDto.code).UploadFileByContainer(dto.ToJsonString(), "exam", builder.ToString(), false));
-
-
-                }
-                StringBuilder paperBuilder = new StringBuilder();
-                paperBuilder.Append(fileDto.examId).Append('/');
-                paperBuilder.Append("paper").Append('/');
-                paperBuilder.Append(fileDto.subjectId).Append('/');
-                paperBuilder.Append("index.json");
-                tasks.Add(_azureStorage.GetBlobContainerClient(fileDto.code).UploadFileByContainer(paperDto.ToJsonString(), "exam", paperBuilder.ToString(), false));
-
-                //开始给ExamInfo paper赋值
-                simple.id = fileDto.subjectId;
-                simple.code = "Paper-" + fileDto.code;
-                simple.name = fileDto.name;
-                simple.blob = paperBuilder.ToString().Replace("index.json", "");
-                simple.scope = "school";
-                simple.multipleRule = fileDto.multipleRule;
-
-                examInfo.papers.Add(simple);
-                await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(examInfo, examInfo.id, new PartitionKey($"{examInfo.code}"));
-                await Task.WhenAll(tasks);
-
-                return Ok(new { code = 200 });
-            }
-            catch (Exception e)
-            {
-                await _dingDing.SendBotMsg($"OS,{_option.Location},analysis/word()\n{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
-                return BadRequest();
-            }
-
-        }
-
-        private class students
-        {
-            public string id { get; set; }
-            public List<List<string>> answer { get; set; }
-        }
-        public class FileDto
-        {
-            public string periodId { get; set; }
-            public string code { get; set; }
-            public string name { get; set; }
-            public int multipleRule { get; set; }
-            public string examId { get; set; }
-            public string subjectId { get; set; }
-            public List<string> gradeIds { get; set; }
-            public IFormFile file { get; set; }
-        }
-
-
-    }
-}

+ 0 - 506
TEAMModelAPI/Controllers/Business/GroupListController.cs

@@ -1,506 +0,0 @@
-using Microsoft.AspNetCore.Mvc;
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Threading.Tasks;
-using TEAMModelOS.Models;
-using TEAMModelOS.SDK;
-using TEAMModelOS.SDK.DI;
-using System.Text.Json;
-using TEAMModelOS.SDK.Models;
-using TEAMModelOS.SDK.Extension;
-using Azure.Cosmos;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.Options;
-using System.IO;
-using System.Dynamic;
-using System.Net.Http;
-using System.Net;
-using Newtonsoft.Json;
-using System.Linq;
-using StackExchange.Redis;
-using static TEAMModelOS.SDK.Models.Teacher;
-using Microsoft.Extensions.Configuration;
-using TEAMModelOS.Filter;
-using Microsoft.AspNetCore.Authorization;
-using HTEXLib.COMM.Helpers;
-using TEAMModelOS.SDK.Models.Service;
-namespace TEAMModelAPI.Controllers
-{
-    [ProducesResponseType(StatusCodes.Status200OK)]
-    [ProducesResponseType(StatusCodes.Status400BadRequest)]
-    [ApiController]
-    [Route("{scope}")]
-    public class GroupListController : ControllerBase
-    {
-        public AzureCosmosFactory _azureCosmos;
-        private readonly AzureStorageFactory _azureStorage;
-        private readonly AzureRedisFactory _azureRedis;
-        private readonly DingDing _dingDing;
-        private readonly Option _option;
-        private readonly IConfiguration _configuration;
-        private readonly CoreAPIHttpService _coreAPIHttpService;
-        private readonly AzureServiceBusFactory _serviceBus;
-        public GroupListController(CoreAPIHttpService coreAPIHttpService, AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, DingDing dingDing, IOptionsSnapshot<Option> option, IConfiguration configuration, AzureServiceBusFactory serviceBus)
-        {
-            _azureCosmos = azureCosmos;
-            _azureStorage = azureStorage;
-            _azureRedis = azureRedis;
-            _dingDing = dingDing;
-            _option = option?.Value;
-            _configuration = configuration;
-            _coreAPIHttpService = coreAPIHttpService;
-            _serviceBus = serviceBus;
-        }
-
-        /*
-            "periodId":"学段(选填)"
-         */
-        /// <summary>
-        ///  获取学校的行政班,教学班,教研组,研修名单
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        [HttpPost("get-group-list")]
-        [ApiToken(Auth = "1201", Name = "学校名单列表", RWN = "R", Limit = false)]
-        public async Task<IActionResult> GetGroupList(JsonElement json)
-        {
-            var client = _azureCosmos.GetCosmosClient();
-            var (id, school) = HttpContext.GetApiTokenInfo();
-            json.TryGetProperty("periodId", out JsonElement periodId);
-            List<GroupListGrp> groupLists = new List<GroupListGrp>();
-            //包含,学校的行政班,教学班
-            json.TryGetProperty("type", out JsonElement _type);
-            List<string> types = null;
-            if (_type.ValueKind.Equals(JsonValueKind.Array))
-            {
-                types = _type.ToObject<List<string>>();
-            }
-            else if (_type.ValueKind.Equals(JsonValueKind.String))
-            {
-                types = new List<string> { $"{types}" };
-            }
-            if (types.IsEmpty() || types.Contains("class"))
-            {
-                StringBuilder classsql = new StringBuilder($"SELECT c.id,c.name,c.periodId ,c.year  FROM c ");
-                if (!string.IsNullOrEmpty($"{periodId}"))
-                {
-                    classsql.Append($" where  c.periodId='{periodId}' ");
-                }
-                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ClassInfo>(queryText: classsql.ToString(),
-                    requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{school}") }))
-                {
-                    HashSet<string> groupNames = new HashSet<string>();
-                    string gpsql = $"SELECT distinct c.groupId,c.groupName FROM c where  c.classId='{item.id}'and c.groupName <>null";
-                    await foreach (var gp in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: gpsql,
-                        requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{school}") }))
-                    {
-                        groupNames.Add(gp.groupName);
-                    }
-                    ///行政班(学生搜寻classId动态返回)class
-                    GroupListGrp group = new GroupListGrp
-                    {
-                        id = item.id,
-                        code = $"GroupList-{school}",
-                        name = item.name,
-                        periodId = item.periodId,
-                        scope = "school",
-                        school = $"{school}",
-                        type = "class",
-                        year = item.year,
-                        groupName = groupNames
-                    };
-                    groupLists.Add(group);
-                }
-            }
-            if (types.IsEmpty() || types.Contains("teach"))
-            {
-                //教学班
-                StringBuilder teachsql = new StringBuilder($" SELECT distinct value(c) FROM c  where c.type='teach'");
-                if (!string.IsNullOrEmpty($"{periodId}"))
-                {
-                    teachsql.Append($" and c.periodId='{periodId}'");
-                }
-                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
-                    GetItemQueryIterator<GroupList>(queryText: teachsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
-                {
-                    HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
-                    groupLists.Add(new GroupListGrp(item, groupName));
-                }
-            }
-            if (types.IsEmpty() || types.Contains("research"))
-            {
-                //教研组
-                StringBuilder researchsql = new StringBuilder($"SELECT distinct value(c) FROM c   where c.type='research'");
-                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
-                    GetItemQueryIterator<GroupList>(queryText: researchsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
-                {
-                    HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
-                    groupLists.Add(new GroupListGrp(item, groupName));
-                }
-            }
-
-            if (types.IsEmpty() || types.Contains("yxtrain"))
-            {
-                //研修名单
-                StringBuilder yxtrainsql = new StringBuilder($"SELECT distinct value(c) FROM c    where c.type='yxtrain'");
-                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
-                    GetItemQueryIterator<GroupList>(queryText: yxtrainsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
-                {
-                    HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
-                    groupLists.Add(new GroupListGrp(item, groupName));
-                }
-            }
-            return Ok(new
-            {
-                groupLists = groupLists.Select(x => new { x.id, x.type, x.name, x.periodId, x.school, x.scope, x.year })
-            });
-        }
-        [ProducesDefaultResponseType]
-        [HttpPost("get-group-members")]
-        [ApiToken(Auth = "1202", Name = "获取名单详细信息和成员信息", RWN = "R", Limit = false)]
-        public async Task<IActionResult> GetGroupMembers(JsonElement json)
-        {
-            var client = _azureCosmos.GetCosmosClient();
-            if (!json.TryGetProperty("ids", out JsonElement ids)) return BadRequest();
-            var (id, school) = HttpContext.GetApiTokenInfo();
-            List<string> listids = ids.ToObject<List<string>>();
-            (List<RMember> members, List<RGroupList> groups) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, listids, $"{school}");
-            return Ok(new { groups = groups.Select(x => new { x.name, x.no, x.periodId, x.school, x.type, x.year, x.tcount, x.scount, x.leader, x.members, x.id }), members });
-        }
-        /// <summary>
-        /// 导入行政班学生
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        [HttpPost("import-class-members")]
-        [ApiToken(Auth = "1203", Name = "导入行政班学生", RWN = "W", Limit = false)]
-        public async Task<IActionResult> ImportClassMembers(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)
-                {
-                    List<Student> webStudents = _students.ToObject<List<Student>>();
-                    webStudents.ForEach(x => x.periodId = $"{_periodId}");
-                    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 = $"{school}", students = retUpsert.studs, retUpsert.classDuplNos, retUpsert.errorIds });
-                }
-                else 
-                {
-                    return Ok(new { error = 2, msg = "学段信息错误!" }); 
-                }
-            }
-            else {
-                return Ok(new { error = 1, msg = "学生列表格式错误" });
-            }
-        }
-        /// <summary>
-        ///更新學生資料,批量密碼重置,基本資訊更新(姓名、教室ID、性別、學年及座號)
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        [HttpPost("update-class-members")]
-        [ApiToken(Auth = "1204", Name = "更新行政班学生", RWN = "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>>();
-                    webStudents.ForEach(x => x.periodId = $"{_periodId}");
-                    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 = "1205", Name = "移除行政班学生", RWN = "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-groups")]
-        [ApiToken(Auth = "1206", Name = "创建或更新教学班", RWN = "W", Limit = false)]
-        public async Task<IActionResult> UpsertTeachGroups(GroupListDtoImpt json) {
-            var (_, school) = HttpContext.GetApiTokenInfo();
-            var groupListsDto = json.groupLists;
-            List<GroupList> groupLists = new List<GroupList>(); ;
-            List<Dictionary<string, string>> errorData = new List<Dictionary<string, string>>();
-            School data = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(school, new PartitionKey("Base"));
-            foreach (var list in groupListsDto) {
-                Period period = data.period.Find(x => x.id.Equals($"{list.periodId}"));
-                if (period != null)
-                {
-                    GroupList groupList = null;
-                    if (string.IsNullOrWhiteSpace(list.id))
-                    {
-                        groupList = new GroupList()
-                        {
-                            pk = "GroupList",
-                            id = Guid.NewGuid().ToString(),
-                            code = $"GroupList-{school}",
-                            name = list.name,
-                            periodId = list.periodId,
-                            scope = "school",
-                            school = school,
-                            type = "teach",
-                            year = list.year,
-                            froms = 3
-                        };
-                        groupList = await GroupListService.CheckListNo(groupList, _azureCosmos, _dingDing, _option);
-                        await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).CreateItemAsync(groupList, new PartitionKey(groupList.code));
-                    }
-                    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);
-                            groupList = jsonDocument.RootElement.ToObject<GroupList>();
-                            groupList.name = string.IsNullOrWhiteSpace(list.name) ? groupList.name : list.name;
-                            groupList.periodId = string.IsNullOrWhiteSpace(list.periodId) ? groupList.periodId : list.periodId;
-                            groupList.school = school;
-                            groupList.scope = "school";
-                            groupList.froms = 3;
-                            await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(groupList, groupList.id, new PartitionKey(groupList.code));
-                        }
-                        else
-                        {
-                            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,
-                                froms = 3
-                            };
-                            groupList = await GroupListService.CheckListNo(groupList, _azureCosmos, _dingDing, _option);
-                            await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).CreateItemAsync(groupList, new PartitionKey(groupList.code));
-                        }
-                    }
-                    if (groupList != null) {
-                        groupLists.Add(groupList);
-                    }
-                }
-                else
-                {
-                    errorData.Add(new Dictionary<string, string> { { "group",list.name}, { "periodId",list.periodId} });
-                    // return Ok(new { error = 2, msg ="学段不存在!" });
-                }
-            }
-             
-            return Ok(new { groupLists, errorData });
-        }
-
-        public class MemberImpt {
-            public List<Member> members { get; set; } = new List<Member>();
-            public string groupId { get; set; } 
-        }
-
-        /// <summary>
-        /// 导入教学班学生
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        [HttpPost("import-teach-members")]
-        [ApiToken(Auth = "1207", Name = "导入教学班学生", RWN    = "W", Limit = false)]
-        public async Task<IActionResult> ImportTeachMembers(MemberImpt json)
-        {
-            var (id, school) = HttpContext.GetApiTokenInfo();
-            //School data = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(school, new PartitionKey("Base"));
-            List<Member> members = json.members;
-            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}\n{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($"{json.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 = "名单错误!" });
-            }
-        }
-
-        /// <summary>
-        /// 移除教学班学生
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        [HttpPost("remove-teach-members")]
-        [ApiToken(Auth = "1208", Name = "移除教学班学生", RWN = "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 = "移除的名单人员为空!" }); 
-            }
-        }
-    }
-}

+ 0 - 172
TEAMModelAPI/Controllers/Business/RoomController.cs

@@ -1,172 +0,0 @@
-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;
-namespace TEAMModelAPI.Controllers
-{
-    [ProducesResponseType(StatusCodes.Status200OK)]
-    [ProducesResponseType(StatusCodes.Status400BadRequest)]
-    [Route("{scope}")]
-    [ApiController]
-    public class RoomController : 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; }
-        public RoomController(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;
-        }
-        /// <summary>
-        /// 获取物理教室列表
-        /// </summary>
-        /// <param name="json"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        [HttpPost("get-room-list")]
-        [ApiToken(Auth = "1401", Name = "获取物理教室列表", RWN= "R", Limit = false)]
-        public async Task<IActionResult> GetRoomList(JsonElement json)
-        {
-            var client = _azureCosmos.GetCosmosClient();
-            var (id, school) = HttpContext.GetApiTokenInfo();
-            StringBuilder sql = new StringBuilder($"select value(c) from c where 1=1 ");
-            json.TryGetProperty("openType", out JsonElement openType);
-            json.TryGetProperty("no", out JsonElement no);
-            if (!string.IsNullOrWhiteSpace($"{openType}"))
-            {
-                sql.Append($" and c.openType='{openType}'");
-            }
-            if (!string.IsNullOrWhiteSpace($"{no}"))
-            {
-                sql.Append($" and c.no='{no}'");
-            }
-            List<Room> rooms = new List<Room>();
-            await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Room>(queryText: sql.ToString(),
-            requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Room-{school}") }))
-            {
-                rooms.Add(item);
-            }
-            return Ok(new { rooms = rooms.Select(x => new { x.id, x.name, x.x, x.y, x.openType, x.style, x.area, x.address, school = school }) });
-        }
-        /// <summary>
-        /// 获取物理教室详细信息
-        /// </summary>
-        /// <param name="json"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        [HttpPost("get-room-info")]
-        [ApiToken(Auth = "1402", Name = "获取物理教室详细信息", RWN= "R", Limit = false)]
-        public async Task<IActionResult> GetRoomInfo(JsonElement json)
-        {
-            var (id, school) = HttpContext.GetApiTokenInfo();
-            if (!json.TryGetProperty("roomId", out JsonElement roomId)) return BadRequest();
-            Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
-              .ReadItemStreamAsync($"{roomId}", new PartitionKey($"Room-{school}"));
-            if (response.Status == 200)
-            {
-                JsonDocument document = JsonDocument.Parse(response.Content);
-                Room room = document.RootElement.Deserialize<Room>();
-                return Ok(new { room.id, room.name, room.x, room.y, room.openType, room.style, room.area, room.address, school = school });
-            }
-            else
-            {
-                return Ok(new { error = 1, msg = "教室不存在!" });
-            }
-        }
-
-        public class RoomsDto
-        {
-            public List<RoomDto> rooms { get; set; } = new List<RoomDto>();
-
-        }
-
-        /// <summary>
-        /// 创建或更新教学班基本信息
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        [HttpPost("upsert-room-infos")]
-        [ApiToken(Auth = "1403", Name = "创建或更新教学班", RWN= "W", Limit = false)]
-        public async Task<IActionResult> UpsertRoomInfo(RoomsDto json)
-        {
-            var (id, school) = HttpContext.GetApiTokenInfo();
-            var rooms = json.rooms ;
-            List<Room> db_rooms = new List<Room>();
-            List<Room> roomCreate = new List<Room>();
-            School data = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(school, new PartitionKey("Base"));
-            string sql = $"select value(c) from c  where c.id in({string.Join(",", rooms.Select(x => $"'{x.id}'"))})";
-            await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
-                .GetItemQueryIterator<Room>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Room-{school}") }))
-            {
-                db_rooms.Add(item);
-            }
-            //不存在的教室,可以被直接创建
-            var unexistRoomIds = rooms.Select(x=>x.id).Except(db_rooms.Select(x => x.id));
-            foreach (var roomId in unexistRoomIds) {
-                var room_web = rooms.Find(x => x.id.Equals(roomId));
-                if (room_web != null) {
-                    var room = new Room
-                    {
-                        id = room_web.id,
-                        name = room_web.name,
-                        code = $"Room-{school}",
-                        pk = "Room",
-                        no = room_web.no,
-                        area = room_web.area,
-                        address = room_web.address,
-                    };
-                    await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).CreateItemAsync(room, new PartitionKey(room.code));
-                    roomCreate.Add(room);
-                }
-            }
-            foreach (var room in db_rooms) {
-                var room_web = rooms.Find(x => x.id.Equals(room.id));
-                if (room_web != null)
-                {
-                    room.name = string.IsNullOrWhiteSpace(room_web.name) ? room.name : room_web.name;  
-                    room.code = $"Room-{school}";
-                    room.pk = "Room";
-                    room.area= string.IsNullOrWhiteSpace(room_web.area) ? room.area : room_web.area; 
-                    room.no =string.IsNullOrWhiteSpace(room_web.no)?room.no : room_web.no;
-                    room.address = string.IsNullOrWhiteSpace(room_web.address) ? room.address : room_web.address; 
-                    await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(room,room.id, new PartitionKey(room.code));
-                }
-            }
-            return Ok(new { roomUpdate= db_rooms, roomCreate= roomCreate });
-        }
-    }
-}

+ 0 - 91
TEAMModelAPI/Controllers/Business/SchoolController.cs

@@ -1,91 +0,0 @@
-using Microsoft.AspNetCore.Mvc;
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Threading.Tasks;
-using TEAMModelOS.Models;
-using TEAMModelOS.SDK;
-using TEAMModelOS.SDK.DI;
-using System.Text.Json;
-using TEAMModelOS.SDK.Models;
-using TEAMModelOS.SDK.Extension;
-using Azure.Cosmos;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.Options;
-using System.IO;
-using System.Dynamic;
-using System.Net.Http;
-using System.Net;
-using Newtonsoft.Json;
-using System.Linq;
-using StackExchange.Redis;
-using static TEAMModelOS.SDK.Models.Teacher;
-using Microsoft.Extensions.Configuration;
-using TEAMModelOS.Filter;
-using Microsoft.AspNetCore.Authorization;
-using HTEXLib.COMM.Helpers;
-using TEAMModelOS.SDK.Models.Service;
-using TEAMModelOS.SDK.Models.Table;
-
-namespace TEAMModelAPI.Controllers
-{
-    [ProducesResponseType(StatusCodes.Status200OK)]
-    [ProducesResponseType(StatusCodes.Status400BadRequest)]
-    [ApiController]
-    [Route("{scope}")]
-    public class SchoolController : ControllerBase
-    {
-        public AzureCosmosFactory _azureCosmos;
-        private readonly AzureStorageFactory _azureStorage;
-        private readonly AzureRedisFactory _azureRedis;
-        private readonly DingDing _dingDing;
-        private readonly Option _option;
-        private readonly IConfiguration _configuration;
-        private readonly CoreAPIHttpService _coreAPIHttpService;
-        public SchoolController(CoreAPIHttpService coreAPIHttpService, AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, DingDing dingDing, IOptionsSnapshot<Option> option, IConfiguration configuration)
-        {
-            _azureCosmos = azureCosmos;
-            _azureStorage = azureStorage;
-            _azureRedis = azureRedis;
-            _dingDing = dingDing;
-            _option = option?.Value;
-            _configuration = configuration;
-            _coreAPIHttpService=coreAPIHttpService;
-        }
-        /// <summary>
-        ///  学校基础信息
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        [HttpPost("get-schools")]
-        [ApiToken(Auth = "1000", Name = "合作商获取可访问的学校列表", RWN= "R", Limit = false)]
-        public async Task<IActionResult> GetSchools() {
-            var (id, _) = HttpContext.GetApiTokenInfo();
-            var table = _azureStorage.GetCloudTableClient().GetTableReference("IESOpenApi");
-            List<BusinessSchool> schools=  await table.FindListByDict<BusinessSchool>(new Dictionary<string, object> { { "PartitionKey", $"BusinessSchool-{id}" } });
-            return Ok(new { schools = schools.Select(x => new {id =x.RowKey,x.name,x.picture })});
-        }
-        /// <summary>
-        ///  学校基础信息
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        [HttpPost("get-school-info")]
-        [ApiToken(Auth = "1001",Name = "学校基础信息", RWN= "R", Limit =false)]
-        public async Task<IActionResult> GetSchoolInfo()
-        {
-            var (id, school) = HttpContext.GetApiTokenInfo();
-            School data = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(school, new PartitionKey("Base"));
-            List<dynamic> period = new List<dynamic>();
-            data.period.ForEach(x => { period.Add(new { x.subjects ,x.grades,x.name,x.id,x.campusId,x.semesters}); });
-            return Ok(new { 
-                id = data.id, name = data.name, data.areaId, type = data.type, 
-                data.region, data.province, data.city, data.dist,
-                campuses=data.campuses,
-                period
-            });
-        }
-    }
-}

+ 0 - 351
TEAMModelAPI/Controllers/Business/TeacherController.cs

@@ -1,351 +0,0 @@
-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;
-using System.ComponentModel.DataAnnotations;
-
-namespace TEAMModelAPI.Controllers
-{
-    [ProducesResponseType(StatusCodes.Status200OK)]
-    [ProducesResponseType(StatusCodes.Status400BadRequest)]
-    [Route("{scope}")]
-    [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]
-        [HttpPost("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 = $"   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   {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));
-            List<dynamic> tchs = new List<dynamic>();
-            teachers.Select(x => new { x.id, x.name, x.picture, x.job, x.subjectIds, x.roles }).ToList().ForEach(x => {
-                var coreUser = coreUsers.Find(c => c.id.Equals(x.id));
-                if (coreUser != null)
-                {
-                    tchs.Add(new { x.id, coreUser.name, coreUser.picture, x.job, x.subjectIds, x.roles, coreUser.searchKey, school });
-                }
-            });
-            return Ok(new
-            {
-                teachers = tchs,
-                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>();
-                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 = 1, msg = "教师未就职该学校!" });
-            }
-        }
-
-
-
-
-        /// <summary>
-        /// 批量导入教师信息,并加入学校。可以导入学科,但需要填写学段id
-        /// </summary>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        [HttpPost("import-school-teacher")]
-        [ApiToken(Auth = "1503", Name = "学校教师信息", RW = "R", Limit = false)]
-        public async Task<IActionResult> ImportSchoolTeacher(ImportTechDto json)
-        {
-            //如果需要同时导入学科,则需要填写学段
-
-            var (id, school) = HttpContext.GetApiTokenInfo();
-            List<ImportTech> teachers = json.teachers;
-            List<string> searchKey = teachers.Select(x => x.id).ToList();
-            string ujson = null;
-            var keys = searchKey.Where(x => !string.IsNullOrWhiteSpace(x));
-            if (keys.Any())
-            {
-                var content = new StringContent(keys.ToJsonString(), Encoding.UTF8, "application/json");
-                ujson = await _coreAPIHttpService.GetUserInfos(content);
-            }
-            List<CoreUser> coreUsers = new List<CoreUser>();
-            if (!string.IsNullOrWhiteSpace(ujson))
-            {
-                coreUsers = ujson.ToObject<List<CoreUser>>();
-            }
-            IEnumerable<string> unexist = new List<string>();
-            if (coreUsers.Any())
-            {
-                unexist = searchKey.Except(coreUsers.Select(x => x.id));
-            }
-            else
-            {
-                return Ok(new { error = 1, msg = "没有找到对应的教师信息!" });
-            }
-            var exist = coreUsers.Select(x => x.id);
-            //注册了账号的教师
-            teachers = teachers.Where(x => exist.Contains(x.id)).ToList();
-
-            List<Teacher> teachersList = new List<Teacher>();
-            List<SchoolTeacher> schoolTeachers = new List<SchoolTeacher>();
-            string sql = $"select value(c) from c where c.id in ({string.Join(",", teachers.Select(x => $"'{x.id}'"))})";
-            await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
-                .GetItemQueryIterator<Teacher>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
-            {
-                teachersList.Add(item);
-            }
-            await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
-              .GetItemQueryIterator<SchoolTeacher>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Teacher-{school}") }))
-            {
-                schoolTeachers.Add(item);
-            }
-            long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
-            School data = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(school, new PartitionKey("Base"));
-            //学校学科发生变化。
-            List<SchoolTeacher> schoolTeachersAdd = new List<SchoolTeacher>();
-            bool baseChange = false;
-            foreach (var item in teachers)
-            {
-                var teacher = teachersList.Find(x => x.id.Equals(item.id));
-                var coreUser = coreUsers.Find(x => x.id.Equals(item.id));
-                if (teacher != null)
-                {
-                    var sch = teacher.schools?.Find(x => x.schoolId.Equals(school));
-                    if (sch == null)
-                    {
-                        if (teacher.schools.IsNotEmpty())
-                        {
-                            teacher.schools.Add(new Teacher.TeacherSchool { schoolId = school, name = data.name, status = "invite", time = now, picture = data.picture, areaId = data.areaId });
-                        }
-                        else
-                        {
-                            teacher.defaultSchool = school;
-                            teacher.size = teacher.size + 1;
-                            teacher.schools = new List<Teacher.TeacherSchool> { new Teacher.TeacherSchool { schoolId = school, name = data.name, status = "invite", time = now, picture = data.picture, areaId = data.areaId } };
-                        }
-                    }
-                    await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
-                }
-                else
-                {
-
-                    teacher = new Teacher
-                    {
-                        createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
-                        id = coreUser.id,
-                        name = coreUser.name,
-                        picture = coreUser.picture,
-                        defaultSchool = school,
-                        size = 2,
-                        code = "Base",
-                        pk = "Base",
-                        schools = new List<Teacher.TeacherSchool> { new Teacher.TeacherSchool { schoolId = school, name = data.name, status = "invite", time = now, picture = data.picture, areaId = data.areaId } }
-                    };
-                    await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).CreateItemAsync(teacher, new PartitionKey("Base"));
-                }
-                var schoolTeacher = schoolTeachers.Find(x => x.id.Equals(item.id));
-                //处理导入的学科
-                List<string> subjectIds = new List<string>();
-                if (item.subjects.IsNotEmpty() && !string.IsNullOrWhiteSpace(item.periodId))
-                {
-                    item.subjects.ForEach(s => {
-                        //同名学科
-                        var subject = data.period.Find(x => x.id.Equals(item.periodId))?.subjects?.Find(x => x.id.Equals(s.id));
-                        if (subject == null)
-                        {
-                            subject = data.period.Find(x => x.id.Equals(item.periodId))?.subjects?.Find(x => x.name.Equals(s.name));
-                        }
-                        else
-                        {
-                            subjectIds.Add(subject.id);
-                        }
-                        if (subject == null)
-                        {
-                            var period = data.period.Find(x => x.id.Equals(item.periodId));
-                            if (period != null)
-                            {
-                                period.subjects.Add(new Subject { id = s.id, name = s.name, type = 2 });
-                                subjectIds.Add(s.id);
-                                baseChange = true;
-                            }
-                        }
-                    });
-                }
-                if (schoolTeacher == null)
-                {
-                    schoolTeacher = new SchoolTeacher
-                    {
-                        id = item.id,
-                        name = coreUser.name,
-                        picture = coreUser.picture,
-                        job = item.job,
-                        subjectIds = subjectIds,
-                        roles = new List<string> { "teacher" },
-                        permissions = new List<string> { "content-read", "exercise-read", "knowledge-read", "syllabus-read" },
-                        status = "invite",
-                        code = $"Teacher-{school}",
-                        pk = "Teacher",
-                        createTime = now,
-                    };
-                    schoolTeachersAdd.Add(schoolTeacher);
-                    await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).CreateItemAsync(schoolTeacher, new PartitionKey(schoolTeacher.code));
-                }
-                else
-                {
-                    if (subjectIds.IsNotEmpty())
-                    {
-                        subjectIds.ForEach(x => {
-                            if (!schoolTeacher.subjectIds.Contains(x))
-                            {
-                                schoolTeacher.subjectIds.Add(x);
-                            }
-                        });
-                    }
-                    schoolTeacher.job = string.IsNullOrWhiteSpace(item.job) ? schoolTeacher.job : item.job;
-                    schoolTeachersAdd.Add(schoolTeacher);
-                    await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(schoolTeacher, schoolTeacher.id, new PartitionKey(schoolTeacher.code));
-                }
-            }
-            if (baseChange)
-            {
-                await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(data, data.id, new PartitionKey("Base"));
-            }
-            return Ok(new { teachers = schoolTeachersAdd.Select(x => new { x.id, x.name, x.picture, x.job, x.subjectIds, x.roles, school }) });
-        }
-    }
-
-    public class ImportTechDto
-    {
-        public List<ImportTech> teachers { get; set; } = new List<ImportTech>();
-    }
-    public class ImportTech
-    {
-        [Required(ErrorMessage = "教师id必须设置")]
-        public string id { get; set; }
-        public List<ImportTechSubject> subjects { get; set; }
-        [RegularExpression(@"[0-9a-zA-Z]{8}(-[0-9a-zA-Z]{4}){3}-[0-9a-zA-Z]{12}", ErrorMessage = "学段的uuid格式错误!")]
-        public string periodId { get; set; }
-        public string job { get; set; }
-    }
-    public class ImportTechSubject
-    {
-        [RegularExpression(@"[0-9a-zA-Z]{8}(-[0-9a-zA-Z]{4}){3}-[0-9a-zA-Z]{12}", ErrorMessage = "科目的uuid格式错误!")]
-        public string id { get; set; }
-        [Required(ErrorMessage = "科目名称 必须设置")]
-        public string name { get; set; }
-    }
-
-}

+ 0 - 26
TEAMModelAPI/Program.cs

@@ -1,26 +0,0 @@
-using Microsoft.AspNetCore.Hosting;
-using Microsoft.Extensions.Configuration;
-using Microsoft.Extensions.Hosting;
-using Microsoft.Extensions.Logging;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-
-namespace TEAMModelAPI
-{
-    public class Program
-    {
-        public static void Main(string[] args)
-        {
-            CreateHostBuilder(args).Build().Run();
-        }
-
-        public static IHostBuilder CreateHostBuilder(string[] args) =>
-            Host.CreateDefaultBuilder(args)
-                .ConfigureWebHostDefaults(webBuilder =>
-                {
-                    webBuilder.UseStartup<Startup>();
-                });
-    }
-}

+ 0 - 31
TEAMModelAPI/Properties/launchSettings.json

@@ -1,31 +0,0 @@
-{
-  "$schema": "http://json.schemastore.org/launchsettings.json",
-  "iisSettings": {
-    "windowsAuthentication": false,
-    "anonymousAuthentication": true,
-    "iisExpress": {
-      "applicationUrl": "http://localhost:58541/",
-      "sslPort": 44333
-    }
-  },
-  "profiles": {
-    "IIS Express": {
-      "commandName": "IISExpress",
-      "launchBrowser": true,
-      "launchUrl": "http://doc.teammodel.cn:4999/web/#/16",
-      "environmentVariables": {
-        "ASPNETCORE_ENVIRONMENT": "Development"
-      }
-    },
-    "TEAMModelAPI": {
-      "commandName": "Project",
-      "launchBrowser": true,
-      "launchUrl": "http://doc.teammodel.cn:4999/web/#/16",
-      "environmentVariables": {
-        "ASPNETCORE_ENVIRONMENT": "Development"
-      },
-      "applicationUrl": "https://localhost:5001;http://localhost:5000",
-      "dotnetRunMessages": "true"
-    }
-  }
-}

+ 0 - 142
TEAMModelAPI/Startup.cs

@@ -1,142 +0,0 @@
- using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Hosting;
-using Microsoft.AspNetCore.HttpsPolicy;
-using Microsoft.AspNetCore.Mvc;
-using Microsoft.Extensions.Configuration;
-using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.Hosting;
-using Microsoft.Extensions.Logging;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-using TEAMModelOS.Models;
-using TEAMModelOS.SDK.DI;
-using System.IdentityModel.Tokens.Jwt;
-using Microsoft.AspNetCore.Authentication.JwtBearer;
-using Microsoft.IdentityModel.Tokens;
-using TEAMModelOS.Filter;
-using TEAMModelOS.SDK.Helper.Common.ReflectorExtensions;
-using System.Reflection;
-using TEAMModelOS.SDK.Extension;
-using TEAMModelOS.SDK;
-using TEAMModelOS.SDK.Models;
-
-namespace TEAMModelAPI
-{
-    public class Startup
-    {
-        readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
-        public Startup(IConfiguration configuration)
-        {
-            Configuration = configuration;
-        }
-
-        public IConfiguration Configuration { get; }
-
-        // This method gets called by the runtime. Use this method to add services to the container.
-        public void ConfigureServices(IServiceCollection services)
-        {
-           
-            JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
-            services.AddAuthentication(options => options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme)
-                .AddJwtBearer(options => //AzureADJwtBearer
-                {
-                    //options.SaveToken = true; //驗證令牌由服務器生成才有效,不適用於服務重啟或分布式架構
-                    options.Authority = Configuration["Option:Authority"];
-                    options.Audience = Configuration["Option:Audience"];
-                    options.RequireHttpsMetadata = true;
-                    options.TokenValidationParameters = new TokenValidationParameters
-                    {
-                        RoleClaimType = "roles",
-                        ValidAudiences = new string[] { Configuration["Option:Audience"], $"api://{Configuration["Option:Audience"]}" }
-                    };
-                    options.Events = new JwtBearerEvents();
-                    //下列事件有需要紀錄則打開
-                    //options.Events.OnMessageReceived = async context => { await Task.FromResult(0); };
-                    //options.Events.OnForbidden = async context => { await Task.FromResult(0); };
-                    //options.Events.OnChallenge = async context => { await Task.FromResult(0); };
-                    //options.Events.OnAuthenticationFailed = async context => { await Task.FromResult(0); };
-                    options.Events.OnTokenValidated = async context =>
-                    {
-                        if (!context.Principal.Claims.Any(x => x.Type.Equals("http://schemas.microsoft.com/identity/claims/scope")) //ClaimConstants.Scope
-                        && !context.Principal.Claims.Any(y => y.Type .Equals("roles"))) //ClaimConstants.Roles //http://schemas.microsoft.com/ws/2008/06/identity/claims/role
-                        {
-                            //TODO 需處理額外授權非角色及範圍的訪問異常紀錄
-                            throw new UnauthorizedAccessException("Neither scope or roles claim was found in the bearer token.");
-                        }
-                        await Task.FromResult(0);
-                    };
-                });
-            //設定跨域請求
-            services.AddCors(options =>
-            {
-                options.AddPolicy(MyAllowSpecificOrigins,
-                builder =>
-                {
-                    builder.WithOrigins("http://teammodelos-test.chinacloudsites.cn",
-                                        "https://www.teammodel.cn", "https://localhost:5001",
-                                        "http://localhost:5000", "http://localhost:64524",
-                                        "https://localhost:44341", "https://localhost:8888", "http://localhost:8888")
-                    .AllowAnyHeader()
-                    .AllowAnyMethod();
-                });
-            });
-            services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.IgnoreNullValues = false; });
-            services.AddAzureStorage(Configuration.GetValue<string>("Azure:Storage:ConnectionString"));
-            services.AddAzureRedis(Configuration.GetValue<string>("Azure:Redis:ConnectionString"));
-            services.AddAzureCosmos(Configuration.GetValue<string>("Azure:Cosmos:ConnectionString"));
-            services.AddAzureServiceBus(Configuration.GetValue<string>("Azure:ServiceBus:ConnectionString"));
-            services.AddMemoryCache();
-            services.AddSnowflakeId(Convert.ToInt64(Configuration.GetValue<string>("Option:LocationNum")), 1);
-            services.AddHttpClient();
-            services.AddHttpClient<DingDing>();
-            services.AddCoreAPIHttpService(Configuration);
-            //HttpContextAccessor,并用来访问HttpContext。(提供組件或非控制器服務存取HttpContext)
-            services.AddHttpContextAccessor();
-            services.Configure<Option>(options => Configuration.GetSection("Option").Bind(options));
-           
-        }
-
-        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
-        public async void Configure(IApplicationBuilder app, IWebHostEnvironment env,AzureStorageFactory azureStorage)
-        {
-            if (env.IsDevelopment())
-            {
-                app.UseDeveloperExceptionPage();
-            }
-
-            app.UseHttpsRedirection();
-
-            app.UseRouting();
-            app.UseCors(MyAllowSpecificOrigins); //使用跨域設定
-            app.UseAuthentication();
-            app.UseAuthorization();
-            app.UseEndpoints(endpoints =>
-            {
-                endpoints.MapControllers();
-            });
-#if DEBUG
-            //在开发模式时,自检 [ApiToken(Auth = "1")] 有重复的接口 https://teammodelos.table.core.chinacloudapi.cn/IESOpenApi
-            List<ApiTokenAttribute> auths = new List<ApiTokenAttribute>();
-            (List < OpenApi > openApis ,List<ApiTokenAttribute> attributes  ) = ReflectorExtensions.GetMethodCustomAttribute<ApiTokenAttribute, HttpPostAttribute>(new string[] { "TEAMModelAPI" });
-            attributes.GroupBy(x => x.Auth).ToList().ForEach(x => {
-                if (x.Count() > 1) 
-                { 
-                    throw new Exception($"接口Auth重复定义{x.ToList()}"); 
-                } 
-            });
-
-            var table =  azureStorage.GetCloudTableClient().GetTableReference("IESOpenApi");
-            try {
-                foreach (var item in openApis)
-                {
-                    await table.SaveOrUpdate<OpenApi>(item);
-                }
-            } catch (Exception ex) {
-                Console.WriteLine(ex.Message);
-            }
-#endif
-        }
-    }
-}

+ 0 - 14
TEAMModelAPI/TEAMModelAPI.csproj

@@ -1,14 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk.Web">
-
-  <PropertyGroup>
-    <TargetFramework>net6.0</TargetFramework>
-  </PropertyGroup>
-
-  <ItemGroup>
-    <None Remove="Controllers\Business\说明.md" />
-  </ItemGroup>
-
-  <ItemGroup>
-    <ProjectReference Include="..\TEAMModelOS.SDK\TEAMModelOS.SDK.csproj" />
-  </ItemGroup>
-</Project>

+ 0 - 72
TEAMModelAPI/appsettings.Development.json

@@ -1,72 +0,0 @@
-{
-  "Logging": {
-    "LogLevel": {
-      "Default": "Information",
-      "Microsoft": "Warning",
-      "Microsoft.Hosting.Lifetime": "Information"
-    }
-  },
-  "AllowedHosts": "*",
-  "Option": {
-    "Location": "China-Dep",
-    "LocationNum": "1",
-    "HostName": "localhost:5001",
-    "AllowedHosts": [ "localhost", "*.teammodel.cn", "*.teammodel.net", "*.habookaclass.biz", "test" ],
-    "Issuer": "www.teammodel.cn",
-    "JwtSecretKey": "fXO6ko/qyXeYrkecPeKdgXnuLXf9vMEtnBC9OB3s+aA=",
-    "Exp": 86400,
-    "IdTokenSalt": "8263692E2213497BB55E74792B7900B4",
-    "HttpTrigger": "https://teammodelosfunction-test.chinacloudsites.cn/api/"
-  },
-  "Azure": {
-    "Storage": {
-      "ConnectionString": "DefaultEndpointsProtocol=https;AccountName=teammodeltest;AccountKey=O2W2vadCqexDxWO+px+QK7y1sHwsYj8f/WwKLdOdG5RwHgW/Dupz9dDUb4c1gi6ojzQaRpFUeAAmOu4N9E+37A==;EndpointSuffix=core.chinacloudapi.cn"
-    },
-    "Cosmos": {
-      "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"
-    //},
-    //"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": {
-      "userinfo": "https://api2.teammodel.cn/Oauth2/GetUserInfos"
-    },
-    "Account": "https://account.teammodel.cn",
-    "CoreAPI": "https://api2.teammodel.cn",
-    "CoreService": {
-      "clientID": "c7317f88-7cea-4e48-ac57-a16071f7b884",
-      "clientSecret": "kguxh:V.PLmxBdaI@jnrTrDSth]A3346",
-      "deviceinfo": "https://api2.teammodel.cn/oauth2/getdeviceinfos",
-      "sendnotification": "https://api2.teammodel.net/service/sendnotification",
-      "getnotification": "https://api2.teammodel.net/service/getnotification",
-      "delnotification": "https://api2.teammodel.net/service/delnotification"
-    }
-  },
-  "DingDingAuth": {
-    "Agentld": "1290158212",
-    "appKey": "dingrucgsnt8p13rfbgd",
-    "appSecret": "Gyx_N57yZslhQOAhAPlvmCwOp_qTm1DScKbd5OoOE0URAW4eViYA2Sk_ZxKb-8WG",
-    "getuserinfo_bycode": "https://oapi.dingtalk.com/sns/getuserinfo_bycode?accessKey=xxx&timestamp=xxx&signature=xxx"
-  }
-}

+ 0 - 22
TEAMModelAPI/appsettings.json

@@ -1,22 +0,0 @@
-{
-  "Logging": {
-    "LogLevel": {
-      "Default": "Information",
-      "Microsoft": "Warning",
-      "Microsoft.Hosting.Lifetime": "Information"
-    }
-  },
-  "AllowedHosts": "*",
-  "Option": {
-    "Location": "China",
-    "LocationNum": "8",
-    "HostName": "localhost:5001",
-    "AllowedHosts": [ "localhost", "*.teammodel.cn", "*.teammodel.net", "*.habookaclass.biz", "test" ],
-    "Authority": "https://login.chinacloudapi.cn/4807e9cf-87b8-4174-aa5b-e76497d7392b/v2.0", //China:"https://login.chinacloudapi.cn/4807e9cf-87b8-4174-aa5b-e76497d7392b/v2.0", //Global:"https://login.microsoftonline.com/73a2bcc5-fe99-4566-aa8a-07e7bb287df1/v2.0"
-    "Audience": "72643704-b2e7-4b26-b881-bd5865e7a7a5", //China:"72643704-b2e7-4b26-b881-bd5865e7a7a5",Global:"8768b06f-c5c5-4b0c-abfb-d7ded354626d"
-    "Issuer": "www.teammodel.cn",
-    "JwtSecretKey": "fXO6ko/qyXeYrkecPeKdgXnuLXf9vMEtnBC9OB3s+aA=",
-    "Exp": 86400,
-    "IdTokenSalt": "8263692E2213497BB55E74792B7900B4"
-  }
-}

+ 0 - 2
TEAMModelAPI/说明.md

@@ -1,2 +0,0 @@
-企业接入,也必须有学校进行授权。企业业务允许的授权范围内。
-请求端,需要在开放平台备注域名,ip白名单。

+ 6 - 1
TEAMModelBI/ClientApp/src/store/index.js

@@ -22,7 +22,8 @@ export default createStore({
         areaClickschool: {},
         areaClickCounselor: '',
         areaClickRoles: '',
-        msgData: {}
+        msgData: {},
+        transmitvalue:[]
     },
     mutations: {
         //修改组织架构
@@ -99,6 +100,10 @@ export default createStore({
         //复用消息
         copyMsgs(state, value) {
             state.msgData = value
+        },
+        //保存产品使用->ID查询用户列表
+        transmitUsers(state,value){
+            state.transmitvalue=value
         }
     },
     actions: {},

+ 96 - 1
TEAMModelBI/ClientApp/src/view/product/index.vue

@@ -264,6 +264,41 @@
       </template>
     </el-dialog>
   </div>
+  <div class="dialog-teachlist" v-if="teachtableShow">
+      <el-dialog v-model="teachtableShow" title="教师详细列表" width="55%">
+      <div class="header-title">
+        <div class="header-title-schoolname">{{touchNowteach.name}}</div>
+        <div class="header-title-content">
+          <div class="header-title-num">共 <span style="color:#409EFF">{{teachData.length}}</span> 名用户</div>
+          <div class="header-title-btn">
+            <el-button size="small" type="primary" v-if="deleteSchoolArr.length >0" @click="seachAllteach"  :icon="Search">个人数据查询</el-button>
+            <el-button size="small" type="info" disabled :icon="Search" v-else>个人数据查询</el-button>
+          </div>
+          <div class="header-title-hint" v-show="deleteSchoolArr.length >0">
+            <span>目前支持同时最多5名用户查询</span>
+          </div>
+        </div>
+      </div>
+      <div class="teachlist-table">
+        <el-table ref="multipleTableRef" :data="teachData" style="width: 100%"  height="50vh" @selection-change="selectTeach">
+          <el-table-column type="selection" />
+          <el-table-column label="头像" align="center">
+            <template #default="scope">
+              <el-image style="width: 50px; height: 50px" :src="scope.row.picture" fit="fill" v-if="scope.row.picture"></el-image>
+              <PersonalPhoto style="cursor: pointer;" :name="scope.row.name" width="50px" height="50px" v-else></PersonalPhoto>
+            </template>
+          </el-table-column>  
+          <el-table-column property="name" label="姓名" align="center"/>
+          <el-table-column property="id" label="ID" align="center"/>
+        </el-table>  
+      </div>
+      <template #footer>
+        <span class="dialog-footer">
+          <el-button @click="teachtableShow = false">关闭</el-button>
+        </span>
+      </template>  
+    </el-dialog>
+  </div>
 </template>
 <script setup>
 import option_cn from '@/static/regions/region_cn.json'
@@ -273,8 +308,12 @@ import { ElMessage, TableV2SortOrder, ElLoading, ElCheckbox,HeaderCellSlotProps,
 import { Filter } from '@element-plus/icons'
 import { multipleSheetExport } from '@/until/multipleSheetExport'
 import { Search, CirclePlus } from '@element-plus/icons-vue'
+import { useRouter } from 'vue-router'
+import { useStore } from 'vuex'
 import Details from './details.vue'
 let { proxy } = getCurrentInstance()
+let router=useRouter()
+const store = useStore()
 let drawer = ref(false)
 let direction = ref('ttb')
 let activeNames = ref(['1'])
@@ -371,7 +410,7 @@ let columns = ref([
     cellRenderer: (data) =>
     (
       <>
-        <el-button type="primary"  round>查看所有教师</el-button>
+        <el-button type="primary"  onClick={examineAllteach.bind(this,data)}>查看所有教师</el-button>
       </>
     )
   },
@@ -688,6 +727,10 @@ let filterType=ref({
    unregistered:true,
 })
 let initLoading=ref(false)
+let teachtableShow=ref(false)
+let teachData=ref([])
+let deleteSchoolArr=ref([])
+let touchNowteach=ref()
 const pickerOptions=function disabledDate(time) {
           return time.getTime() > Date.now();
 }
@@ -709,6 +752,7 @@ const monthOptions=function disabledDate(time){
                 const elTimeData = timeyear.toString() + timemonth.toString();
                 return elTimeData >= nowDate; 
 }
+
 function changeState (value) {
   console.log(value)
   showState.value = 'details'
@@ -1423,6 +1467,31 @@ function filterSchooltype(){
   console.log(result,'赋值')
   filterdata.value=result
 }
+//获取查看所有老师BTN
+function examineAllteach(value){
+  let teachList=value.rowData.tmidList
+  touchNowteach.value=value.rowData
+  store.commit('transmitUsers', [])
+  let data={tmids:teachList,mode:'simple'}
+  proxy.$api.getUserdatas(data).then((res)=>{
+    console.log(res,'查询老师')
+    res.length >0 ? teachData.value=res:(teachData.value=[],ElMessage.info('暂无查询到相应用户数据'))
+    teachtableShow.value=true
+  })
+}
+function selectTeach (value) {
+    deleteSchoolArr.value=value
+    console.log(deleteSchoolArr.value,'6666')
+}
+function seachAllteach(){
+  if(deleteSchoolArr.value.length >4){
+      ElMessage.info('当前查询人数仅支持小于或等于5名用户')
+      return
+  }
+  console.log(deleteSchoolArr.value,'传递出去的参数')
+  store.commit('transmitUsers', deleteSchoolArr.value)
+  router.push({name:'userinquire'})  
+}
 // init()
 dataInit()
 filterDistrict()
@@ -1626,6 +1695,28 @@ watch(clickNum, (newv) => {
 .school-type {
   display: flex;
 }
+.dialog-teachlist{
+  line-height: 40px;
+}
+.header-title-content{
+  display: flex;
+  flex-direction: row-reverse;
+  position: relative;
+}
+.header-title-schoolname{
+  font-size:20px;
+  text-align: center;
+}
+.header-title-num{
+  margin-left:2%;
+}
+.header-title-hint{
+  position:absolute;
+  top:0%;
+  left:1%;
+  font-size:12px;
+  color:#909399;
+}
 </style>
 <style>
 .data-tables .header-class,
@@ -1687,4 +1778,8 @@ watch(clickNum, (newv) => {
 .data-tables .el-table-v2__header-cell:hover .el-icon{
   display: flex;
 }
+.dialog-teachlist .el-dialog__header{
+  padding: 5px;
+
+}
 </style>

+ 19 - 5
TEAMModelBI/ClientApp/src/view/userInquire/details.vue

@@ -49,11 +49,11 @@
                   <use :xlink:href="item.icon"></use>
                 </svg>
                 <span class="information-text">{{item.value}}</span>
-                <div :title="[item.correlation ? '已关联':'弱关联,可进行手动修改']" v-show="item.key ==='school' && item.value !=='无'">
+                <!-- <div :title="[item.correlation ? '已关联':'弱关联,可进行手动修改']" v-show="item.key ==='school' && item.value !=='无'">
                     <svg class="hint-icon" aria-hidden="true"  >
                         <use :xlink:href="[item.correlation ? '#icon-zhengque3':'#icon-tishi2']"></use>
                     </svg>
-                </div>
+                </div> -->
                 <!-- <el-button type="" size="small" v-show="item.key ==='school'&& !item.correlation" class="changebtn">更改</el-button> -->
                 <!-- <el-button type="" size="small" v-show="item.key ==='local'">更改</el-button> -->
             </div>
@@ -369,7 +369,7 @@
     </div>
 </template>
 <script setup>
-import { ref, getCurrentInstance, watch, h, nextTick,onMounted,defineProps,defineEmits,computed } from 'vue'
+import { ref, getCurrentInstance, watch, h, nextTick,onMounted,defineProps,defineEmits,computed,inject} from 'vue'
 import { Iphone,More,MoreFilled,ArrowLeft,Right } from '@element-plus/icons'
 import commonHeatmapVue from '../../components/echarts/commonHeatmap.vue'
 import commonGaugeVue from '../../components/echarts/commonGauge.vue'
@@ -381,9 +381,11 @@ import Score from './score.vue'
 import Ticket from './ticket.vue'
 import Userdetail from './userdetail.vue'
 import replaceHiTeach from './iot.vue'
+import { useRouter } from 'vue-router'
 let props = defineProps({
     searchdata: Object,
 })
+let router=useRouter()
 let {ctx:that,proxy } = getCurrentInstance()
 let activeName = ref('basics')
 let userdetailState=ref(false)
@@ -733,6 +735,7 @@ let headerData=ref([
     require('@/assets/img/default4.png'),
     ])
 let userPortrait=ref()     //用户头像
+let backtoShow=inject("transmitShow")
 const randomImage = computed(()=>{
     const randomIndex = Math.floor(Math.random() * headerData.value.length);
     console.log(randomIndex,'随机头像')
@@ -744,7 +747,11 @@ const handleChildEvent = (payload) => {
 const emits = defineEmits(['parentClick']) 
 const backClick = () => {
     console.log('back init')
-        emits('parentClick','default') // 使用方式和 vue2 this.$emit 一样
+    if(backtoShow){
+        router.push({name:'analysis'})
+    }else{
+        emits('parentClick','default')
+    }
 }
 // initdata()
 function initdata() {
@@ -758,9 +765,16 @@ function initdata() {
     userdata.value[0].value = id ? id:'暂无'
     userdata.value[1].value = mobile ?mobile:'暂无'
     userdata.value[2].value = schoolCodeW ? schoolCodeW : schoolCode ? schoolCode:'无'
+    let schoolname= schoolCode ?schoolCode:'无'; let schoolnameW=schoolCodeW ? schoolCodeW:'无'
+    userdata.value[2].value = schoolCodeW || schoolCode ?  schoolname   + ' | '  +schoolnameW:'暂无'
     schoolCodeW ? userdata.value[2].correlation=true:false
     userdata.value[3].value = mail ? mail:'暂无'
-    userdata.value[4].value = country && province && city ? country+'-'+province+city:country && province ? country+'-'+province:'暂无'
+    //userdata.value[4].value = country && province && city ? country+'-'+province+city:country && province ? country+'-'+province:'暂无'
+    let locationName= country && province && city && dist ? country+'-'+province+city+dist:
+                      country && province && city ? country +'-'+province+city:
+                      country && city && dist  ? country+'-'+city+dist:
+                      country && province ? country+'-'+province:'暂无'
+    userdata.value[4].value = locationName
     //产品使用及安装情况 登入时间
     let {login}=transmitData
     let logintimes = login.length >0 ? login.sort(function(a,b){return b.time-a.time}):'无'

+ 27 - 1
TEAMModelBI/ClientApp/src/view/userInquire/index.vue

@@ -39,11 +39,18 @@
     </div>
 </template>
 <script setup>
-import { ref, getCurrentInstance, watch, h, nextTick } from 'vue'
+import { ref, getCurrentInstance, watch, h, nextTick,provide } from 'vue'
 import { ElMessage, ElLoading } from 'element-plus'
 import { Search } from '@element-plus/icons'
 import Detailsbox from './details.vue'
+import {useRoute} from "vue-router"
+import { useStore } from 'vuex'
 let { proxy } = getCurrentInstance()
+let route=useRoute()
+const store = useStore()
+let transmitUser=store.state.transmitvalue
+let transmitModel=ref(transmitUser.length >0 ? true:false)
+console.log(store,'用户传递')
 let tags = ref([
   { name: 'Tag 1', type: '' },
   { name: 'Tag 2', type: 'success' },
@@ -59,6 +66,9 @@ let searchLoading=ref(false)
 const searchRecordsArr = ref(localStorage.getItem('searchRecords') ?  JSON.parse(localStorage.getItem('searchRecords')):[]);
 const backClicks=()=>{pageShow.value='default'}
 console.log(searchRecordsArr.value,'搜索记录')
+//逻辑判断  是否是从 产品使用分析跳转过来
+transmitModel.value ? transmitinit():''
+provide('transmitShow',transmitModel.value)
 function seachSole(datavalue) {
     if(!searchvalue.value){
         ElMessage.info('请输入手机号码/ 醍魔豆账号 进行搜索!')
@@ -90,6 +100,8 @@ function seachSole(datavalue) {
         time:Date.now()
     }
     proxy.$api.getUserdatas(data).then((res) => { 
+        //重置vuex内的值,预防下次Menu进入 自动获取vuex值进行查询
+        store.commit('transmitUsers', [])
         console.log(res, 'user back')
         res.length >0 ? 
         (searchResult.value=res,searchLoading.value=false,pageShow.value='details'):
@@ -122,6 +134,20 @@ function deleteLog(value){
     resultNum !== -1 ? (searchRecordsArr.value.splice(resultNum,1)):''
     localStorage.setItem('searchRecords', JSON.stringify(searchRecordsArr.value));
 }
+function transmitinit(){
+    console.log('被调用')
+    let users=store.state.transmitvalue
+    let searchvs=''
+    users.forEach(element => {
+        if(searchvs.length ===0){
+            searchvs=element.id
+        }else{
+            searchvs=searchvs+','+element.id
+        }
+    });
+    searchvalue.value=searchvs
+    seachSole()
+}
 </script>
 <style scoped>
 .inquirebox{

+ 1 - 1
TEAMModelBI/Controllers/BITest/Ies5TestController.cs

@@ -74,7 +74,7 @@ namespace TEAMModelBI.Controllers.BITest
             var messageBatchCopyFile = new ServiceBusMessage(olrec.ToJsonString());
             messageBatchCopyFile.ApplicationProperties.Add("name", "OnLinRecord");   //Function名称
             var onlinRecTask = _configuration.GetValue<string>("Azue:ServiceBus:OnlinRecord");
-            await _serviceBus.GetServiceBusClient().SendMessageAsync(onlinRecTask, messageBatchCopyFile);
+           // await _serviceBus.GetServiceBusClient().SendMessageAsync(onlinRecTask, messageBatchCopyFile);
             return Ok(new { state = 200, dateHours, dateHours1, dateHours2, dateDay, dateDays, dateMonth, });
         }
 

+ 0 - 264
TEAMModelFunction/.gitignore

@@ -1,264 +0,0 @@
-## Ignore Visual Studio temporary files, build results, and
-## files generated by popular Visual Studio add-ons.
-
-# Azure Functions localsettings file
-local.settings.json
-
-# User-specific files
-*.suo
-*.user
-*.userosscache
-*.sln.docstates
-
-# User-specific files (MonoDevelop/Xamarin Studio)
-*.userprefs
-
-# Build results
-[Dd]ebug/
-[Dd]ebugPublic/
-[Rr]elease/
-[Rr]eleases/
-x64/
-x86/
-bld/
-[Bb]in/
-[Oo]bj/
-[Ll]og/
-
-# Visual Studio 2015 cache/options directory
-.vs/
-# Uncomment if you have tasks that create the project's static files in wwwroot
-#wwwroot/
-
-# MSTest test Results
-[Tt]est[Rr]esult*/
-[Bb]uild[Ll]og.*
-
-# NUNIT
-*.VisualState.xml
-TestResult.xml
-
-# Build Results of an ATL Project
-[Dd]ebugPS/
-[Rr]eleasePS/
-dlldata.c
-
-# DNX
-project.lock.json
-project.fragment.lock.json
-artifacts/
-
-*_i.c
-*_p.c
-*_i.h
-*.ilk
-*.meta
-*.obj
-*.pch
-*.pdb
-*.pgc
-*.pgd
-*.rsp
-*.sbr
-*.tlb
-*.tli
-*.tlh
-*.tmp
-*.tmp_proj
-*.log
-*.vspscc
-*.vssscc
-.builds
-*.pidb
-*.svclog
-*.scc
-
-# Chutzpah Test files
-_Chutzpah*
-
-# Visual C++ cache files
-ipch/
-*.aps
-*.ncb
-*.opendb
-*.opensdf
-*.sdf
-*.cachefile
-*.VC.db
-*.VC.VC.opendb
-
-# Visual Studio profiler
-*.psess
-*.vsp
-*.vspx
-*.sap
-
-# TFS 2012 Local Workspace
-$tf/
-
-# Guidance Automation Toolkit
-*.gpState
-
-# ReSharper is a .NET coding add-in
-_ReSharper*/
-*.[Rr]e[Ss]harper
-*.DotSettings.user
-
-# JustCode is a .NET coding add-in
-.JustCode
-
-# TeamCity is a build add-in
-_TeamCity*
-
-# DotCover is a Code Coverage Tool
-*.dotCover
-
-# NCrunch
-_NCrunch_*
-.*crunch*.local.xml
-nCrunchTemp_*
-
-# MightyMoose
-*.mm.*
-AutoTest.Net/
-
-# Web workbench (sass)
-.sass-cache/
-
-# Installshield output folder
-[Ee]xpress/
-
-# DocProject is a documentation generator add-in
-DocProject/buildhelp/
-DocProject/Help/*.HxT
-DocProject/Help/*.HxC
-DocProject/Help/*.hhc
-DocProject/Help/*.hhk
-DocProject/Help/*.hhp
-DocProject/Help/Html2
-DocProject/Help/html
-
-# Click-Once directory
-publish/
-
-# Publish Web Output
-*.[Pp]ublish.xml
-*.azurePubxml
-# TODO: Comment the next line if you want to checkin your web deploy settings
-# but database connection strings (with potential passwords) will be unencrypted
-#*.pubxml
-*.publishproj
-
-# Microsoft Azure Web App publish settings. Comment the next line if you want to
-# checkin your Azure Web App publish settings, but sensitive information contained
-# in these scripts will be unencrypted
-PublishScripts/
-
-# NuGet Packages
-*.nupkg
-# The packages folder can be ignored because of Package Restore
-**/packages/*
-# except build/, which is used as an MSBuild target.
-!**/packages/build/
-# Uncomment if necessary however generally it will be regenerated when needed
-#!**/packages/repositories.config
-# NuGet v3's project.json files produces more ignoreable files
-*.nuget.props
-*.nuget.targets
-
-# Microsoft Azure Build Output
-csx/
-*.build.csdef
-
-# Microsoft Azure Emulator
-ecf/
-rcf/
-
-# Windows Store app package directories and files
-AppPackages/
-BundleArtifacts/
-Package.StoreAssociation.xml
-_pkginfo.txt
-
-# Visual Studio cache files
-# files ending in .cache can be ignored
-*.[Cc]ache
-# but keep track of directories ending in .cache
-!*.[Cc]ache/
-
-# Others
-ClientBin/
-~$*
-*~
-*.dbmdl
-*.dbproj.schemaview
-*.jfm
-*.pfx
-*.publishsettings
-node_modules/
-orleans.codegen.cs
-
-# Since there are multiple workflows, uncomment next line to ignore bower_components
-# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
-#bower_components/
-
-# RIA/Silverlight projects
-Generated_Code/
-
-# Backup & report files from converting an old project file
-# to a newer Visual Studio version. Backup files are not needed,
-# because we have git ;-)
-_UpgradeReport_Files/
-Backup*/
-UpgradeLog*.XML
-UpgradeLog*.htm
-
-# SQL Server files
-*.mdf
-*.ldf
-
-# Business Intelligence projects
-*.rdl.data
-*.bim.layout
-*.bim_*.settings
-
-# Microsoft Fakes
-FakesAssemblies/
-
-# GhostDoc plugin setting file
-*.GhostDoc.xml
-
-# Node.js Tools for Visual Studio
-.ntvs_analysis.dat
-
-# Visual Studio 6 build log
-*.plg
-
-# Visual Studio 6 workspace options file
-*.opt
-
-# Visual Studio LightSwitch build output
-**/*.HTMLClient/GeneratedArtifacts
-**/*.DesktopClient/GeneratedArtifacts
-**/*.DesktopClient/ModelManifest.xml
-**/*.Server/GeneratedArtifacts
-**/*.Server/ModelManifest.xml
-_Pvt_Extensions
-
-# Paket dependency manager
-.paket/paket.exe
-paket-files/
-
-# FAKE - F# Make
-.fake/
-
-# JetBrains Rider
-.idea/
-*.sln.iml
-
-# CodeRush
-.cr/
-
-# Python Tools for Visual Studio (PTVS)
-__pycache__/
-*.pyc

+ 0 - 548
TEAMModelFunction/ActivityHttpTrigger.cs

@@ -1,548 +0,0 @@
-using System;
-using System.IO;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Mvc;
-using Microsoft.Azure.WebJobs;
-using Microsoft.Azure.WebJobs.Extensions.Http;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.Logging;
-using TEAMModelOS.SDK.DI;
-using Azure.Cosmos;
-using System.Text.Json;
-using System.Collections.Generic;
-using TEAMModelOS.SDK.Models;
-using TEAMModelOS.SDK.Extension;
-using TEAMModelOS.SDK;
-using TEAMModelOS.SDK.Models.Cosmos;
-using TEAMModelOS.SDK.Models.Cosmos.Common;
-using System.Linq;
-using TEAMModelOS.Services.Common;
-using TEAMModelOS.SDK.Models.Service;
-using HTEXLib.COMM.Helpers;
-
-namespace TEAMModelFunction
-{
-    public   class ActivityHttpTrigger
-    {
-
-
-        private readonly AzureCosmosFactory _azureCosmos;
-        private readonly DingDing _dingDing;
-        private readonly AzureStorageFactory _azureStorage;
-        private readonly AzureRedisFactory _azureRedis;
-        public ActivityHttpTrigger(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage
-             , AzureRedisFactory azureRedis)
-        {
-            _azureCosmos = azureCosmos;
-            _dingDing = dingDing;
-            _azureStorage = azureStorage;
-            _azureRedis = azureRedis;
-        }
-
-        /// <summary>
-        /// 修复已存在的课程且未初始化学生课程列表的业务。
-        /// </summary>
-        /// <param name="req"></param>
-        /// <param name="log"></param>
-        /// <returns></returns>
-        [FunctionName("fix-stu-course")]
-        public  async Task<IActionResult> StuCourse([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log)
-        {
-            log.LogInformation("fix-stu-course...");
-            string originCode = await new StreamReader(req.Body).ReadToEndAsync();
-            List<Course> courses = new List<Course>();
-            var client = _azureCosmos.GetCosmosClient();
-            var query = $"select  *  from c ";
-            await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<Course>(queryText: query,
-                    requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Course-{originCode}") }))
-            {
-                courses.Add(item);
-            }
-            await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<Course>(queryText: query,
-                    requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Course-{originCode}") }))
-            {
-                courses.Add(item);
-            }
-            //2.获取课程的id 并尝试添加或移除对应的学生课程记录StuCourse。
-            foreach (var course in courses)
-            {
-                if (course.schedule.IsNotEmpty())
-                {
-                    foreach (var sc in course.schedule)
-                    {
-                        if (!string.IsNullOrEmpty(sc.stulist))
-                        {
-                            (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(client, _dingDing, new List<string>() { sc.stulist }, course.school);
-                            var addStudentsCls = tchList.FindAll(x => x.type == 2);
-                            var addTmdidsCls = tchList.FindAll(x => x.type == 1);
-                            foreach (var addStu in addStudentsCls)
-                            {
-                                var stuCourse = new StuCourse
-                                {
-                                    id = course.id,
-                                    scode = course.code,
-                                    name = course.name,
-                                    code = $"StuCourse-{course.school}-{addStu.id}",
-                                    scope = course.scope,
-                                    school = course.school,
-                                    creatorId = course.creatorId,
-                                    pk = "StuCourse",
-                                    createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
-                                };
-                                await client.GetContainer("TEAMModelOS", "Student").UpsertItemAsync(stuCourse, new PartitionKey(stuCourse.code));
-                            }
-                            foreach (var addTmd in addTmdidsCls)
-                            {
-                                var tmdCourse = new StuCourse
-                                {
-                                    id = course.id,
-                                    scode = course.code,
-                                    name = course.name,
-                                    code = $"StuCourse-{addTmd}",
-                                    scope = course.scope,
-                                    //school = courseChange.school,
-                                    creatorId = course.creatorId,
-                                    pk = "StuCourse",
-                                    createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
-                                };
-                                await client.GetContainer("TEAMModelOS", "Teacher").UpsertItemAsync(tmdCourse, new PartitionKey(tmdCourse.code));
-                            }
-                        }
-                    }
-                }
-            }
-            return new OkObjectResult(new { });
-        }
-        /// <summary>
-        /// 设置评测未初始化学生列表的
-        /// </summary>
-        /// <param name="req"></param>
-        /// <param name="log"></param>
-        /// <returns></returns>
-        [FunctionName("fix-exam-activity")]
-        public   async Task<IActionResult> ExamActivity([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,ILogger log)
-        {
-            log.LogInformation("fix-exam-activity...");
-            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
-            List<string> datas = JsonSerializer.Deserialize<List<string>>(requestBody);
-            var client = _azureCosmos.GetCosmosClient();
-           
-            var query = $"select  *  from c ";
-            foreach (string data in datas) {
-                List<ExamInfo> exams = new List<ExamInfo>();
-                await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(
-                    queryText: query,  requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Exam-{data}") }))
-                {
-                    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())
-                        {
-                            exams.Add(obj.ToObject<ExamInfo>());
-                        }
-                    }
-                }
-                log.LogInformation($"{exams.ToJsonString()}");
-                foreach (var info in exams)
-                {
-                    List<string> classes = ExamService.getClasses(info.classes,info.stuLists);
-                    if (!classes.IsNotEmpty())
-                    {
-                        continue;
-                    }
-                    List<string> sub = new List<string>();
-                    foreach (ExamSubject subject in info.subjects)
-                    {
-                        sub.Add(subject.id);
-                    }
-                    (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(client, _dingDing, classes, info.school);
-                    var addStudentsCls = tchList.FindAll(x => x.type == 2);
-                    var addTmdidsCls = tchList.FindAll(x => x.type == 1);
-                    List<StuActivity> stuActivities = new List<StuActivity>();
-                    List<StuActivity> tmdActivities = new List<StuActivity>();
-                    if (addTmdidsCls.IsNotEmpty())
-                    {
-                        addTmdidsCls.ForEach(x => {
-                            tmdActivities.Add(new StuActivity
-                            {
-                                pk = "Activity",
-                                id = info.id,
-                                code = $"Activity-{x.id}",
-                                type = "Exam",
-                                name = info.name,
-                                startTime = info.startTime,
-                                endTime = info.endTime,
-                                scode = info.code,
-                                scope = info.scope,
-                                school = info.school,
-                                creatorId = info.creatorId,
-                                subjects = sub,
-                                blob = null,
-                                owner = info.owner,
-                                createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
-                                taskStatus = -1,
-                                classIds = classes
-
-                            });
-                        });
-                    }
-                    if (addStudentsCls.IsNotEmpty())
-                    {
-                        addStudentsCls.ForEach(x => {
-                            stuActivities.Add(new StuActivity
-                            {
-                                pk = "Activity",
-                                id = info.id,
-                                code = $"Activity-{info.school}-{x.id}",
-                                type = "Exam",
-                                name = info.name,
-                                startTime = info.startTime,
-                                endTime = info.endTime,
-                                scode = info.code,
-                                scope = info.scope,
-                                school = info.school,
-                                creatorId = info.creatorId,
-                                subjects = sub,
-                                blob=null,
-                                owner = info.owner,
-                                createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
-                                taskStatus = -1,
-                                classIds = classes
-                            });
-                        });
-                    }
-                    await ActivityService.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities,null);
-                }
-            }
-            return new OkObjectResult(new { });
-        }
-        /// <summary>
-        /// 设置投票未初始化学生列表的业务
-        /// </summary>
-        /// <param name="req"></param>
-        /// <param name="log"></param>
-        /// <returns></returns>
-        [FunctionName("fix-vote-activity")]
-        public async Task<IActionResult> VoteActivity(
-            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
-            ILogger log)
-        {
-
-            log.LogInformation("fix-vote-activity...");
-            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
-            List<string> datas = JsonSerializer.Deserialize<List<string>>(requestBody);
-            var client = _azureCosmos.GetCosmosClient();
-
-            var query = $"select  *  from c ";
-            foreach (string data in datas)
-            {
-                List<Vote> votes = new List<Vote>();
-                await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(
-                    queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Vote-{data}") }))
-                {
-                    using var json = await JsonDocument.ParseAsync(item.ContentStream);
-                    if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
-                    {
-                        foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
-                        {
-                            votes.Add(obj.ToObject<Vote>());
-                        }
-                    }
-                }
-                log.LogInformation($"{votes.ToJsonString()}");
-                foreach (var info in votes)
-                {
-                    List<string> classes = ExamService.getClasses(info.classes, info.stuLists);
-                    if (classes.IsNotEmpty())
-                    {
-                        continue;
-                    }
-                    (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(client, _dingDing, classes, info.school);
-                    var addStudentsCls = tchList.FindAll(x => x.type == 2);
-                    var addTmdidsCls = tchList.FindAll(x => x.type == 1);
-                    List<StuActivity> stuActivities = new List<StuActivity>();
-                    List<StuActivity> tmdActivities = new List<StuActivity>();
-                    if (addTmdidsCls.IsNotEmpty())
-                    {
-                        addTmdidsCls.ForEach(x => {
-                            tmdActivities.Add(new StuActivity
-                            {
-                                pk = "Activity",
-                                id = info.id,
-                                code = $"Activity-{x.id}",
-                                type = "Vote",
-                                name = info.name,
-                                startTime = info.startTime,
-                                endTime = info.endTime,
-                                scode = info.code,
-                                scope = info.scope,
-                                school = info.school,
-                                creatorId = info.creatorId,
-                                subjects = new List<string>() { "" },
-                                blob = null,
-                                owner = info.owner,
-                                createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
-                                taskStatus = -1,
-                                classIds = classes
-
-                            });
-                        });
-                    }
-                    if (addStudentsCls.IsNotEmpty())
-                    {
-                        addStudentsCls.ForEach(x => {
-                            stuActivities.Add(new StuActivity
-                            {
-                                pk = "Activity",
-                                id = info.id,
-                                code = $"Activity-{info.school}-{x.id}",
-                                type = "Vote",
-                                name = info.name,
-                                startTime = info.startTime,
-                                endTime = info.endTime,
-                                scode = info.code,
-                                scope = info.scope,
-                                school = info.school,
-                                creatorId = info.creatorId,
-                                subjects = new List<string>() { "" },
-                                blob = null,
-                                owner = info.owner,
-                                createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
-                                taskStatus = -1,
-                                classIds = classes
-                            });
-                        });
-                    }
-                    await ActivityService.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities, null);
-                }
-            }
-            return new OkObjectResult(new { });
-        }
-
-        /// <summary>
-        /// 设置问卷调查未初始化学生列表的业务
-        /// </summary>
-        /// <param name="req"></param>
-        /// <param name="log"></param>
-        /// <returns></returns>
-        [FunctionName("fix-survey-activity")]
-        public async Task<IActionResult> SurveyActivity(
-            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
-            ILogger log)
-        {
-            log.LogInformation("fix-survey-activity...");
-            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
-            List<string> datas = JsonSerializer.Deserialize<List<string>>(requestBody);
-            var client = _azureCosmos.GetCosmosClient();
-
-            var query = $"select  *  from c ";
-            foreach (string data in datas)
-            {
-                List<Survey> surveys = new List<Survey>();
-                await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(
-                    queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Survey-{data}") }))
-                {
-                    using var json = await JsonDocument.ParseAsync(item.ContentStream);
-                    if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
-                    {
-                        foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
-                        {
-                            surveys.Add(obj.ToObject<Survey>());
-                        }
-                    }
-                }
-                log.LogInformation($"{surveys.ToJsonString()}");
-                foreach (var info in surveys)
-                {
-                    List<string> classes = ExamService.getClasses(info.classes, info.stuLists);
-                    if (!classes.IsNotEmpty())
-                    {
-                        continue;
-                    }
-                    (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(client, _dingDing, classes, info.school);
-                    var addStudentsCls = tchList.FindAll(x => x.type == 2);
-                    var addTmdidsCls = tchList.FindAll(x => x.type == 1);
-                    List<StuActivity> stuActivities = new List<StuActivity>();
-                    List<StuActivity> tmdActivities = new List<StuActivity>();
-                    if (addTmdidsCls.IsNotEmpty())
-                    {
-                        addTmdidsCls.ForEach(x => {
-                            tmdActivities.Add(new StuActivity
-                            {
-                                pk = "Activity",
-                                id = info.id,
-                                code = $"Activity-{x.id}",
-                                type = "Survey",
-                                name = info.name,
-                                startTime = info.startTime,
-                                endTime = info.endTime,
-                                scode = info.code,
-                                scope = info.scope,
-                                school = info.school,
-                                creatorId = info.creatorId,
-                                subjects = new List<string>() { "" },
-                                blob = info.blob,
-                                owner=info.owner,
-                                createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
-                                taskStatus = -1,
-                                classIds = classes
-
-                            });
-                        });
-                    }
-                    if (addStudentsCls.IsNotEmpty())
-                    {
-                        addStudentsCls.ForEach(x => {
-                            stuActivities.Add(new StuActivity
-                            {
-                                pk = "Activity",
-                                id = info.id,
-                                code = $"Activity-{info.school}-{x.id}",
-                                type = "Survey",
-                                name = info.name,
-                                startTime = info.startTime,
-                                endTime = info.endTime,
-                                scode = info.code,
-                                scope = info.scope,
-                                school = info.school,
-                                creatorId = info.creatorId,
-                                subjects = new List<string>() { "" },
-                                blob=info.blob,
-                                owner = info.owner,
-                                createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
-                                taskStatus = -1,
-                                classIds = classes
-                            });
-                        });
-                    }
-                    await ActivityService.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities, null);
-                }
-            }
-            return new OkObjectResult(new { });
-        }
-        
-       
-        /// <summary>
-        ///获取单个目录的大小,用于获取评测,试题,试卷,问卷,投票等 文件层级超过两层的文件。
-        ///例如 /exam/uuid/xxx  /item/uuid/xxx   /paper/uuid/xxx  /vote/uuid/xxx  /suervy/uuid/xxx
-        /// {"name":"hbcn","/item/uuid/xxx"}
-        /// </summary>
-        /// <param name="req"></param>
-        /// <param name="log"></param>
-        /// <returns></returns>
-        [FunctionName("get-prefixsize")]
-        public async Task<IActionResult> GetPrefixsize(
-            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
-            ILogger log)
-        {
-            try {
-                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
-                var data = System.Text.Json.JsonSerializer.Deserialize<JsonElement>(requestBody);
-                if (data.TryGetProperty("name", out JsonElement name) && data.TryGetProperty("root", out JsonElement root))
-                {
-                    var size = await _azureStorage.GetBlobContainerClient($"{name}").GetBlobsSize($"{root}");
-                    return new OkObjectResult(new { size = size });
-                }
-                else
-                {
-                    return new BadRequestResult();
-                }
-            } catch (Exception ex) {
-                await _dingDing.SendBotMsg($"TEAMModelFunction,ActivityHttpTrigger,get-prefixsize()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
-                return new BadRequestResult();
-            }
-
-        }
-        /// <summary>
-        ///获取多个blob路径的文件大小
-        /// {"name":"hbcn","blobs":["/paper/uuid/xxx.json","/paper/uuid/aaa.json"]}
-        /// </summary>
-        /// <param name="req"></param>
-        /// <param name="log"></param>
-        /// <returns></returns>
-        [FunctionName("used-space")]
-        public async Task<IActionResult> UsedSpace(
-            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
-            ILogger log)
-        {
-            try { 
-                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
-                var data = System.Text.Json.JsonSerializer.Deserialize<JsonElement>(requestBody);
-                if (data.TryGetProperty("name", out JsonElement name) && data.TryGetProperty("blobs", out JsonElement blob))
-                {
-                    List<string> blobs = JsonSerializer.Deserialize<List<string>>(blob.ToJsonString());
-                   var size= await _azureStorage.GetBlobContainerClient($"{name}").GetBlobsSize(blobs);
-                    return new OkObjectResult(new { size = size });
-                }
-                else {
-                    return new BadRequestResult();
-                }
-              
-            } catch (Exception ex)
-            {
-                await _dingDing.SendBotMsg($"TEAMModelFunction,ActivityHttpTrigger,get-blobsize()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
-                return new BadRequestResult();
-            }
-        }
-        /// <summary>
-        /// 修复容器的内容显示
-        /// </summary>
-        /// <param name="req"></param>
-        /// <param name="log"></param>
-        /// <returns></returns>
-        [FunctionName("fix-blob-content")]
-        public async Task<IActionResult> FixBlobContent(
-            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
-            ILogger log)
-        {
-            try
-            {
-                var client = _azureCosmos.GetCosmosClient();
-                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
-                var data = System.Text.Json.JsonSerializer.Deserialize<JsonElement>(requestBody);
-                await FixDataService.FixBlobContent(client, _dingDing, _azureStorage, data);
-                return new OkObjectResult(new { });
-            }
-            catch (Exception ex)
-            {
-                await _dingDing.SendBotMsg($"TEAMModelFunction,ActivityHttpTrigger,fix-blob-content()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
-                return new BadRequestResult();
-            }
-        }
-        /// <summary>
-        /// 修复容器的内容显示
-        /// </summary>
-        /// <param name="req"></param>
-        /// <param name="log"></param>
-        /// <returns></returns>
-        [FunctionName("fix-student-info")]
-        public async Task<IActionResult> FixStudentInfo(
-            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
-            ILogger log)
-        {
-            var client = _azureCosmos.GetCosmosClient();
-            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
-            var data = System.Text.Json.JsonSerializer.Deserialize<JsonElement>(requestBody);
-            await FixDataService.FixStudentInfo(client, _dingDing, _azureStorage, data);
-            return new OkObjectResult(new { });
-        }
-
-        /// <summary>
-        /// 修复评测publish字段内容
-        /// </summary>
-        /// <param name="req"></param>
-        /// <param name="log"></param>
-        /// <returns></returns>
-        [FunctionName("fix-exam-publish")]
-        public async Task<IActionResult> FixExamPublish(
-            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
-            ILogger log)
-        {
-            var client = _azureCosmos.GetCosmosClient();
-            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
-            var data = System.Text.Json.JsonSerializer.Deserialize<JsonElement>(requestBody);
-            List<string> infos = await FixDataService.FixExamPublish(client, data);
-            return new OkObjectResult(new { infos });
-        }
-    }
-}

+ 0 - 342
TEAMModelFunction/CourseServiceBus.cs

@@ -1,342 +0,0 @@
-using Azure.Cosmos;
-using Microsoft.Azure.WebJobs;
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Text.Json;
-using System.Threading.Tasks;
-using TEAMModelOS.SDK.DI;
-using TEAMModelOS.SDK.Extension;
-using TEAMModelOS.SDK;
-using TEAMModelOS.SDK.Models;
-using TEAMModelOS.SDK.Models.Cosmos.Common;
-using HTEXLib.COMM.Helpers;
-using TEAMModelOS.Models;
-using Microsoft.Extensions.Options;
-
-namespace TEAMModelFunction
-{
-    public class CourseServiceBus
-    {
-        private readonly AzureCosmosFactory _azureCosmos;
-        private readonly DingDing _dingDing;
-        private readonly Option _option;
-        public CourseServiceBus(AzureCosmosFactory azureCosmos, DingDing dingDing, IOptionsSnapshot<Option> option)
-        {
-            _azureCosmos = azureCosmos;
-            _dingDing = dingDing;
-            _option = option?.Value;
-        }
-
-        /// <summary>
-        /// 完善课程变更
-        /// </summary>
-        /// <data msg>
-        /// CourseChange
-        ///// </data>
-        /// <param name="msg"></param>
-        /// <returns></returns>
-        [FunctionName("Course")]
-        public async Task Course([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "course", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
-        {
-            var client = _azureCosmos.GetCosmosClient();
-            try
-            {
-                //await _dingDing.SendBotMsg($"ServiceBus,CourseChange:{msg}", GroupNames.醍摩豆服務運維群組);
-                var jsonMsg = JsonDocument.Parse(msg);
-                CourseChange courseChange = msg.ToObject<CourseChange>();
-                if (courseChange == null)
-                {
-                    return;
-                }
-                foreach (var cls in courseChange.addClass)
-                {
-                    (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(client, _dingDing, new List<string> { cls }, courseChange.school);
-                    var addStudentsCls = tchList.FindAll(x => x.type == 2);
-                    var addTmdidsCls = tchList.FindAll(x => x.type == 1);
-                    foreach (var stu in addStudentsCls)
-                    {
-                        try
-                        {
-                            ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
-                            if (!stuCourse.Value.classId.Contains(cls))
-                            {
-                                stuCourse.Value.classId.Add(cls);
-                            }
-                            await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
-                        }
-                        catch (CosmosException ex)
-                        {
-                            if (ex.Response.Status == 404)
-                            {
-                                var course = new StuCourse
-                                {
-                                    id = courseChange.id,
-                                    scode = courseChange.code,
-                                    name = courseChange.name,
-                                    code = $"StuCourse-{courseChange.school}-{stu.id}",
-                                    scope = courseChange.scope,
-                                    school = courseChange.school,
-                                    creatorId = courseChange.creatorId,
-                                    classId = new List<string> { cls },
-                                    pk = "StuCourse",
-                                    createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
-                                };
-                                await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
-
-                            }
-                            else {
-
-                                await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
-                            }
-                        }
-                    }
-                    foreach (var tmd in addTmdidsCls)
-                    {
-                        try
-                        {
-                            ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
-                            if (!stuCourse.Value.classId.Contains(cls))
-                            {
-                                stuCourse.Value.classId.Add(cls);
-                            }
-                            await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
-                        }
-                        catch (CosmosException ex)
-                        {
-                            if (ex.Response.Status == 404)
-                            {
-                                var course = new StuCourse
-                                {
-                                    id = courseChange.id,
-                                    scode = courseChange.code,
-                                    name = courseChange.name,
-                                    code = $"StuCourse-{tmd.id}",
-                                    scope = courseChange.scope,
-                                    school = courseChange.school,
-                                    creatorId = courseChange.creatorId,
-                                    classId = new List<string> { cls },
-                                    pk = "StuCourse",
-                                    createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
-                                };
-                                await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
-                            }
-                            else
-                            {
-
-                                await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
-                            }
-                        }
-                    }
-                }
-
-                foreach (var list in courseChange.addList)
-                {
-                    (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(client, _dingDing, new List<string> { list }, courseChange.school);
-                    var addStudentsCls = tchList.FindAll(x => x.type == 2);
-                    var addTmdidsCls = tchList.FindAll(x => x.type == 1);
-                    foreach (var stu in addStudentsCls)
-                    {
-                        try
-                        {
-                            ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
-                            if (!stuCourse.Value.stulist.Contains(list))
-                            {
-                                stuCourse.Value.stulist.Add(list);
-                                await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
-                            }
-                        }
-                        catch (CosmosException ex)
-                        {
-                            if (ex.Response.Status == 404)
-                            {
-                                var course = new StuCourse
-                                {
-                                    id = courseChange.id,
-                                    scode = courseChange.code,
-                                    name = courseChange.name,
-                                    code = $"StuCourse-{courseChange.school}-{stu.id}",
-                                    scope = courseChange.scope,
-                                    school = courseChange.school,
-                                    creatorId = courseChange.creatorId,
-                                    stulist = new List<string> { list },
-                                    pk = "StuCourse",
-                                    createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
-                                };
-                                await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
-                            }
-                            else
-                            {
-
-                                await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
-                            }
-                        }
-                    }
-                    foreach (var tmd in addTmdidsCls)
-                    {
-                        try
-                        {
-                            ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
-                            if (!stuCourse.Value.stulist.Contains(list))
-                            {
-                                stuCourse.Value.stulist.Add(list);
-                                await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
-                            }
-
-                        }
-                        catch (CosmosException ex)
-                        {
-                            if (ex.Response.Status == 404)
-                            {
-                                var course = new StuCourse
-                                {
-                                    id = courseChange.id,
-                                    scode = courseChange.code,
-                                    name = courseChange.name,
-                                    code = $"StuCourse-{tmd.id}",
-                                    scope = courseChange.scope,
-                                    school = courseChange.school,
-                                    creatorId = courseChange.creatorId,
-                                    stulist = new List<string> { list },
-                                    pk = "StuCourse",
-                                    createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
-                                };
-                                await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
-                            }
-                            else
-                            {
-
-                                await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
-                            }
-                        }
-                    }
-                }
-
-                foreach (var delCls in courseChange.delClass)
-                {
-                    (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(client, _dingDing, new List<string> { delCls }, courseChange.school);
-                    var delStudentsCls = tchList.FindAll(x => x.type == 2);
-                    var delTmdidsCls = tchList.FindAll(x => x.type == 1);
-                    foreach (var stu in delStudentsCls)
-                    {
-                        try
-                        {
-                            ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
-
-                            if (stuCourse.Value.classId.Contains(delCls))
-                            {
-                                stuCourse.Value.classId.Remove(delCls);
-                            }
-
-                            if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
-                            {
-                                //当两个列表都不存在时则直接删除
-                                await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
-                            }
-                            else
-                            {
-                                await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
-                            }
-
-                        }
-                        catch (CosmosException ex)
-                        {
-                            await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
-                        }
-                    }
-                    foreach (var tmd in delTmdidsCls)
-                    {
-                        try
-                        {
-                            ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
-
-                            if (stuCourse.Value.classId.Contains(delCls))
-                            {
-                                stuCourse.Value.classId.Remove(delCls);
-                            }
-
-                            if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
-                            {
-                                //当两个列表都不存在时则直接删除
-                                await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
-                            }
-                            else
-                            {
-                                await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
-                            }
-
-                        }
-                        catch (CosmosException ex)
-                        {
-                            await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
-                        }
-                    }
-                }
-                foreach (var delList in courseChange.delList)
-                {
-                    (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(client, _dingDing, new List<string> { delList }, courseChange.school);
-                    var delStudentsCls = tchList.FindAll(x => x.type == 2);
-                    var delTmdidsCls = tchList.FindAll(x => x.type == 1);
-                    foreach (var stu in delStudentsCls)
-                    {
-                        try
-                        {
-                            ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
-
-                            if (stuCourse.Value.stulist.Contains(delList))
-                            {
-                                stuCourse.Value.stulist.Remove(delList);
-                            }
-
-                            if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
-                            {
-                                //当两个列表都不存在时则直接删除
-                                await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
-                            }
-                            else
-                            {
-                                await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
-                            }
-
-                        }
-                        catch (CosmosException ex)
-                        {
-                            await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
-                        }
-                    }
-                    foreach (var tmd in delTmdidsCls)
-                    {
-                        try
-                        {
-                            ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
-
-                            if (stuCourse.Value.stulist.Contains(delList))
-                            {
-                                stuCourse.Value.stulist.Remove(delList);
-                            }
-
-                            if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
-                            {
-                                //当两个列表都不存在时则直接删除
-                                await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
-                            }
-                            else
-                            {
-                                await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
-                            }
-
-                        }
-                        catch (CosmosException ex)
-                        {
-                            await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
-                        }
-                    }
-                }
-            }
-            catch (Exception ex)
-            {
-                await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -Course\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
-            }
-        }
-    }
-}

+ 0 - 89
TEAMModelFunction/LessonHttpTrigger.cs

@@ -1,89 +0,0 @@
-using System;
-using System.IO;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Mvc;
-using Microsoft.Azure.WebJobs;
-using Microsoft.Azure.WebJobs.Extensions.Http;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.Logging;
-using Newtonsoft.Json;
-using TEAMModelOS.SDK.DI;
-using System.Text.Json;
-using TEAMModelOS.SDK.Models;
-using Azure.Cosmos;
-using TEAMModelOS.SDK.Extension;
-using TEAMModelOS.SDK.Models.Cosmos.Common;
-using System.Collections.Generic;
-using TEAMModelOS.SDK.Helper.Common.DateTimeHelper;
-
-namespace TEAMModelFunction
-{
-    public class LessonHttpTrigger
-    {
-        private readonly AzureCosmosFactory _azureCosmos;
-        private readonly DingDing _dingDing;
-        public LessonHttpTrigger(AzureCosmosFactory azureCosmos, DingDing dingDing)
-        {
-            _azureCosmos = azureCosmos;
-            _dingDing = dingDing;
-        }
-        [FunctionName("insert-class-count")]
-        public async Task<IActionResult> Run(
-            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
-            ILogger log)
-        {
-            log.LogInformation("C# HTTP trigger function processed a request.");
-            var client = _azureCosmos.GetCosmosClient();
-            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
-
-            var data = System.Text.Json.JsonSerializer.Deserialize<LessonRecord>(requestBody);
-            /*int day = DateTimeOffset.FromUnixTimeMilliseconds(data.startTime).DayOfYear;
-            int year = DateTimeOffset.FromUnixTimeMilliseconds(data.startTime).Year;
-            int days = DateTimeHelper.getDays(year);
-            //int years = DateTimeOffset.UtcNow.DayOfYear;
-            string tbname = string.Empty;
-            string code = string.Empty;
-            if (data.scope.Equals("school"))
-            {
-                code = $"LessonCount-{data.school}";
-                tbname = "School";
-            }
-            else
-            {
-                code = $"LessonCount";
-                tbname = "Teacher";
-            }
-            var response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(data.id.ToString(), new PartitionKey(code));
-            if (response.Status == 200)
-            {
-                using var json = await JsonDocument.ParseAsync(response.ContentStream);
-                LessonCount count = json.ToObject<LessonCount>();
-                if (count.courseIds.Count > 0)
-                {
-                    if (!count.courseIds.Contains(data.courseId))
-                    {
-                        count.courseIds.Add(data.courseId);
-                        count.beginCount[day] += 1;
-                    }
-                }
-                await client.GetContainer("TEAMModelOS", tbname).ReplaceItemAsync(count, count.id, new PartitionKey(code));
-            }
-            else
-            {
-                LessonCount count = new LessonCount
-                {
-                    id = data.tmdid,
-                    code = "LessonCount-" + data.school,
-                    year = year
-                };
-                double[] da = new double[days];
-                List<double> list = new List<double>(da);
-                list[day] += 1;
-                count.beginCount.AddRange(list);
-                //count.courseIds.Add(data.courseId);
-                await client.GetContainer("TEAMModelOS", "tbname").CreateItemAsync(count, new PartitionKey(code));
-            }*/
-            return new OkObjectResult(data);
-        }
-    }
-}

+ 0 - 155
TEAMModelFunction/MonitorCosmosDB.cs

@@ -1,155 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Net.Http;
-using System.Text.Json;
-using System.Threading.Tasks;
-using Azure.Cosmos;
-using Azure.Messaging.ServiceBus;
-using Microsoft.Azure.Documents;
-using Microsoft.Azure.WebJobs;
-using Microsoft.Extensions.Configuration;
-using Microsoft.Extensions.Logging;
-using TEAMModelOS.SDK.DI;
-using TEAMModelOS.SDK.Extension;
-using TEAMModelOS.SDK.Models;
-
-namespace TEAMModelFunction
-{
-    public class MonitorCosmosDB
-    {
-        private readonly AzureCosmosFactory _azureCosmos;
-        private readonly AzureServiceBusFactory _serviceBus;
-        private readonly AzureStorageFactory _azureStorage;
-        private readonly DingDing _dingDing;
-        private readonly AzureRedisFactory _azureRedis;
-         
-        private   IConfiguration _configuration { get; set; }
-        public MonitorCosmosDB( AzureCosmosFactory azureCosmos, AzureServiceBusFactory azureServiceBus, AzureStorageFactory azureStorage, DingDing dingDing, AzureRedisFactory azureRedis
-            , IConfiguration configuration
-            )
-        {
-            _azureCosmos = azureCosmos;
-            _serviceBus = azureServiceBus;
-            _azureStorage = azureStorage;
-            _dingDing = dingDing;
-            _azureRedis = azureRedis;
-            _configuration = configuration;
-        }
-        //[Function("Common")]
-        //public async Task Common([Microsoft.Azure.Functions.Worker.CosmosDBTriggerAttribute(
-        //    databaseName: "TEAMModelOS",
-        //    containerName: "Common",
-        //    Connection =    "Azure:Cosmos:ConnectionString",
-        //    LeaseContainerName = "leases",
-        //    LeaseContainerPrefix = "TEAMModelOS",
-        //    CreateLeaseContainerIfNotExists =true)]string josn, ILogger log)
-        //{
-        //    IReadOnlyList<Document> inputs = new List<Document>();
-
-
-        [FunctionName("Common")]
-        public async Task Common([Microsoft.Azure.WebJobs.CosmosDBTriggerAttribute(
-                databaseName: "TEAMModelOS",
-                collectionName: "Common",
-                ConnectionStringSetting  =    "Azure:Cosmos:ConnectionString",
-                LeaseCollectionName = "leases",
-                LeaseCollectionPrefix = "TEAMModelOS",
-                CreateLeaseCollectionIfNotExists  =true)]IReadOnlyList<Document> inputs, ILogger log)
-        {
-
-            if (inputs != null && inputs.Count > 0)
-            {
-                log.LogInformation("Documents modified " + inputs.Count);
-                log.LogInformation("First document Id " + inputs[0].Id);
-                var client = _azureCosmos.GetCosmosClient();
-                
-                foreach (var input in inputs)
-                {
-                    string pk = input.GetPropertyValue<string>("pk");
-                    if (!string.IsNullOrWhiteSpace(pk))
-                    {
-                        if (pk.Equals("Receiver", StringComparison.OrdinalIgnoreCase))
-                        { 
-                            ///通知接收者的变更
-                            return;
-                        }
-                        else {
-                            ///活动类型的变更
-                            int ttl = input.GetPropertyValue<int>("ttl");
-                            long stime = input.GetPropertyValue<long>("startTime");
-                            long etime = input.GetPropertyValue<long>("endTime");
-                            string school = input.GetPropertyValue<string>("school");
-                            string code = input.GetPropertyValue<string>("code");
-                            string creatorId = input.GetPropertyValue<string>("creatorId");
-                            string progress = input.GetPropertyValue<string>("progress");
-                            string scope = input.GetPropertyValue<string>("scope");
-                            string name = input.GetPropertyValue<string>("name");
-                            int? status = input.GetPropertyValue<int?>("status");
-                            int? publish = input.GetPropertyValue<int?>("publish");
-                            var data = new TriggerData
-                            {
-                                stime = stime,
-                                etime = etime,
-                                school = school,
-                                code = code,
-                                creatorId = creatorId,
-                                progress = progress,
-                                scope = scope,
-                                ttl = ttl,
-                                id = input.Id,
-                                status = status,
-                                name = name,
-                                publish = publish
-                            };
-#if DEBUG
-                            await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDBTrigger,{pk}触发变更\n{data.ToJsonString()}",
-                                            GroupNames.成都开发測試群組);
-#endif
-                            switch (pk)
-                            {
-                                case "Exam":
-                                  await  TriggerExam.Trigger(_azureCosmos, _serviceBus, _azureStorage, _dingDing, client, input, code, stime, etime, school);
-                                    break;
-                                case "Vote":
-                                    await TriggerVote.Trigger(_serviceBus, _azureStorage, _dingDing, client, input, data, _azureRedis, _configuration);
-                                    break;
-                                case "Survey":
-                                    await TriggerSurvey.Trigger(_serviceBus, _azureStorage, _dingDing, client, input, data, _azureRedis, _configuration);
-                                    break;
-                                case "Correct":
-                                    await TriggerCorrect.Trigger(_serviceBus, _azureStorage, _dingDing, client, input, data, _azureRedis);
-                                    break;
-                                case "ExamLite":
-                                    await TriggerExamLite.Trigger(_serviceBus, _azureStorage, _dingDing, client, input, data, _azureRedis, _configuration);
-                                    break;
-                                case "Study":
-                                    await TriggerStudy.Trigger(_serviceBus, _azureStorage, _dingDing, client, input, data, _azureRedis, _configuration);
-                                    break;
-                                case "Homework":
-                                    await TriggerHomework.Trigger(_serviceBus, _azureStorage, _dingDing, client, input, data, _azureRedis, _configuration);
-                                    break;
-
-                            }
-
-                        }
-                        
-                    }
-                }
-            }
-        }
-    }
-    public class TriggerData {
-        public int? status { get; set; }
-        public string name { get; set; }
-        public long stime { get; set; }
-        public long etime { get; set; }
-        public string school { get; set; }
-        public string code { get; set; }
-        public string creatorId { get; set; }
-        public string progress { get; set; }
-        public string scope { get; set; }
-        public int ttl { get; set; }
-        public string id { get; set; }
-        public int? publish { get; set; }
-    }
-}

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 0 - 1033
TEAMModelFunction/MonitorServicesBus.cs


+ 0 - 175
TEAMModelFunction/Properties/ServiceDependencies/TEAMModelOSFunction - Zip Deploy/profile.arm.json

@@ -1,175 +0,0 @@
-{
-  "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
-  "contentVersion": "1.0.0.0",
-  "metadata": {
-    "_dependencyType": "function.windows.appService"
-  },
-  "parameters": {
-    "resourceGroupName": {
-      "type": "string",
-      "defaultValue": "TEAMModelChengdu",
-      "metadata": {
-        "description": "Name of the resource group for the resource. It is recommended to put resources under same resource group for better tracking."
-      }
-    },
-    "resourceGroupLocation": {
-      "type": "string",
-      "defaultValue": "",
-      "metadata": {
-        "description": "Location of the resource group. Resource groups could have different location than resources, however by default we use API versions from latest hybrid profile which support all locations for resource types we support."
-      }
-    },
-    "resourceName": {
-      "type": "string",
-      "defaultValue": "TEAMModelOSFunction",
-      "metadata": {
-        "description": "Name of the main resource to be created by this template."
-      }
-    },
-    "resourceLocation": {
-      "type": "string",
-      "defaultValue": "[parameters('resourceGroupLocation')]",
-      "metadata": {
-        "description": "Location of the resource. By default use resource group's location, unless the resource provider is not supported there."
-      }
-    }
-  },
-  "resources": [
-    {
-      "type": "Microsoft.Resources/resourceGroups",
-      "name": "[parameters('resourceGroupName')]",
-      "location": "[parameters('resourceGroupLocation')]",
-      "apiVersion": "2019-10-01"
-    },
-    {
-      "type": "Microsoft.Resources/deployments",
-      "name": "[concat(parameters('resourceGroupName'), 'Deployment', uniqueString(concat(parameters('resourceName'), subscription().subscriptionId)))]",
-      "resourceGroup": "[parameters('resourceGroupName')]",
-      "apiVersion": "2019-10-01",
-      "dependsOn": [
-        "[parameters('resourceGroupName')]"
-      ],
-      "properties": {
-        "mode": "Incremental",
-        "expressionEvaluationOptions": {
-          "scope": "inner"
-        },
-        "parameters": {
-          "resourceGroupName": {
-            "value": "[parameters('resourceGroupName')]"
-          },
-          "resourceGroupLocation": {
-            "value": "[parameters('resourceGroupLocation')]"
-          },
-          "resourceName": {
-            "value": "[parameters('resourceName')]"
-          },
-          "resourceLocation": {
-            "value": "[parameters('resourceLocation')]"
-          }
-        },
-        "template": {
-          "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
-          "contentVersion": "1.0.0.0",
-          "parameters": {
-            "resourceGroupName": {
-              "type": "string"
-            },
-            "resourceGroupLocation": {
-              "type": "string"
-            },
-            "resourceName": {
-              "type": "string"
-            },
-            "resourceLocation": {
-              "type": "string"
-            }
-          },
-          "variables": {
-            "storage_name": "[toLower(concat('storage', uniqueString(concat(parameters('resourceName'), subscription().subscriptionId))))]",
-            "appServicePlan_name": "[concat('Plan', uniqueString(concat(parameters('resourceName'), subscription().subscriptionId)))]",
-            "storage_ResourceId": "[concat('/subscriptions/', subscription().subscriptionId, '/resourceGroups/', parameters('resourceGroupName'), '/providers/Microsoft.Storage/storageAccounts/', variables('storage_name'))]",
-            "appServicePlan_ResourceId": "[concat('/subscriptions/', subscription().subscriptionId, '/resourceGroups/', parameters('resourceGroupName'), '/providers/Microsoft.Web/serverFarms/', variables('appServicePlan_name'))]",
-            "function_ResourceId": "[concat('/subscriptions/', subscription().subscriptionId, '/resourceGroups/', parameters('resourceGroupName'), '/providers/Microsoft.Web/sites/', parameters('resourceName'))]"
-          },
-          "resources": [
-            {
-              "location": "[parameters('resourceLocation')]",
-              "name": "[parameters('resourceName')]",
-              "type": "Microsoft.Web/sites",
-              "apiVersion": "2015-08-01",
-              "tags": {
-                "[concat('hidden-related:', variables('appServicePlan_ResourceId'))]": "empty"
-              },
-              "dependsOn": [
-                "[variables('appServicePlan_ResourceId')]",
-                "[variables('storage_ResourceId')]"
-              ],
-              "kind": "functionapp",
-              "properties": {
-                "name": "[parameters('resourceName')]",
-                "kind": "functionapp",
-                "httpsOnly": true,
-                "reserved": false,
-                "serverFarmId": "[variables('appServicePlan_ResourceId')]",
-                "siteConfig": {
-                  "alwaysOn": true
-                }
-              },
-              "identity": {
-                "type": "SystemAssigned"
-              },
-              "resources": [
-                {
-                  "name": "appsettings",
-                  "type": "config",
-                  "apiVersion": "2015-08-01",
-                  "dependsOn": [
-                    "[variables('function_ResourceId')]"
-                  ],
-                  "properties": {
-                    "AzureWebJobsDashboard": "[concat('DefaultEndpointsProtocol=https;AccountName=', variables('storage_name'), ';AccountKey=', listKeys(variables('storage_ResourceId'), '2017-10-01').keys[0].value, ';EndpointSuffix=', 'core.windows.net')]",
-                    "AzureWebJobsStorage": "[concat('DefaultEndpointsProtocol=https;AccountName=', variables('storage_name'), ';AccountKey=', listKeys(variables('storage_ResourceId'), '2017-10-01').keys[0].value, ';EndpointSuffix=', 'core.windows.net')]",
-                    "FUNCTIONS_EXTENSION_VERSION": "~3",
-                    "FUNCTIONS_WORKER_RUNTIME": "dotnet"
-                  }
-                }
-              ]
-            },
-            {
-              "location": "[parameters('resourceGroupLocation')]",
-              "name": "[variables('storage_name')]",
-              "type": "Microsoft.Storage/storageAccounts",
-              "apiVersion": "2017-10-01",
-              "tags": {
-                "[concat('hidden-related:', concat('/providers/Microsoft.Web/sites/', parameters('resourceName')))]": "empty"
-              },
-              "properties": {
-                "supportsHttpsTrafficOnly": true
-              },
-              "sku": {
-                "name": "Standard_LRS"
-              },
-              "kind": "Storage"
-            },
-            {
-              "location": "[parameters('resourceGroupLocation')]",
-              "name": "[variables('appServicePlan_name')]",
-              "type": "Microsoft.Web/serverFarms",
-              "apiVersion": "2015-08-01",
-              "sku": {
-                "name": "S1",
-                "tier": "Standard",
-                "family": "S",
-                "size": "S1"
-              },
-              "properties": {
-                "name": "[variables('appServicePlan_name')]"
-              }
-            }
-          ]
-        }
-      }
-    }
-  ]
-}

+ 0 - 113
TEAMModelFunction/Properties/ServiceDependencies/TEAMModelOSFunction - Zip 部署/profile.arm.json

@@ -1,113 +0,0 @@
-{
-  "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
-  "contentVersion": "1.0.0.0",
-  "metadata": {
-    "_dependencyType": "appService.windows"
-  },
-  "parameters": {
-    "resourceGroupName": {
-      "type": "string",
-      "defaultValue": "TEAMModelChengdu",
-      "metadata": {
-        "description": "Name of the resource group for the resource. It is recommended to put resources under same resource group for better tracking."
-      }
-    },
-    "resourceGroupLocation": {
-      "type": "string",
-      "defaultValue": "",
-      "metadata": {
-        "description": "Location of the resource group. Resource groups could have different location than resources, however by default we use API versions from latest hybrid profile which support all locations for resource types we support."
-      }
-    },
-    "resourceName": {
-      "type": "string",
-      "defaultValue": "TEAMModelOSFunction",
-      "metadata": {
-        "description": "Name of the main resource to be created by this template."
-      }
-    },
-    "resourceLocation": {
-      "type": "string",
-      "defaultValue": "[parameters('resourceGroupLocation')]",
-      "metadata": {
-        "description": "Location of the resource. By default use resource group's location, unless the resource provider is not supported there."
-      }
-    }
-  },
-  "variables": {
-    "appServicePlan_name": "[concat('Plan', uniqueString(concat(parameters('resourceName'), subscription().subscriptionId)))]",
-    "appServicePlan_ResourceId": "[concat('/subscriptions/', subscription().subscriptionId, '/resourceGroups/', parameters('resourceGroupName'), '/providers/Microsoft.Web/serverFarms/', variables('appServicePlan_name'))]"
-  },
-  "resources": [
-    {
-      "type": "Microsoft.Resources/resourceGroups",
-      "name": "[parameters('resourceGroupName')]",
-      "location": "[parameters('resourceGroupLocation')]",
-      "apiVersion": "2019-10-01"
-    },
-    {
-      "type": "Microsoft.Resources/deployments",
-      "name": "[concat(parameters('resourceGroupName'), 'Deployment', uniqueString(concat(parameters('resourceName'), subscription().subscriptionId)))]",
-      "resourceGroup": "[parameters('resourceGroupName')]",
-      "apiVersion": "2019-10-01",
-      "dependsOn": [
-        "[parameters('resourceGroupName')]"
-      ],
-      "properties": {
-        "mode": "Incremental",
-        "template": {
-          "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
-          "contentVersion": "1.0.0.0",
-          "resources": [
-            {
-              "location": "[parameters('resourceLocation')]",
-              "name": "[parameters('resourceName')]",
-              "type": "Microsoft.Web/sites",
-              "apiVersion": "2015-08-01",
-              "tags": {
-                "[concat('hidden-related:', variables('appServicePlan_ResourceId'))]": "empty"
-              },
-              "dependsOn": [
-                "[variables('appServicePlan_ResourceId')]"
-              ],
-              "kind": "app",
-              "properties": {
-                "name": "[parameters('resourceName')]",
-                "kind": "app",
-                "httpsOnly": true,
-                "reserved": false,
-                "serverFarmId": "[variables('appServicePlan_ResourceId')]",
-                "siteConfig": {
-                  "metadata": [
-                    {
-                      "name": "CURRENT_STACK",
-                      "value": "dotnetcore"
-                    }
-                  ]
-                }
-              },
-              "identity": {
-                "type": "SystemAssigned"
-              }
-            },
-            {
-              "location": "[parameters('resourceLocation')]",
-              "name": "[variables('appServicePlan_name')]",
-              "type": "Microsoft.Web/serverFarms",
-              "apiVersion": "2015-08-01",
-              "sku": {
-                "name": "S1",
-                "tier": "Standard",
-                "family": "S",
-                "size": "S1"
-              },
-              "properties": {
-                "name": "[variables('appServicePlan_name')]"
-              }
-            }
-          ]
-        }
-      }
-    }
-  ]
-}

+ 0 - 113
TEAMModelFunction/Properties/ServiceDependencies/TEAMModelOSFunction - 压缩部署/profile.arm.json

@@ -1,113 +0,0 @@
-{
-  "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
-  "contentVersion": "1.0.0.0",
-  "metadata": {
-    "_dependencyType": "appService.windows"
-  },
-  "parameters": {
-    "resourceGroupName": {
-      "type": "string",
-      "defaultValue": "TEAMModelChengdu",
-      "metadata": {
-        "description": "Name of the resource group for the resource. It is recommended to put resources under same resource group for better tracking."
-      }
-    },
-    "resourceGroupLocation": {
-      "type": "string",
-      "defaultValue": "",
-      "metadata": {
-        "description": "Location of the resource group. Resource groups could have different location than resources, however by default we use API versions from latest hybrid profile which support all locations for resource types we support."
-      }
-    },
-    "resourceName": {
-      "type": "string",
-      "defaultValue": "TEAMModelOSFunction",
-      "metadata": {
-        "description": "Name of the main resource to be created by this template."
-      }
-    },
-    "resourceLocation": {
-      "type": "string",
-      "defaultValue": "[parameters('resourceGroupLocation')]",
-      "metadata": {
-        "description": "Location of the resource. By default use resource group's location, unless the resource provider is not supported there."
-      }
-    }
-  },
-  "variables": {
-    "appServicePlan_name": "[concat('Plan', uniqueString(concat(parameters('resourceName'), subscription().subscriptionId)))]",
-    "appServicePlan_ResourceId": "[concat('/subscriptions/', subscription().subscriptionId, '/resourceGroups/', parameters('resourceGroupName'), '/providers/Microsoft.Web/serverFarms/', variables('appServicePlan_name'))]"
-  },
-  "resources": [
-    {
-      "type": "Microsoft.Resources/resourceGroups",
-      "name": "[parameters('resourceGroupName')]",
-      "location": "[parameters('resourceGroupLocation')]",
-      "apiVersion": "2019-10-01"
-    },
-    {
-      "type": "Microsoft.Resources/deployments",
-      "name": "[concat(parameters('resourceGroupName'), 'Deployment', uniqueString(concat(parameters('resourceName'), subscription().subscriptionId)))]",
-      "resourceGroup": "[parameters('resourceGroupName')]",
-      "apiVersion": "2019-10-01",
-      "dependsOn": [
-        "[parameters('resourceGroupName')]"
-      ],
-      "properties": {
-        "mode": "Incremental",
-        "template": {
-          "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
-          "contentVersion": "1.0.0.0",
-          "resources": [
-            {
-              "location": "[parameters('resourceLocation')]",
-              "name": "[parameters('resourceName')]",
-              "type": "Microsoft.Web/sites",
-              "apiVersion": "2015-08-01",
-              "tags": {
-                "[concat('hidden-related:', variables('appServicePlan_ResourceId'))]": "empty"
-              },
-              "dependsOn": [
-                "[variables('appServicePlan_ResourceId')]"
-              ],
-              "kind": "app",
-              "properties": {
-                "name": "[parameters('resourceName')]",
-                "kind": "app",
-                "httpsOnly": true,
-                "reserved": false,
-                "serverFarmId": "[variables('appServicePlan_ResourceId')]",
-                "siteConfig": {
-                  "metadata": [
-                    {
-                      "name": "CURRENT_STACK",
-                      "value": "dotnetcore"
-                    }
-                  ]
-                }
-              },
-              "identity": {
-                "type": "SystemAssigned"
-              }
-            },
-            {
-              "location": "[parameters('resourceLocation')]",
-              "name": "[variables('appServicePlan_name')]",
-              "type": "Microsoft.Web/serverFarms",
-              "apiVersion": "2015-08-01",
-              "sku": {
-                "name": "S1",
-                "tier": "Standard",
-                "family": "S",
-                "size": "S1"
-              },
-              "properties": {
-                "name": "[variables('appServicePlan_name')]"
-              }
-            }
-          ]
-        }
-      }
-    }
-  ]
-}

+ 0 - 175
TEAMModelFunction/Properties/ServiceDependencies/teammodelosfunction-test - Zip Deploy/profile.arm.json

@@ -1,175 +0,0 @@
-{
-  "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
-  "contentVersion": "1.0.0.0",
-  "metadata": {
-    "_dependencyType": "function.windows.appService"
-  },
-  "parameters": {
-    "resourceGroupName": {
-      "type": "string",
-      "defaultValue": "TEAMModelChengdu",
-      "metadata": {
-        "description": "Name of the resource group for the resource. It is recommended to put resources under same resource group for better tracking."
-      }
-    },
-    "resourceGroupLocation": {
-      "type": "string",
-      "defaultValue": "",
-      "metadata": {
-        "description": "Location of the resource group. Resource groups could have different location than resources, however by default we use API versions from latest hybrid profile which support all locations for resource types we support."
-      }
-    },
-    "resourceName": {
-      "type": "string",
-      "defaultValue": "test",
-      "metadata": {
-        "description": "Name of the main resource to be created by this template."
-      }
-    },
-    "resourceLocation": {
-      "type": "string",
-      "defaultValue": "[parameters('resourceGroupLocation')]",
-      "metadata": {
-        "description": "Location of the resource. By default use resource group's location, unless the resource provider is not supported there."
-      }
-    }
-  },
-  "resources": [
-    {
-      "type": "Microsoft.Resources/resourceGroups",
-      "name": "[parameters('resourceGroupName')]",
-      "location": "[parameters('resourceGroupLocation')]",
-      "apiVersion": "2019-10-01"
-    },
-    {
-      "type": "Microsoft.Resources/deployments",
-      "name": "[concat(parameters('resourceGroupName'), 'Deployment', uniqueString(concat(parameters('resourceName'), subscription().subscriptionId)))]",
-      "resourceGroup": "[parameters('resourceGroupName')]",
-      "apiVersion": "2019-10-01",
-      "dependsOn": [
-        "[parameters('resourceGroupName')]"
-      ],
-      "properties": {
-        "mode": "Incremental",
-        "expressionEvaluationOptions": {
-          "scope": "inner"
-        },
-        "parameters": {
-          "resourceGroupName": {
-            "value": "[parameters('resourceGroupName')]"
-          },
-          "resourceGroupLocation": {
-            "value": "[parameters('resourceGroupLocation')]"
-          },
-          "resourceName": {
-            "value": "[parameters('resourceName')]"
-          },
-          "resourceLocation": {
-            "value": "[parameters('resourceLocation')]"
-          }
-        },
-        "template": {
-          "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
-          "contentVersion": "1.0.0.0",
-          "parameters": {
-            "resourceGroupName": {
-              "type": "string"
-            },
-            "resourceGroupLocation": {
-              "type": "string"
-            },
-            "resourceName": {
-              "type": "string"
-            },
-            "resourceLocation": {
-              "type": "string"
-            }
-          },
-          "variables": {
-            "storage_name": "[toLower(concat('storage', uniqueString(concat(parameters('resourceName'), subscription().subscriptionId))))]",
-            "appServicePlan_name": "[concat('Plan', uniqueString(concat(parameters('resourceName'), subscription().subscriptionId)))]",
-            "storage_ResourceId": "[concat('/subscriptions/', subscription().subscriptionId, '/resourceGroups/', parameters('resourceGroupName'), '/providers/Microsoft.Storage/storageAccounts/', variables('storage_name'))]",
-            "appServicePlan_ResourceId": "[concat('/subscriptions/', subscription().subscriptionId, '/resourceGroups/', parameters('resourceGroupName'), '/providers/Microsoft.Web/serverFarms/', variables('appServicePlan_name'))]",
-            "function_ResourceId": "[concat('/subscriptions/', subscription().subscriptionId, '/resourceGroups/', parameters('resourceGroupName'), '/providers/Microsoft.Web/sites/', parameters('resourceName'))]"
-          },
-          "resources": [
-            {
-              "location": "[parameters('resourceLocation')]",
-              "name": "[parameters('resourceName')]",
-              "type": "Microsoft.Web/sites",
-              "apiVersion": "2015-08-01",
-              "tags": {
-                "[concat('hidden-related:', variables('appServicePlan_ResourceId'))]": "empty"
-              },
-              "dependsOn": [
-                "[variables('appServicePlan_ResourceId')]",
-                "[variables('storage_ResourceId')]"
-              ],
-              "kind": "functionapp",
-              "properties": {
-                "name": "[parameters('resourceName')]",
-                "kind": "functionapp",
-                "httpsOnly": true,
-                "reserved": false,
-                "serverFarmId": "[variables('appServicePlan_ResourceId')]",
-                "siteConfig": {
-                  "alwaysOn": true
-                }
-              },
-              "identity": {
-                "type": "SystemAssigned"
-              },
-              "resources": [
-                {
-                  "name": "appsettings",
-                  "type": "config",
-                  "apiVersion": "2015-08-01",
-                  "dependsOn": [
-                    "[variables('function_ResourceId')]"
-                  ],
-                  "properties": {
-                    "AzureWebJobsDashboard": "[concat('DefaultEndpointsProtocol=https;AccountName=', variables('storage_name'), ';AccountKey=', listKeys(variables('storage_ResourceId'), '2017-10-01').keys[0].value, ';EndpointSuffix=', 'core.windows.net')]",
-                    "AzureWebJobsStorage": "[concat('DefaultEndpointsProtocol=https;AccountName=', variables('storage_name'), ';AccountKey=', listKeys(variables('storage_ResourceId'), '2017-10-01').keys[0].value, ';EndpointSuffix=', 'core.windows.net')]",
-                    "FUNCTIONS_EXTENSION_VERSION": "~3",
-                    "FUNCTIONS_WORKER_RUNTIME": "dotnet"
-                  }
-                }
-              ]
-            },
-            {
-              "location": "[parameters('resourceGroupLocation')]",
-              "name": "[variables('storage_name')]",
-              "type": "Microsoft.Storage/storageAccounts",
-              "apiVersion": "2017-10-01",
-              "tags": {
-                "[concat('hidden-related:', concat('/providers/Microsoft.Web/sites/', parameters('resourceName')))]": "empty"
-              },
-              "properties": {
-                "supportsHttpsTrafficOnly": true
-              },
-              "sku": {
-                "name": "Standard_LRS"
-              },
-              "kind": "Storage"
-            },
-            {
-              "location": "[parameters('resourceGroupLocation')]",
-              "name": "[variables('appServicePlan_name')]",
-              "type": "Microsoft.Web/serverFarms",
-              "apiVersion": "2015-08-01",
-              "sku": {
-                "name": "S1",
-                "tier": "Standard",
-                "family": "S",
-                "size": "S1"
-              },
-              "properties": {
-                "name": "[variables('appServicePlan_name')]"
-              }
-            }
-          ]
-        }
-      }
-    }
-  ]
-}

+ 0 - 175
TEAMModelFunction/Properties/ServiceDependencies/teammodelosfunction__test - 压缩部署/profile.arm.json

@@ -1,175 +0,0 @@
-{
-  "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
-  "contentVersion": "1.0.0.0",
-  "metadata": {
-    "_dependencyType": "function.windows.appService"
-  },
-  "parameters": {
-    "resourceGroupName": {
-      "type": "string",
-      "defaultValue": "TEAMModelChengdu",
-      "metadata": {
-        "description": "Name of the resource group for the resource. It is recommended to put resources under same resource group for better tracking."
-      }
-    },
-    "resourceGroupLocation": {
-      "type": "string",
-      "defaultValue": "",
-      "metadata": {
-        "description": "Location of the resource group. Resource groups could have different location than resources, however by default we use API versions from latest hybrid profile which support all locations for resource types we support."
-      }
-    },
-    "resourceName": {
-      "type": "string",
-      "defaultValue": "test",
-      "metadata": {
-        "description": "Name of the main resource to be created by this template."
-      }
-    },
-    "resourceLocation": {
-      "type": "string",
-      "defaultValue": "[parameters('resourceGroupLocation')]",
-      "metadata": {
-        "description": "Location of the resource. By default use resource group's location, unless the resource provider is not supported there."
-      }
-    }
-  },
-  "resources": [
-    {
-      "type": "Microsoft.Resources/resourceGroups",
-      "name": "[parameters('resourceGroupName')]",
-      "location": "[parameters('resourceGroupLocation')]",
-      "apiVersion": "2019-10-01"
-    },
-    {
-      "type": "Microsoft.Resources/deployments",
-      "name": "[concat(parameters('resourceGroupName'), 'Deployment', uniqueString(concat(parameters('resourceName'), subscription().subscriptionId)))]",
-      "resourceGroup": "[parameters('resourceGroupName')]",
-      "apiVersion": "2019-10-01",
-      "dependsOn": [
-        "[parameters('resourceGroupName')]"
-      ],
-      "properties": {
-        "mode": "Incremental",
-        "expressionEvaluationOptions": {
-          "scope": "inner"
-        },
-        "parameters": {
-          "resourceGroupName": {
-            "value": "[parameters('resourceGroupName')]"
-          },
-          "resourceGroupLocation": {
-            "value": "[parameters('resourceGroupLocation')]"
-          },
-          "resourceName": {
-            "value": "[parameters('resourceName')]"
-          },
-          "resourceLocation": {
-            "value": "[parameters('resourceLocation')]"
-          }
-        },
-        "template": {
-          "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
-          "contentVersion": "1.0.0.0",
-          "parameters": {
-            "resourceGroupName": {
-              "type": "string"
-            },
-            "resourceGroupLocation": {
-              "type": "string"
-            },
-            "resourceName": {
-              "type": "string"
-            },
-            "resourceLocation": {
-              "type": "string"
-            }
-          },
-          "variables": {
-            "storage_name": "[toLower(concat('storage', uniqueString(concat(parameters('resourceName'), subscription().subscriptionId))))]",
-            "appServicePlan_name": "[concat('Plan', uniqueString(concat(parameters('resourceName'), subscription().subscriptionId)))]",
-            "storage_ResourceId": "[concat('/subscriptions/', subscription().subscriptionId, '/resourceGroups/', parameters('resourceGroupName'), '/providers/Microsoft.Storage/storageAccounts/', variables('storage_name'))]",
-            "appServicePlan_ResourceId": "[concat('/subscriptions/', subscription().subscriptionId, '/resourceGroups/', parameters('resourceGroupName'), '/providers/Microsoft.Web/serverFarms/', variables('appServicePlan_name'))]",
-            "function_ResourceId": "[concat('/subscriptions/', subscription().subscriptionId, '/resourceGroups/', parameters('resourceGroupName'), '/providers/Microsoft.Web/sites/', parameters('resourceName'))]"
-          },
-          "resources": [
-            {
-              "location": "[parameters('resourceLocation')]",
-              "name": "[parameters('resourceName')]",
-              "type": "Microsoft.Web/sites",
-              "apiVersion": "2015-08-01",
-              "tags": {
-                "[concat('hidden-related:', variables('appServicePlan_ResourceId'))]": "empty"
-              },
-              "dependsOn": [
-                "[variables('appServicePlan_ResourceId')]",
-                "[variables('storage_ResourceId')]"
-              ],
-              "kind": "functionapp",
-              "properties": {
-                "name": "[parameters('resourceName')]",
-                "kind": "functionapp",
-                "httpsOnly": true,
-                "reserved": false,
-                "serverFarmId": "[variables('appServicePlan_ResourceId')]",
-                "siteConfig": {
-                  "alwaysOn": true
-                }
-              },
-              "identity": {
-                "type": "SystemAssigned"
-              },
-              "resources": [
-                {
-                  "name": "appsettings",
-                  "type": "config",
-                  "apiVersion": "2015-08-01",
-                  "dependsOn": [
-                    "[variables('function_ResourceId')]"
-                  ],
-                  "properties": {
-                    "AzureWebJobsDashboard": "[concat('DefaultEndpointsProtocol=https;AccountName=', variables('storage_name'), ';AccountKey=', listKeys(variables('storage_ResourceId'), '2017-10-01').keys[0].value, ';EndpointSuffix=', 'core.windows.net')]",
-                    "AzureWebJobsStorage": "[concat('DefaultEndpointsProtocol=https;AccountName=', variables('storage_name'), ';AccountKey=', listKeys(variables('storage_ResourceId'), '2017-10-01').keys[0].value, ';EndpointSuffix=', 'core.windows.net')]",
-                    "FUNCTIONS_EXTENSION_VERSION": "~3",
-                    "FUNCTIONS_WORKER_RUNTIME": "dotnet"
-                  }
-                }
-              ]
-            },
-            {
-              "location": "[parameters('resourceGroupLocation')]",
-              "name": "[variables('storage_name')]",
-              "type": "Microsoft.Storage/storageAccounts",
-              "apiVersion": "2017-10-01",
-              "tags": {
-                "[concat('hidden-related:', concat('/providers/Microsoft.Web/sites/', parameters('resourceName')))]": "empty"
-              },
-              "properties": {
-                "supportsHttpsTrafficOnly": true
-              },
-              "sku": {
-                "name": "Standard_LRS"
-              },
-              "kind": "Storage"
-            },
-            {
-              "location": "[parameters('resourceGroupLocation')]",
-              "name": "[variables('appServicePlan_name')]",
-              "type": "Microsoft.Web/serverFarms",
-              "apiVersion": "2015-08-01",
-              "sku": {
-                "name": "S1",
-                "tier": "Standard",
-                "family": "S",
-                "size": "S1"
-              },
-              "properties": {
-                "name": "[variables('appServicePlan_name')]"
-              }
-            }
-          ]
-        }
-      }
-    }
-  ]
-}

+ 0 - 8
TEAMModelFunction/Properties/launchSettings.json

@@ -1,8 +0,0 @@
-{
-  "profiles": {
-    "TEAMModelFunction": {
-      "commandName": "Project",
-      "nativeDebugging": false
-    }
-  }
-}

+ 0 - 3
TEAMModelFunction/Properties/serviceDependencies.json

@@ -1,3 +0,0 @@
-{
-  "dependencies": {}
-}

+ 0 - 3
TEAMModelFunction/Properties/serviceDependencies.local.json

@@ -1,3 +0,0 @@
-{
-  "dependencies": {}
-}

+ 0 - 611
TEAMModelFunction/ScsApisHttpTrigger.cs

@@ -1,611 +0,0 @@
-using System;
-using System.IO;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Mvc;
-using Microsoft.Azure.WebJobs;
-using Microsoft.Azure.WebJobs.Extensions.Http;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.Logging;
-using TEAMModelOS.SDK.DI;
-using Azure.Cosmos;
-using System.Text.Json;
-using System.Collections.Generic;
-using TEAMModelOS.SDK.Models;
-using TEAMModelOS.SDK.Extension;
-using TEAMModelOS.SDK;
-using TEAMModelOS.SDK.Models.Cosmos;
-using TEAMModelOS.SDK.Models.Cosmos.Common;
-using System.Linq;
-using TEAMModelOS.Services.Common;
-using TEAMModelOS.SDK.Models.Service;
-using HTEXLib.COMM.Helpers;
-using System.Text;
-using static TEAMModelOS.SDK.Models.Teacher;
-using TEAMModelOS.SDK.Models.Cosmos.Common.Inner;
-using Azure.Storage.Blobs.Models;
-
-namespace TEAMModelFunction
-{
-    public class ScsApisHttpTrigger
-    {
-        private readonly AzureCosmosFactory _azureCosmos;
-        private readonly DingDing _dingDing;
-        private readonly AzureStorageFactory _azureStorage;
-        private readonly AzureRedisFactory _azureRedis;
-        private readonly ThirdApisService _thirdApisService;
-        public static string Code { get; set; }
-        public static Dictionary<string, object> parameterMap = null;
-        public ScsApisHttpTrigger(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, ThirdApisService thirdApisService
-             , AzureRedisFactory azureRedis)
-        {
-            _azureCosmos = azureCosmos;
-            _dingDing = dingDing;
-            _azureStorage = azureStorage;
-            _azureRedis = azureRedis;
-            _thirdApisService = thirdApisService;
-        }
-
-        /// <summary>
-        /// 数据推送接口
-        /// </summary>
-        /// <param name="req"></param>
-        /// <param name="log"></param>
-        /// <returns></returns>
-        [FunctionName("knowledge-change")]
-        public async Task<IActionResult> KnowledgeChange([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) {
-            string data = await new StreamReader(req.Body).ReadToEndAsync();
-            var  json = JsonDocument.Parse(data).RootElement;
-            List<OldNew> old_new = null;
-            string school = null;
-            if (json.TryGetProperty("school", out JsonElement _school))
-            {
-                school = _school.GetString();
-            }
-            if (json.TryGetProperty("old_new", out JsonElement _old_new))
-            {
-                old_new = _old_new.ToObject<List<OldNew>>();
-            }
-            if (old_new.IsNotEmpty() && !string.IsNullOrWhiteSpace(school))
-            {
-                foreach (var on in old_new)
-                {
-                    List<ItemInfo> items = new List<ItemInfo>();
-                    string sql = $"select value(c) from c    where array_contains(c.knowledge,'{on._old}') ";
-                    await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ItemInfo>
-                        (queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{_school}") }))
-                    {
-                        items.Add(item);
-                    }
-
-                    items.ForEach(item => {
-                        //修改知识点
-                        if (!string.IsNullOrEmpty(on._new))
-                        {
-                            for (int i = 0; i < item.knowledge.Count; i++)
-                            {
-                                if (item.knowledge[i].Equals(on._old))
-                                {
-                                    item.knowledge[i] = on._new;
-                                }
-                            }
-                        }
-                        else
-                        {
-                            //表示删除知识点
-                            item.knowledge.RemoveAll(x => x.Equals(on._old));
-                        }
-                    });
-                    foreach (var item in items)
-                    {
-                        ItemBlob itemBlob = null;
-                        try
-                        {
-                            BlobDownloadInfo blobDownloadResult = await _azureStorage.GetBlobContainerClient($"hbcn").GetBlobClient($"/item/{item.id}/{item.id}.json").DownloadAsync();
-                            if (blobDownloadResult != null)
-                            {
-                                var blob = JsonDocument.Parse(blobDownloadResult.Content);
-                                itemBlob = blob.RootElement.ToObject<ItemBlob>();
-                                itemBlob.exercise.knowledge = item.knowledge;
-                                await _azureStorage.UploadFileByContainer("hbcn", itemBlob.ToJsonString(), "item", $"{item.id}/{item.id}.json", true);
-                            }
-                        }
-                        catch (Exception ex)
-                        {
-                            itemBlob = null;
-                        }
-                        await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
-                    }
-                }
-            }
-            return new OkResult();
-        }
-        /// <summary>
-        /// 数据推送接口
-        /// </summary>
-        /// <param name="req"></param>
-        /// <param name="log"></param>
-        /// <returns></returns>
-        [FunctionName("SchoolDataPush")]
-        public async Task<IActionResult> SchoolDataPush([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) {
-            var client = _azureCosmos.GetCosmosClient();
-            string data = await new StreamReader(req.Body).ReadToEndAsync();
-            JsonElement accessConfig = data.ToObject<JsonElement>().GetProperty("accessConfig");
-            ScAccessConfig config = $"{accessConfig}".ToObject<ScAccessConfig>();
-            JsonElement school = data.ToObject<JsonElement>().GetProperty("school");
-            StringBuilder queryText = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='yxtrain'");
-            List<GroupList> yxtrain = new List<GroupList>();
-            await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupList>(queryText: queryText.ToString(),
-            requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school}") }))
-            {
-                yxtrain.Add(item);
-            }
-            List<TeacherTrain> trains = new List<TeacherTrain>();
-            var members = yxtrain.SelectMany(x => x.members).ToList();
-            if (members.IsNotEmpty()) {
-                queryText = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='yxtrain' " +
-                    $"and  c.id in ({string.Join(",", members.Select(x => $"'{x.id}'"))}) ");
-                await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<TeacherTrain>(queryText: queryText.ToString(),
-                requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"TeacherTrain-{school}") }))
-                {
-                    trains.Add(item);
-                }
-            }
-
-            string sql = $" SELECT value(c) FROM c join a in c.binds where ARRAY_LENGTH(c.binds)>0 and a.type='{config.config}' ";
-            List<Teacher> teachers = new List<Teacher>();
-            await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Teacher>(queryText: sql,
-                requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
-            {
-                teachers.Add(item);
-            }
-            //5.3.1.12学员培训基本情况批量回写-UpdateTeacherListSituation
-            List<TeacherTrain> trains53112OK = new List<TeacherTrain>();
-
-            //5.3.1.13学员能力点测评结果批量回写-UpdateTeacherListDiagnosis
-            List<TeacherTrain> trains53113OK = new List<TeacherTrain>();
-
-            //5.3.1.17学员课堂实录批量回写-UploadKTSLList
-            List<TeacherTrain> trains53117OK = new List<TeacherTrain>();
-
-            //5.3.1.22学员校本教研PDF(每人可以返回多条)批量回写-UploadSBTARPDFListV2
-            List<TeacherTrain> trains53122OK = new List<TeacherTrain>();
-
-            List<KeyValuePair<TeacherTrain,string>> trainsNO = new List<KeyValuePair<TeacherTrain, string>>();
-            List<PushFail> fails= new List<PushFail>();
-            trains.ForEach(x => {
-                var teacher = teachers.Find(t => t.id.Equals(x.id));
-                if (teacher == null)
-                {
-                    fails.Add(new PushFail { tmdid = x.id, msgs = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("tmdid-unexistent", "账号不存在!") } });
-                }
-                else {
-                    List<KeyValuePair<string, string>> msgs = new List<KeyValuePair<string, string>>();
-                    var binddata = teachers.Where(t => t.id.Equals(x.id)).SelectMany(z => z.binds)
-                        .Where(d => d.data.IsNotEmpty()).SelectMany(d => d.data)
-                        .Where(d => string.IsNullOrEmpty(d) && d.Contains(config.config) && d.Contains(config.path));
-                    if (binddata != null && binddata.Count() > 0)
-                    {
-                        var bindData = binddata.First().ToObject<ScBindData>();
-                        if (binddata != null)
-                        {
-                        }
-                        else
-                        {
-                            //如果没有找到绑定信息,则去blob查找。
-                        }
-                    }
-                    else
-                    {
-                        //如果没有找到绑定信息,则去blob查找。
-                    }
-                }
-            });
-            return new OkObjectResult(new { });
-        }
-
-        /// <summary>
-        /// 5.3.1.1获取项目列表
-        /// </summary>
-        /// <param name="req"></param>
-        /// <param name="log"></param>
-        /// <returns></returns>
-        [FunctionName("GetProjectInfoByTrainComID")]
-        public async Task<IActionResult> GetProjectInfoByTrainComID([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log)
-        {
-            List<ScProject> projects = new List<ScProject>() ;
-            string data = await new StreamReader(req.Body).ReadToEndAsync();
-            JsonElement accessConfig = data.ToObject<JsonElement>().GetProperty("accessConfig");
-            ScAccessConfig config = $"{accessConfig}".ToObject<ScAccessConfig>();
-            Code = "GetProjectInfoByTrainComID";
-            parameterMap = new Dictionary<string, object>();
-            parameterMap.Add("TrainComID", config.trainComID);
-            ScsResult result = new ScsResult { code = Code, title = "5.3.1.1获取项目列表" };
-            try
-            {
-                result = await _thirdApisService.Post(config.url, Code, config.passKey, config.privateKey, parameterMap);
-                if (result.result)
-                {
-                    projects = result.content.ToObject<List<ScProject>>();
-                }
-                else { 
-                
-                }
-                return new OkObjectResult(new { data = projects.ToJsonString() });
-            }
-            catch (Exception ex)
-            {
-                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},IES5.ScApisService:GetProjectInfoByTrainComID\n{ex.Message}{ex.StackTrace}\n{result.ToJsonString()}\n{data}", GroupNames.成都开发測試群組);
-                return new OkObjectResult(new { data = projects.ToJsonString() });
-            }
-        }
-
-
-        /// <summary>
-        ///  5.3.1.18根据机构ID、项目ID、子项目ID返回学校列表
-        /// </summary>
-        /// <param name="req"></param>
-        /// <param name="log"></param>
-        /// <returns></returns>
-        [FunctionName("GetSchoolList")]
-        public async Task<IActionResult> GetSchoolList([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log)
-        {
-            List<ScSchool> scSchools = new List<ScSchool>();
-            string data = await new StreamReader(req.Body).ReadToEndAsync();
-            JsonElement accessConfig = data.ToObject<JsonElement>().GetProperty("accessConfig");
-            ScAccessConfig config = $"{accessConfig}".ToObject<ScAccessConfig>();
-            Code = "GetSchoolList";
-            parameterMap = new Dictionary<string, object>();
-            parameterMap.Add("TrainComID", config.trainComID);
-            List<ScsResult> results = new List<ScsResult>();
-            try
-            {
-                if (config.p.IsNotEmpty())
-                {
-                    foreach (var ps in config.p)
-                    {
-                        parameterMap["ProjectID"] = ps.pd;
-                        parameterMap["ProjectItemID"] = ps.pid;
-                        ScsResult result = new ScsResult { code = Code, title = " 5.3.1.18根据机构ID、项目ID、子项目ID返回学校列表" };
-                        result = await _thirdApisService.Post(config.url, Code, config.passKey, config.privateKey, parameterMap);
-                        if (result.result)
-                        {
-                            List<ScSchool> schools = result.content.ToObject<List<ScSchool>>();
-                            if (schools.IsNotEmpty())
-                            {
-                                scSchools.AddRange(schools);
-                            }
-                        }
-                        results.Add(result);
-                    }
-                }
-                return new OkObjectResult(new { data = scSchools.ToJsonString() });
-            }
-            catch (Exception ex)
-            {
-                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},IES5.ScApisService:GetSchoolList\n{ex.Message}{ex.StackTrace}\n{results.ToJsonString()}\n{data}", GroupNames.成都开发測試群組);
-                return new OkObjectResult(new { data = scSchools.ToJsonString() });
-            }
-        }
-        /// <summary>
-        /// 5.3.1.2获取学员名单
-        /// </summary>
-        /// <param name="req"></param>
-        /// <param name="log"></param>
-        /// <returns></returns>
-        [FunctionName("GetTeachersListByProject")]
-        public async Task<IActionResult> GetTeachersListByProject([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log)
-        {
-            List<ScTeacher> scTeachers = new List<ScTeacher>();
-            string data = await new StreamReader(req.Body).ReadToEndAsync();
-            JsonElement accessConfig = data.ToObject<JsonElement>().GetProperty("accessConfig");
-            ScAccessConfig config = $"{accessConfig}".ToObject<ScAccessConfig>();
-            Code = "GetTeachersListByProject";
-            parameterMap = new Dictionary<string, object>();
-            parameterMap.Add("TrainComID", config.trainComID);
-            List<ScsResult> results = new List<ScsResult>();
-            try
-            {
-                if (config.p.IsNotEmpty())
-                {
-                    foreach (var ps in config.p)
-                    {
-                        parameterMap["ProjectID"] = ps.pd;
-                        parameterMap["ProjectItemID"] = ps.pid;
-                        ScsResult result = new ScsResult { code = Code, title = "5.3.1.2获取学员名单" };
-                        result = await _thirdApisService.Post(config.url, Code, config.passKey, config.privateKey, parameterMap);
-                        if (result.result)
-                        {
-                            List<ScTeacher> teachers = result.content.ToObject<List<ScTeacher>>();
-                            if (teachers.IsNotEmpty())
-                            {
-                                scTeachers.AddRange(teachers);
-                            }
-                        }
-                        results.Add(result);
-                    }
-                }
-                return new OkObjectResult(new { data = scTeachers.ToJsonString() });
-            }
-            catch (Exception ex)
-            {
-                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},IES5.ScApisService:GetTeachersListByProject\n{ex.Message}{ex.StackTrace}\n{results.ToJsonString()}\n{data}", GroupNames.成都开发測試群組);
-                return new OkObjectResult(new { data = scTeachers.ToJsonString() });
-            }
-        }
-        /// <summary>
-        /// 5.3.1.20获取学校设置的可选能力点
-        /// </summary>
-        /// <param name="req"></param>
-        /// <param name="log"></param>
-        /// <returns></returns>
-        [FunctionName("GetSchoolDiagnosis")]
-        public async Task<IActionResult> GetSchoolDiagnosis([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) {
-            List<ScsProjectDiagnosis> projects = new List<ScsProjectDiagnosis>();
-            string data = await new StreamReader(req.Body).ReadToEndAsync();
-            JsonElement accessConfig = data.ToObject<JsonElement>().GetProperty("accessConfig");
-            JsonElement schoolCode = data.ToObject<JsonElement>().GetProperty("schoolCode");
-            ScAccessConfig config = $"{accessConfig}".ToObject<ScAccessConfig>();
-            Code = "GetSchoolDiagnosis";
-            parameterMap = new Dictionary<string, object>();
-            parameterMap.Add("TrainComID", config.trainComID);
-            List<ScsResult> results = new List<ScsResult>();
-            try
-            {
-                if (config.p.IsNotEmpty())
-                {
-                    foreach (var ps in config.p)
-                    {
-                        parameterMap["ProjectID"] = ps.pd;
-                        parameterMap["ProjectItemID"] = ps.pid;
-                        parameterMap["SchoolID"] = $"{schoolCode}";
-                        parameterMap["School"] = $"{schoolCode}";
-                        ScsResult result = new ScsResult { code = Code, title = " 5.3.1.20获取学校设置的可选能力点" };
-                        result = await _thirdApisService.Post(config.url, Code, config.passKey, config.privateKey, parameterMap);
-                        if (result.result)
-                        {
-                            List<ScPDiagnosis> diagnoses = result.content.ToObject<List<ScPDiagnosis>>();
-                            if (diagnoses.IsNotEmpty())
-                            {
-                                projects.Add(new ScsProjectDiagnosis { project = ps, diagnoses = diagnoses });
-                                await _azureStorage.SaveOrUpdate<ScProjectDiagnosis>(new ScProjectDiagnosis { RowKey = $"{ps.pid}-{schoolCode}", PartitionKey = "ScSchoolDiagnosis", abilityNos = diagnoses.ToJsonString() });
-                            }
-                        }
-                        else
-                        {
-                            List<ScProjectDiagnosis> teacherDiagnoses = await _azureStorage.FindListByDict<ScProjectDiagnosis>(new Dictionary<string, object> { { "PartitionKey", "ScSchoolDiagnosis" }, { "RowKey", $"{ps.pid}-{schoolCode}" } });
-                            if (teacherDiagnoses.IsNotEmpty())
-                            {
-                                projects.Add(new ScsProjectDiagnosis { project = ps, diagnoses = teacherDiagnoses[0].abilityNos.ToObject<List<ScPDiagnosis>>() });
-
-                            }
-                        }
-                        results.Add(result);
-                    }
-                }
-                return new OkObjectResult(new { data = projects.ToJsonString() });
-            }
-            catch (Exception ex)
-            {
-                //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},IES5.ScApisService:GetSchoolDiagnosis\n{ex.Message}{ex.StackTrace}\n{results.ToJsonString()}\n{data}", GroupNames.成都开发測試群組);
-
-                if (config.p.IsNotEmpty()) {
-                    foreach (var ps in config.p)
-                    {
-                        List<ScProjectDiagnosis> teacherDiagnoses = await _azureStorage.FindListByDict<ScProjectDiagnosis>(new Dictionary<string, object> { { "PartitionKey", "ScSchoolDiagnosis" }, { "RowKey", $"{ps.pid}-{schoolCode}" } });
-                        if (teacherDiagnoses.IsNotEmpty())
-                        {
-                            projects.Add(new ScsProjectDiagnosis { project = ps, diagnoses = teacherDiagnoses[0].abilityNos.ToObject<List<ScPDiagnosis>>() });
-
-                        }
-                    }
-                }
-                return new OkObjectResult(new { data = projects.ToJsonString() });
-            }
-        }
-        /// <summary>
-        /// 5.3.1.19获取项目设置的可选能力点
-        /// </summary>
-        /// <param name="req"></param>
-        /// <param name="log"></param>
-        /// <returns></returns>
-        [FunctionName("GetProjectDiagnosis")]
-        public async Task<IActionResult> GetProjectDiagnosis([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log)
-        {
-            List<ScsProjectDiagnosis> projects =  new List<ScsProjectDiagnosis> () ;
-            string data = await new StreamReader(req.Body).ReadToEndAsync();
-            JsonElement accessConfig = data.ToObject<JsonElement>().GetProperty("accessConfig");
-            ScAccessConfig config = $"{accessConfig}".ToObject<ScAccessConfig>();
-            Code = "GetProjectDiagnosis";
-            parameterMap = new Dictionary<string, object>();
-            parameterMap.Add("TrainComID", config.trainComID);
-            List<ScsResult> results = new List<ScsResult>();
-            try
-            {
-                if (config.p.IsNotEmpty())
-                {
-                    foreach (var ps in config.p)
-                    {
-                        parameterMap["ProjectID"] = ps.pd;
-                        parameterMap["ProjectItemID"] = ps.pid;
-                        ScsResult result = new ScsResult { code = Code, title = "5.3.1.19获取项目设置的可选能力点" };
-                        result = await _thirdApisService.Post(config.url, Code, config.passKey, config.privateKey, parameterMap);
-                        if (result.result)
-                        {
-                            List<ScPDiagnosis> diagnoses = result.content.ToObject<List<ScPDiagnosis>>();
-                            if (diagnoses.IsNotEmpty())
-                            {
-                                projects.Add(new ScsProjectDiagnosis { project = ps, diagnoses = diagnoses });
-                                await _azureStorage.SaveOrUpdate<ScProjectDiagnosis>(new ScProjectDiagnosis { RowKey = $"{ps.pid}", PartitionKey = "ScProjectDiagnosis", abilityNos = diagnoses.ToJsonString() });
-                            }
-                        }
-                        else
-                        {
-                            List<ScProjectDiagnosis> teacherDiagnoses = await _azureStorage.FindListByDict<ScProjectDiagnosis>(new Dictionary<string, object> { { "PartitionKey", "ScProjectDiagnosis" }, { "RowKey", $"{ps.pid}" } });
-                            if (teacherDiagnoses.IsNotEmpty())
-                            {
-                                projects.Add(new ScsProjectDiagnosis { project = ps, diagnoses = teacherDiagnoses[0].abilityNos.ToObject<List<ScPDiagnosis>>() });
-
-                            }
-                        }
-                        results.Add(result);
-                    }
-                }
-                return new OkObjectResult(new { data = projects.ToJsonString() });
-            }
-            catch (Exception ex)
-            {
-                if (config.p.IsNotEmpty()) {
-                    foreach (var ps in config.p)
-                    {
-                        //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},IES5.ScApisService:GetProjectDiagnosis\n{ex.Message}{ex.StackTrace}\n{results.ToJsonString()}\n{data}", GroupNames.成都开发測試群組);
-                        List<ScProjectDiagnosis> teacherDiagnoses = await _azureStorage.FindListByDict<ScProjectDiagnosis>(new Dictionary<string, object> { { "PartitionKey", "ScProjectDiagnosis" }, { "RowKey", $"{ps.pid}" } });
-                        if (teacherDiagnoses.IsNotEmpty())
-                        {
-                            projects.Add(new ScsProjectDiagnosis { project = ps, diagnoses = teacherDiagnoses[0].abilityNos.ToObject<List<ScPDiagnosis>>() });
-
-                        }
-                    }
-                }
-                return new OkObjectResult(new { data = projects.ToJsonString() });
-            }
-        }
-
-        /// <summary>
-        /// 5.3.1.3通过项目编号获取学员测评能力项V2
-        /// </summary>
-        /// <param name="req"></param>
-        /// <param name="log"></param>
-        /// <returns></returns>
-        [FunctionName("GetDiagnosisListByProject_V2")]
-        public async Task<IActionResult> GetDiagnosisListByProject_V2([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) {
-            List<string> abilityNos = new  List<string>();
-            string data = await new StreamReader(req.Body).ReadToEndAsync();
-            JsonElement accessConfig=  data.ToObject<JsonElement>().GetProperty("accessConfig");
-            JsonElement pxid = data.ToObject<JsonElement>().GetProperty("pxid");
-            ScAccessConfig config = $"{accessConfig}".ToObject<ScAccessConfig>();
-            Code = "GetDiagnosisListByProject_V2";
-            parameterMap = new Dictionary<string, object>();
-            parameterMap.Add("TrainComID", config.trainComID);
-            parameterMap.Add("PXID", pxid);
-            ScsResult result = new ScsResult { code = Code, title = "5.3.1.3通过项目编号获取学员测评能力项V2" };
-            try
-            {
-                result = await _thirdApisService.Post(config.url, Code, config.passKey, config.privateKey, parameterMap);
-                if (result.result)
-                {
-                    List<ScDiagnosis> diagnoses = result.content.ToObject<List<ScDiagnosis>>();
-                    if (diagnoses != null)
-                    {
-                        abilityNos = diagnoses.Select(x => x.DiagnosisDicNum).ToList();
-                    }
-                    if (abilityNos .IsNotEmpty()) {
-                        await _azureStorage.SaveOrUpdate<ScTeacherDiagnosis>(new ScTeacherDiagnosis { RowKey = $"{pxid}", PartitionKey = "ScTeacherDiagnosis",abilityNos=abilityNos.ToJsonString() });
-                    }
-                }
-                else {
-
-                    List<ScTeacherDiagnosis> teacherDiagnoses = await _azureStorage.FindListByDict<ScTeacherDiagnosis>(new Dictionary<string, object> { { "PartitionKey", "ScTeacherDiagnosis" },  { "RowKey", $"{pxid}" } });
-                    if (teacherDiagnoses.IsNotEmpty()) {
-                        abilityNos = teacherDiagnoses[0].abilityNos.ToObject<List<string>>();
-                    }
-                }
-                return new  OkObjectResult(new { data= abilityNos .ToJsonString()});
-            }
-            catch (Exception ex)
-            {
-                //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},IES5.ScApisService:getDiagnosisListByProject_V2\n{ex.Message}{ex.StackTrace}\n{result.ToJsonString()}\n{data}", GroupNames.成都开发測試群組);
-
-                List<ScTeacherDiagnosis> teacherDiagnoses = await _azureStorage.FindListByDict<ScTeacherDiagnosis>(new Dictionary<string, object> { { "PartitionKey", "ScTeacherDiagnosis" }, { "RowKey", $"{pxid}" } });
-                if (teacherDiagnoses.IsNotEmpty())
-                {
-                    abilityNos = teacherDiagnoses[0].abilityNos.ToObject<List<string>>();
-                }
-                return new OkObjectResult(new { data = abilityNos.ToJsonString() });
-            }
-        }
-        /// <summary>
-        /// 5.3.1.11获取跳转学员信息,用于sso单点,后端验证。
-        /// </summary>
-        /// <param name="req"></param>
-        /// <param name="log"></param>
-        /// <returns></returns>
-        [FunctionName("GetSingleTeacherByProject")]
-        public async Task<IActionResult> GetSingleTeacherByProject([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log)
-        {
-            string teacher=null;
-            string data = await new StreamReader(req.Body).ReadToEndAsync();
-            JsonElement accessConfig = data.ToObject<JsonElement>().GetProperty("accessConfig");
-            JsonElement pxid = data.ToObject<JsonElement>().GetProperty("pxid");
-            JsonElement tid = data.ToObject<JsonElement>().GetProperty("tid");
-            ScAccessConfig config = $"{accessConfig}".ToObject<ScAccessConfig>();
-            Code = "GetSingleTeacherByProject";
-            parameterMap = new Dictionary<string, object>();
-            parameterMap.Add("TrainComID", config.trainComID);
-            parameterMap.Add("Pxid", $"{pxid}");
-            parameterMap.Add("Tid", $"{tid}");
-            ScsResult result = new ScsResult { code = Code, title = "5.3.1.11获取跳转学员信息,用于sso单点,后端验证。" };
-            try
-            {
-                ///{“result”:true,”reason”:null,”content”:”{“PXID”:””,”TID”:””,”TeacherName”:””,”ProjectTitle”:””,”ProjectItemTitle”:””,”CityName”:””,
-                ///”DisName”:””,”SchoolName”:””,”Sex”:””,”PXXK”:””,”PXXD”:””,”TeacherXK”:””,”TeacherXD”:””,”Email”:””}”,”pagecount”:1}
-                result = await _thirdApisService.Post(config.url, Code, config.passKey, config.privateKey, parameterMap);
-                if (result.result)
-                {
-                      teacher = result.content;
-                }
-                return new OkObjectResult(new {data= teacher });
-            }
-            catch (Exception ex)
-            {
-                //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},IES5.ScApisService:GetSingleTeacherByProject\n{ex.Message}{ex.StackTrace}\n{result.ToJsonString()}\n{data}", GroupNames.成都开发測試群組);
-                return new OkObjectResult(new { data = teacher });
-            }
-        }
-
-        public (int t53112OK, List<KeyValuePair<string, string>> msgs) check53112(TeacherTrain teacherTrain, List<KeyValuePair<string, string>> msgs)
-        {
-            //校验 基本情况是否满足
-            int t53112OK = 1;
-            if (teacherTrain.finalScore < 0)
-            {
-                msgs.Add(new KeyValuePair<string, string>("finalScore", $"最终评定结果参数:{teacherTrain.finalScore}"));
-                t53112OK = 0;
-            }
-            if (string.IsNullOrEmpty(teacherTrain.summary) || teacherTrain.summary.Length > 300)
-            {
-                string msg = string.IsNullOrEmpty(teacherTrain.summary) ? "未填写" : teacherTrain.summary.Length > 300 ? "字数超过300." : "";
-                msgs.Add(new KeyValuePair<string, string>("summary", $"教师培训总结:{msg}"));
-                t53112OK = 0;
-            }
-            if (teacherTrain.totalTime <= 0)
-            {
-                msgs.Add(new KeyValuePair<string, string>("totalTime", $"未获得学时:{teacherTrain.totalTime}"));
-                t53112OK = 0;
-            }
-            return (t53112OK, msgs);
-        }
-
-        public (int t53112OK, List<KeyValuePair<string, string>> msgs) check53113(TeacherTrain teacherTrain, List<KeyValuePair<string, string>> msgs)
-        {
-            //校验 基本情况是否满足
-            int t53112OK = 1;
-            if (teacherTrain.finalScore < 0)
-            {
-                msgs.Add(new KeyValuePair<string, string>("finalScore", $"最终评定结果参数:{teacherTrain.finalScore}"));
-                t53112OK = 0;
-            }
-            if (string.IsNullOrEmpty(teacherTrain.summary) || teacherTrain.summary.Length > 300)
-            {
-                string msg = string.IsNullOrEmpty(teacherTrain.summary) ? "未填写" : teacherTrain.summary.Length > 300 ? "字数超过300." : "";
-                msgs.Add(new KeyValuePair<string, string>("summary", $"教师培训总结:{msg}"));
-                t53112OK = 0;
-            }
-            if (teacherTrain.totalTime <= 0)
-            {
-                msgs.Add(new KeyValuePair<string, string>("totalTime", $"未获得学时:{teacherTrain.totalTime}"));
-                t53112OK = 0;
-            }
-            return (t53112OK, msgs);
-        }
-    }
-}

+ 0 - 34
TEAMModelFunction/Startup.cs

@@ -1,34 +0,0 @@
-using Microsoft.Azure.Functions.Extensions.DependencyInjection;
-using Microsoft.Extensions.Configuration;
-using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.Hosting;
-using System;
-using System.Collections.Generic;
-using System.Configuration;
-using System.IO;
-using System.Reflection;
-using System.Text;
-using TEAMModelOS.SDK;
-using TEAMModelOS.SDK.DI;
-using TEAMModelOS.SDK.Models.Service;
-
-[assembly: FunctionsStartup(typeof(TEAMModelFunction.Startup))]
-namespace TEAMModelFunction
-{
-    public class Startup : FunctionsStartup
-    {
-        public override void Configure(IFunctionsHostBuilder builder)
-        {
-            builder.Services.AddHttpClient();
-            builder.Services.AddHttpClient<DingDing>();
-            builder.Services.AddHttpClient<ThirdApisService>();
-            builder.Services.AddHttpClient<NotificationService>();
-            builder.Services.AddAzureServiceBus(Environment.GetEnvironmentVariable("Azure:ServiceBus:ConnectionString"));
-            builder.Services.AddAzureStorage(Environment.GetEnvironmentVariable("Azure:Storage:ConnectionString"));
-            builder.Services.AddAzureCosmos(Environment.GetEnvironmentVariable("Azure:Cosmos:ConnectionString"));
-            builder.Services.AddAzureRedis(Environment.GetEnvironmentVariable("Azure:Redis:ConnectionString"));
-        }
-
-
-    }
-}

+ 0 - 43
TEAMModelFunction/TEAMModelFunction.csproj

@@ -1,43 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-	<PropertyGroup>
-		<TargetFramework>net6.0</TargetFramework>
-		<AzureFunctionsVersion>v4</AzureFunctionsVersion>
-		<!--<_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput>-->
-		<Version>5.2112.21</Version>
-		<AssemblyVersion>5.2107.29.2</AssemblyVersion>
-		<FileVersion>5.2107.29.2</FileVersion>
-		<!--<OutputType>Exe</OutputType>
-		<_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput>
-		<SignAssembly>true</SignAssembly>-->
-	</PropertyGroup>
-	<!--<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
-		<DefineConstants>DEBUG;TRACE</DefineConstants>
-	</PropertyGroup>-->
-	<ItemGroup>
-		<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.0.1" />
-		<PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" />
-		<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.CosmosDB" Version="3.0.10" />
-		<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.ServiceBus" Version="5.2.0" />
-		<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Http" Version="3.0.12" />
-		<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage" Version="5.0.0" />
-		<!--<PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.6.0" />
-		<PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.3.0" />
-		<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.0.13" />
-		<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Storage" Version="5.0.0" />
-		<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.ServiceBus" Version="5.0.0-beta.6" />
-		<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.CosmosDB" Version="4.0.0-preview2" />
-		<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Storage.Blobs" Version="5.0.0" />-->
-	</ItemGroup>
-	<ItemGroup>
-		<ProjectReference Include="..\TEAMModelOS.SDK\TEAMModelOS.SDK.csproj" />
-	</ItemGroup>
-	<ItemGroup>
-		<None Update="host.json">
-			<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
-		</None>
-		<None Update="local.settings.json">
-			<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
-			<CopyToPublishDirectory>Never</CopyToPublishDirectory>
-		</None>
-	</ItemGroup>
-</Project>

+ 0 - 427
TEAMModelFunction/TriggerCorrect.cs

@@ -1,427 +0,0 @@
-using Azure.Cosmos;
-using Azure.Messaging.ServiceBus;
-using Microsoft.Azure.Documents;
-using System;
-using System.Collections.Generic;
-using System.Text.Json;
-using System.Threading.Tasks;
-using TEAMModelOS.SDK.DI;
-using TEAMModelOS.SDK.Extension;
-using TEAMModelOS.SDK;
-using TEAMModelOS.SDK.Models;
-using TEAMModelOS.SDK.Models.Cosmos;
-using TEAMModelOS.SDK.Models.Cosmos.Common;
-using TEAMModelOS.SDK.Models.Table;
-using HTEXLib.COMM.Helpers;
-using Azure;
-
-namespace TEAMModelFunction
-{
-    public static class TriggerCorrect
-    {
-        public static async Task Trigger(AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
-           CosmosClient client, Document input, TriggerData tdata, AzureRedisFactory _azureRedis)
-        {
-            if ((tdata.status != null && tdata.status.Value == 404) || tdata.ttl > 0)
-            {
-                return;
-            }
-            var adid = tdata.id;
-            var adcode = "";
-            string blobcntr = null;
-            if (tdata.scope.Equals("school"))
-            {
-                adcode = $"Activity-{tdata.school}";
-                blobcntr = tdata.school;
-            }
-            else
-            {
-                return;
-            }
-            await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}阅卷配置【{tdata.name}-{tdata.id}-ttl={tdata.ttl}】正在执行", GroupNames.成都开发測試群組);
-            try {
-                Correct correct = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Correct>(input.Id, new Azure.Cosmos.PartitionKey($"{tdata.code}"));
-
-                if (correct != null)
-                {
-                    string PartitionKey = string.Format("{0}{1}{2}", correct.code, "-", correct.progress);
-                    List<ChangeRecord> correctRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", PartitionKey } });
-                    switch (correct.progress)
-                    {
-                        case "pending":
-                            var messageCorrect = new ServiceBusMessage(new { id = input.Id, progress = "going", code = tdata.code }.ToJsonString());
-                            messageCorrect.ApplicationProperties.Add("name", "Correct");
-                            if (correctRecords.Count > 0)
-                            {
-                                long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageCorrect, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
-                                await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), correctRecords[0].sequenceNumber);
-                                correctRecords[0].sequenceNumber = start;
-                                await _azureStorage.SaveOrUpdate<ChangeRecord>(correctRecords[0]);
-                            }
-                            else
-                            {
-                                long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageCorrect, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
-                                ChangeRecord changeRecord = new ChangeRecord
-                                {
-                                    RowKey = input.Id,
-                                    PartitionKey = PartitionKey,
-                                    sequenceNumber = start,
-                                    msgId = messageCorrect.MessageId
-                                };
-                                await _azureStorage.Save<ChangeRecord>(changeRecord);
-                            }
-                            break;
-                        case "going":
-                            //评测id
-                            string eid = correct.id;
-                            //评测的分区键
-                            string ecode = correct.scode;
-                            ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(input.Id, new Azure.Cosmos.PartitionKey($"{ecode}"));
-                            if (correct.subs.IsNotEmpty())
-                            {
-
-                                foreach (var sub in correct.subs)
-                                {
-                                    ///生成阅卷教师的阅卷任务列表
-                                    if (sub.markers.IsNotEmpty())
-                                    {
-                                        foreach (var marker in sub.markers)
-                                        {
-                                            CorrectTask task = new CorrectTask
-                                            {
-                                                ttl = -1,
-                                                pk = "CorrectTask",
-                                                code = "CorrectTask-" + marker.id,
-
-                                                id = Guid.NewGuid().ToString(),
-                                                //评测id 或者阅卷配置id
-                                                cid = correct.id,
-                                                //科目
-                                                subject = sub.id,
-                                                //科目名称
-                                                subjectName = sub.name,
-                                                //评测code
-                                                ecode = correct.scode,
-                                                //阅卷配置code
-                                                scode = correct.code,
-                                                //任务名称
-                                                name = correct.name,
-                                                progress = "going",
-                                                //开始时间
-                                                startTime = correct.startTime,
-                                                //结束时间
-                                                endTime = correct.endTime,
-                                                //批改数量
-                                                count = marker.count,
-                                                //按题阅卷时,题号
-                                                qu = marker.qu,
-                                                //模块数
-                                                model = sub.model,
-                                                type = 1,
-                                                createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
-                                                source = info.source
-                                            };
-                                            await client.GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync<CorrectTask>(task, new Azure.Cosmos.PartitionKey(task.code));
-                                        }
-                                    }
-
-
-                                    //生成异常卷处理人员
-                                    if (sub.err.IsNotEmpty())
-                                    {
-
-                                        foreach (var tId in sub.err)
-                                        {
-                                            CorrectTask task = new CorrectTask
-                                            {
-                                                ttl = -1,
-                                                pk = "CorrectTask",
-                                                code = "CorrectTask-" + tId,
-
-                                                id = Guid.NewGuid().ToString(),
-                                                //评测id 或者阅卷配置id
-                                                cid = correct.id,
-                                                //科目
-                                                subject = sub.id,
-                                                //科目名称
-                                                subjectName = sub.name,
-                                                //评测code
-                                                ecode = correct.scode,
-                                                //阅卷配置code
-                                                scode = correct.code,
-                                                progress = "going",
-                                                //任务名称
-                                                name = correct.name,
-                                                //开始时间
-                                                startTime = correct.startTime,
-                                                //结束时间
-                                                endTime = correct.endTime,
-                                                //模块数
-                                                model = sub.model,
-                                                type = 2,
-                                                createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
-                                            };
-                                            await client.GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync<CorrectTask>(task, new Azure.Cosmos.PartitionKey(task.code));
-                                        }
-
-
-                                    }
-
-                                    //生成仲裁人员
-
-                                    if (sub.arb.IsNotEmpty())
-                                    {
-
-                                        foreach (var tId in sub.arb)
-                                        {
-                                            CorrectTask task = new CorrectTask
-                                            {
-                                                ttl = -1,
-                                                pk = "CorrectTask",
-                                                code = "CorrectTask-" + tId,
-
-                                                id = Guid.NewGuid().ToString(),
-                                                //评测id 或者阅卷配置id
-                                                cid = correct.id,
-                                                //科目
-                                                subject = sub.id,
-                                                //科目名称
-                                                subjectName = sub.name,
-                                                progress = "going",
-                                                //评测code
-                                                ecode = correct.scode,
-                                                //阅卷配置code
-                                                scode = correct.code,
-                                                //任务名称
-                                                name = correct.name,
-                                                //开始时间
-                                                startTime = correct.startTime,
-                                                //结束时间
-                                                endTime = correct.endTime,
-                                                //模块数
-                                                model = sub.model,
-                                                type = 3,
-                                                createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
-                                            };
-                                            await client.GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync<CorrectTask>(task, new Azure.Cosmos.PartitionKey(task.code));
-                                        }
-
-
-                                    }
-                                    //评测科目
-                                    string subjectId = sub.id;
-                                    //生成临时作答数据存放到redis
-                                    //var redisClient = _azureRedis.GetRedisClient(8);
-                                    //ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(eid, new Azure.Cosmos.PartitionKey(ecode));
-                                    List<ExamClassResult> classResults = new List<ExamClassResult>();
-                                    //获取原题配分
-                                    int paperIndex = 0;
-                                    foreach (ExamSubject subject in info.subjects)
-                                    {
-                                        if (subject.id.Equals(subjectId))
-                                        {
-                                            break;
-                                        }
-                                        else
-                                        {
-                                            paperIndex++;
-                                        }
-                                    }
-                                    List<double> paperPoint = info.papers[paperIndex].point;
-                                    List<List<string>> ans = info.papers[paperIndex].answers;
-                                    if (info.scope.Equals("school"))
-                                    {
-
-                                        await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
-                                        queryText: $"select value(c) from c where c.examId = '{eid}' and c.subjectId = '{subjectId}'",
-                                        requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamClassResult-{info.school}") }))
-                                        {
-                                            classResults.Add(item);
-                                        }
-                                    }
-                                    else
-                                    {
-                                        await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
-                                            queryText: $"select value(c) from c where c.examId = '{eid}' and c.subjectId = '{subjectId}'",
-                                            requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamClassResult-{info.creatorId}") }))
-                                        {
-                                            classResults.Add(item);
-                                        }
-                                    }
-                                    List<Task<ItemResponse<Scoring>>> tasks = new List<Task<ItemResponse<Scoring>>>();
-                                    //初始化老师阅卷记录
-                                    //List<string> tmds = new List<string>();
-                                    /*                                List<string> marks = new List<string>();
-                                                                    for (int i = 0; i < correct.num; i++)
-                                                                    {
-                                                                        marks.Add("");
-                                                                    }*/
-                                    foreach (ExamClassResult examClass in classResults)
-                                    {
-                                        foreach (string stuId in examClass.studentIds)
-                                        {
-                                            int index = examClass.studentIds.IndexOf(stuId);
-                                            if (index > -1)
-                                            {
-                                                List<double> scc = examClass.studentScores[index];
-                                                List<Item> items = new List<Item>();
-                                                List<Qs> qss = new List<Qs>();
-                                                int itemIndex = 0;
-                                                foreach (double psc in scc)
-                                                {
-                                                    //初始化异常卷信息,初始化仲裁卷信息
-                                                    Qs qs = new Qs();
-                                                    List<Info> infos = new List<Info>();
-                                                    Item item = new Item
-                                                    {
-                                                        ssc = paperPoint[itemIndex],
-                                                        scores = infos
-                                                    };
-                                                    itemIndex++;
-                                                    items.Add(item);
-                                                    qss.Add(qs);
-                                                }
-                                                //处理学生未作答 生成阅卷数据时 客观题分数为-1的情况
-                                                List<double> scores = new List<double>();
-                                                int n = 0;
-                                                foreach (List<string> answer in ans)
-                                                {
-                                                    var scs = examClass.studentScores[index][n];
-
-                                                    if (answer.Count > 0)
-                                                    {
-                                                        if (scs == -1)
-                                                        {
-                                                            scores.Add(0);
-                                                        }
-                                                        else
-                                                        {
-                                                            scores.Add(scs);
-                                                        }
-                                                    }
-                                                    else
-                                                    {
-                                                        scores.Add(scs);
-                                                    }
-                                                    n++;
-                                                }
-                                                Scoring sc = new Scoring
-                                                {
-                                                    id = Guid.NewGuid().ToString(),
-                                                    code = "Scoring-" + info.school,
-                                                    blob = examClass.studentAnswers[index].Count > 0 ? examClass.studentAnswers[index][0] : "",
-                                                    stuId = stuId,
-                                                    examId = eid,
-                                                    subjectId = subjectId,
-                                                    scores = scores,
-                                                    count = correct.num,
-                                                    //marks = marks,
-                                                    items = items,
-                                                    qs = qss,
-                                                    //endTime = correct.endTime,
-                                                    model = sub.model
-
-                                                };
-                                                tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Scoring>(sc, new Azure.Cosmos.PartitionKey(sc.code)));
-                                            }
-                                            //tasks.Add(redisClient.HashSetAsync($"Exam:Scoring:{eid}-{subjectId}", stuId, new { tmdId = tmds, ans = examClass.studentAnswers[index].Count > 0 ? examClass.studentAnswers[index][0] : "", score = examClass.studentScores[index] }.ToJsonString()));
-                                        }
-
-                                    }
-                                    await Task.WhenAll(tasks);
-                                }
-                            }
-                            var messageCorrectEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = tdata.code }.ToJsonString());
-                            messageCorrectEnd.ApplicationProperties.Add("name", "Correct");
-                            if (correctRecords.Count > 0)
-                            {
-                                long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageCorrectEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
-                                await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), correctRecords[0].sequenceNumber);
-                                correctRecords[0].sequenceNumber = end;
-                                await _azureStorage.SaveOrUpdate<ChangeRecord>(correctRecords[0]);
-                            }
-                            else
-                            {
-                                long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageCorrectEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
-                                ChangeRecord changeRecord = new ChangeRecord
-                                {
-                                    RowKey = input.Id,
-                                    PartitionKey = PartitionKey,
-                                    sequenceNumber = end,
-                                    msgId = messageCorrectEnd.MessageId
-                                };
-                                await _azureStorage.Save<ChangeRecord>(changeRecord);
-                            }
-                            break;
-                        case "finish":
-                            foreach (var sub in correct.subs)
-                            {
-                                List<string> ids = new List<string>();
-                                ///阅卷教师的阅卷任务列表
-                                if (sub.markers.IsNotEmpty())
-                                {
-                                    foreach (var marker in sub.markers)
-                                    {
-                                        ids.Add(marker.id);
-                                        //await client.GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync<CorrectTask>(task, new Azure.Cosmos.PartitionKey(task.code),new ItemRequestOptions().PostTriggers);
-                                    }
-                                }
-                                //异常卷处理人员
-                                if (sub.err.IsNotEmpty())
-                                {
-
-                                    foreach (var tId in sub.err)
-                                    {
-                                        if (!ids.Contains(tId))
-                                        {
-                                            ids.Add(tId);
-                                        }
-                                    }
-                                }
-
-                                //仲裁人员
-
-                                if (sub.arb.IsNotEmpty())
-                                {
-                                    foreach (var tId in sub.arb)
-                                    {
-                                        if (!ids.Contains(tId))
-                                        {
-                                            ids.Add(tId);
-                                        }
-                                    }
-                                }
-                                List<CorrectTask> corrects = new List<CorrectTask>();
-                                foreach (string id in ids)
-                                {
-                                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<CorrectTask>(
-                                          queryText: $"select value(c) from c where c.cid = '{correct.id}'",
-                                          requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"CorrectTask-{id}") }))
-                                    {
-                                        corrects.Add(item);
-                                    }
-                                }
-                                List<Task<ItemResponse<CorrectTask>>> tasks = new List<Task<ItemResponse<CorrectTask>>>();
-                                foreach (CorrectTask task in corrects)
-                                {
-                                    task.progress = "finish";
-                                    tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(task, task.id, new Azure.Cosmos.PartitionKey(task.code)));
-                                }
-                                await Task.WhenAll(tasks);
-                            }
-                            break;
-                    }
-                }
-            }
-            catch (CosmosException e)
-            {
-                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDB异常{e.Message}\n{e.Status}", GroupNames.成都开发測試群組);
-            }
-            catch (Exception e)
-            {
-                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-阅卷异常{e.Message}\n{e.StackTrace}", GroupNames.成都开发測試群組);
-            }
-            
-        }
-    }
-}

+ 0 - 997
TEAMModelFunction/TriggerExam.cs

@@ -1,997 +0,0 @@
-using Azure.Cosmos;
-using Azure.Messaging.ServiceBus;
-using Microsoft.Azure.Documents;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Text.Json;
-using System.Threading.Tasks;
-using TEAMModelOS.SDK.DI;
-using TEAMModelOS.SDK.Extension;
-using TEAMModelOS.SDK;
-using TEAMModelOS.SDK.Models;
-using TEAMModelOS.SDK.Models.Cosmos;
-using TEAMModelOS.SDK.Models.Cosmos.Common;
-using TEAMModelOS.SDK.Models.Service;
-using HTEXLib.COMM.Helpers;
-
-namespace TEAMModelFunction
-{
-    public class TriggerExam
-    {
-        public static async Task Trigger(AzureCosmosFactory _azureCosmos, AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
-            CosmosClient client, Document input, string code, long stime, long etime, string school)
-        {
-
-            List<ExamClassResult> examClassResults = new List<ExamClassResult>();
-            List<ExamSubject> examSubjects = new List<ExamSubject>();
-            try
-            {
-                ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(input.Id, new Azure.Cosmos.PartitionKey($"{code}"));
-                if (info != null)
-                {
-                    if (info.scope.Equals("teacher", StringComparison.OrdinalIgnoreCase) || info.scope.Equals("private", StringComparison.OrdinalIgnoreCase))
-                    {
-                        await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: $"select value(c) from c where c.examId = '{info.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamClassResult-{info.creatorId}") }))
-                        {
-                            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())
-                                {
-                                    examClassResults.Add(obj.ToObject<ExamClassResult>());
-                                }
-                            }
-                        }
-                    }
-                    else
-                    {
-                        await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: $"select value(c) from c where c.examId = '{info.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamClassResult-{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())
-                                {
-                                    examClassResults.Add(obj.ToObject<ExamClassResult>());
-                                }
-                            }
-                        }
-                    }
-
-                    string PartitionKey = string.Format("{0}{1}{2}", info.code, "-", info.progress);
-                    List<ChangeRecord> records = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", PartitionKey } });
-                    //处理科目信息
-                    List<string> sub = new List<string>();
-                    foreach (ExamSubject subject in info.subjects)
-                    {
-                        sub.Add(subject.id);
-                    }
-                    //ChangeRecord record = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ChangeRecord>(input.Id, new Azure.Cosmos.PartitionKey($"{info.progress}"));
-                    switch (info.progress)
-                    {
-                        case "pending":
-                            var message = new ServiceBusMessage(new { id = input.Id, progress = "going", code = code }.ToJsonString());
-                            message.ApplicationProperties.Add("name", "Exam");
-                            if (records.Count > 0)
-                            {
-                                await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), records[0].sequenceNumber);
-                                long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(stime));
-                                records[0].sequenceNumber = start;
-                                await _azureStorage.SaveOrUpdate<ChangeRecord>(records[0]);
-                                //await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(record, record.id, new Azure.Cosmos.PartitionKey($"{record.code}"));
-                            }
-                            else
-                            {
-                                long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(stime));
-                                //string pk = String.Format("{0}{1}{2}", info.code, "-", "pending");
-                                ChangeRecord changeRecord = new ChangeRecord
-                                {
-                                    RowKey = input.Id,
-                                    PartitionKey = PartitionKey,
-                                    sequenceNumber = start,
-                                    msgId = message.MessageId
-                                };
-                                await _azureStorage.Save<ChangeRecord>(changeRecord);
-                                //await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
-                            }
-                            break;
-                        case "going":
-
-                            try
-                            {
-                                //处理活动中间件
-                                (List<string> classes, List<RGroupList> members) = await Activity(info, client, _dingDing, sub);
-                                //向学生或醍摩豆账号发起通知
-                                #region
-                                //Notice notice = new Notice()
-                                //{
-                                //    msgId = info.id,
-                                //    creation = info.startTime,
-                                //    expire = info.endTime,
-                                //    creatorId = info.creatorId,
-                                //    stuids = studentss,
-                                //    tmdids = tmdids,
-                                //    type = "notice",//评测参加通知
-                                //    priority = "normal",
-                                //    school = info.school,
-                                //    scope = info.scope,
-                                //    //data = new { }.ToJsonString()
-                                //    body = new Body { sid = info.id, scode = info.code, spk = info.pk, biztype = "exam-join" }
-
-                                //};
-                                //var messageBlob = new ServiceBusMessage(notice.ToJsonString());
-                                //messageBlob.ApplicationProperties.Add("name", "Notice");
-                                //await _serviceBus.GetServiceBusClient().SendMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageBlob);
-                                #endregion
-                                if (examClassResults.Count == 0)
-                                {
-
-                                    foreach (string cla in classes)
-                                    {
-                                        int m = 0;
-                                        foreach (ExamSubject subject in info.subjects)
-                                        {
-                                            string classCode = string.Empty;
-                                            string cname = string.Empty;
-                                            if (string.IsNullOrEmpty(info.school) || !info.scope.Equals("school", StringComparison.OrdinalIgnoreCase))
-                                            {
-                                                classCode = "ExamClassResult-" + info.creatorId;                                               
-                                                //cname = members.Select(m => m.members.Where(c => c.groupId.Equals(cla)).Select(g => g.groupName)).ToString();
-                                            }
-                                            else
-                                            {
-                                                classCode = "ExamClassResult-" + info.school;
-                                                //cname = members.Select(m => m.members.Where(c => c.classId.Equals(cla)).Select(g => g.groupName)).ToString();
-                                            }
-                                            cname = members.Where(m => m.id.Equals(cla)).FirstOrDefault()?.name;
-                                            ExamClassResult result = new ExamClassResult
-                                            {
-                                                code = classCode,
-                                                examId = info.id,
-                                                id = Guid.NewGuid().ToString(),
-                                                subjectId = subject.id,
-                                                year = info.year,
-                                                scope = info.scope,
-                                            };
-                                            result.info.name = cname;
-                                            result.info.id = cla;
-                                            result.info.name = cname;
-                                            List<string> ans = new List<string>();
-                                            List<List<string>> anses = new List<List<string>>();
-                                            List<List<Details>> marks = new List<List<Details>>();
-                                            List<double> ansPoint = new List<double>();
-                                            List<string> ids = new List<string>();
-                                            foreach (double p in info.papers[m].point)
-                                            {
-                                                //Details details = new Details();
-                                                //ans.Add(new List<string>());
-                                                anses.Add(new List<string>());
-                                                marks.Add(new List<Details>());
-                                                ansPoint.Add(-1);
-                                            }
-                                            var sresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"Class-{info.school}"));
-                                            if (sresponse.Status == 200)
-                                            {
-
-                                                using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
-                                                Class classroom = json.ToObject<Class>();
-                                                School sc = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(info.school, new Azure.Cosmos.PartitionKey("Base"));
-                                                foreach (Period period in sc.period)
-                                                {
-                                                    if (period.id.Equals(classroom.periodId))
-                                                    {
-                                                        foreach (Semester semester in period.semesters)
-                                                        {
-                                                            if (semester.start == 1)
-                                                            {
-                                                                int year = DateTimeOffset.UtcNow.Year;
-                                                                int month = DateTimeOffset.UtcNow.Month;
-                                                                int day = DateTimeOffset.UtcNow.Day;
-                                                                int time = 0;
-                                                                if (month == semester.month)
-                                                                {
-                                                                    time = day >= semester.day ? 0 : 1;
-                                                                }
-                                                                else
-                                                                {
-                                                                    time = month > semester.month ? 0 : 1;
-                                                                }
-                                                                int eyear = year - time;
-                                                                result.gradeId = (eyear - classroom.year).ToString();
-                                                            }
-                                                        }
-                                                    }
-                                                }
-                                                //result.info.id = classroom.id;                                               
-                                                //result.gradeId = classroom.year.ToString();
-                                                //处理班级人数
-                                               /* await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: $"select c.id from c where c.classId = '{classroom.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{info.school}") }))
-                                                {
-                                                    using var json_stu = await JsonDocument.ParseAsync(item.ContentStream);
-                                                    if (json_stu.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
-                                                    {
-                                                        var accounts = json_stu.RootElement.GetProperty("Documents").EnumerateArray();
-                                                        while (accounts.MoveNext())
-                                                        {
-                                                            JsonElement account = accounts.Current;
-                                                            ids.Add(account.GetProperty("id").GetString());
-                                                        }
-                                                    }
-                                                }*/
-                                            }
-                                            /*if (info.scope.Equals("private", StringComparison.OrdinalIgnoreCase))
-                                            {
-                                                var stuResponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"GroupList"));
-                                                if (stuResponse.Status == 200)
-                                                {
-                                                    using var json = await JsonDocument.ParseAsync(stuResponse.ContentStream);
-                                                    GroupList stuList = json.ToObject<GroupList>();
-                                                    //result.info.id = stuList.id;
-                                                    result.info.name = stuList.name;
-                                                    //处理发布对象为自选名单(个人)
-
-                                                    foreach (Member stus in stuList.members)
-                                                    {
-
-                                                        if (!ids.Contains(stus.id))
-                                                        {
-                                                            ids.Add(stus.id);
-                                                        }
-                                                    }
-                                                }
-                                            }
-                                            else
-                                            {
-                                                var stuResponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"GroupList-{info.school}"));
-                                                if (stuResponse.Status == 200)
-                                                {
-                                                    using var json = await JsonDocument.ParseAsync(stuResponse.ContentStream);
-                                                    GroupList stuList = json.ToObject<GroupList>();
-                                                    //result.info.id = stuList.id;
-                                                    result.info.name = stuList.name;
-                                                    //处理发布对象为自选名单(校本)
-                                                    foreach (Member stus in stuList.members)
-                                                    {
-                                                        if (!ids.Contains(stus.id))
-                                                        {
-                                                            ids.Add(stus.id);
-                                                        }
-                                                    }
-                                                }
-                                            }*/
-                                            ids = members.Where(c => c.id.Equals(cla)).SelectMany( m => m.members).Select(g => g.id).ToList();
-                                            foreach (string stu in ids)
-                                            {
-                                                result.mark.Add(marks);
-                                                result.studentIds.Add(stu);
-                                                result.studentAnswers.Add(ans);
-                                                result.studentScores.Add(ansPoint);
-                                                result.ans.Add(anses);
-                                                result.sum.Add(0);
-                                            }
-
-                                            //result.progress = info.progress;
-                                            result.school = info.school;
-                                            m++;
-                                            await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(result, new Azure.Cosmos.PartitionKey($"{result.code}"));
-                                        }
-                                    }
-
-
-                                }
-                                else
-                                {
-                                    //处理单科结算时科目与试卷信息匹配的问题
-                                    int gno = 0;
-                                    foreach (ExamSubject subject in info.subjects)
-                                    {
-                                        if (subject.classCount == classes.Count)
-                                        {
-                                            await createClassResultAsync(info, examClassResults, subject, gno, _azureCosmos, _dingDing, _azureStorage);
-                                        }
-                                        gno++;
-                                    }
-                                }
-                            }
-                            catch (Exception e)
-                            {
-                                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测going状态异常{e.Message}\n{e.StackTrace}", GroupNames.成都开发測試群組);
-                            }
-                            finally
-                            {
-                                // 发送信息通知
-                                var messageEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = code }.ToJsonString());
-                                messageEnd.ApplicationProperties.Add("name", "Exam");
-                                if (records.Count > 0)
-                                {
-                                    long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(etime));
-                                    await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), records[0].sequenceNumber);
-                                    records[0].sequenceNumber = end;
-                                    await _azureStorage.SaveOrUpdate<ChangeRecord>(records[0]);
-                                    //await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(record, record.id, new Azure.Cosmos.PartitionKey($"{record.code}"));
-                                }
-                                else
-                                {
-                                    long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(etime));
-                                    //string pk = String.Format("{0}{1}{2}", info.code, "-", "going");
-                                    ChangeRecord changeRecord = new ChangeRecord
-                                    {
-                                        RowKey = input.Id,
-                                        PartitionKey = PartitionKey,
-                                        sequenceNumber = end,
-                                        msgId = messageEnd.MessageId
-                                    };
-                                    await _azureStorage.Save<ChangeRecord>(changeRecord);
-                                    //await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
-                                }
-                            }
-                            break;
-                        case "finish":
-                            int fno = 0;
-                            try
-                            {
-                                //处理活动中间件
-                                await Activity(info, client, _dingDing, sub);
-                                foreach (ExamSubject subject in info.subjects)
-                                {
-                                    await createClassResultAsync(info, examClassResults, subject, fno, _azureCosmos, _dingDing, _azureStorage);
-                                    fno++;
-                                }
-
-                                //计算单次考试简易统计信息
-                                List<ExamResult> examResults = new List<ExamResult>();
-                                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamResult>(
-                                                   queryText: $"select value(c) from c where c.examId  = '{info.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}") }))
-                                {
-                                    examResults.Add(item);
-                                }
-                                List<Task<ItemResponse<ExamClassResult>>> tasks = new List<Task<ItemResponse<ExamClassResult>>>();
-                                //结算单科单班的标准差和平均分
-                                foreach (ExamClassResult classResult in examClassResults)
-                                {
-                                    //标记单科单班总得分
-                                    double subScore = 0;
-                                    //标准差
-                                    double sPowSum = 0;
-                                    List<double> newSumScore = new List<double>();
-                                    var scount = classResult.studentIds.Count;
-                                    foreach (List<double> sc in classResult.studentScores)
-                                    {
-                                        List<double> newSc = new List<double>();
-                                        foreach (double ssc in sc)
-                                        {
-                                            if (ssc == -1)
-                                            {
-                                                newSc.Add(0);
-                                            }
-                                            else
-                                            {
-                                                newSc.Add(ssc);
-                                            }
-                                        }
-                                        double nc = newSc.Sum();
-                                        newSumScore.Add(nc);
-                                        subScore += nc;
-                                    }
-                                    double rateScore = scount > 0 ? Math.Round(subScore * 1.0 / scount, 2) : 0;
-                                    foreach (double scs in newSumScore)
-                                    {
-                                        sPowSum += Math.Pow(scs - rateScore, 2);
-
-                                    }
-                                    classResult.standard = Math.Round(scount > 0 ? Math.Pow(sPowSum / scount, 0.5) : 0, 2);
-                                    classResult.average = scount > 0 ? Math.Round(subScore / scount, 2) : 0;
-                                    classResult.progress = true;
-                                    tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new Azure.Cosmos.PartitionKey($"{classResult.code}")));
-                                }
-                                await Task.WhenAll(tasks);
-                                //记录某次考试所有学生得分总分
-                                double score = 0;
-                                double allScore = 0;
-                                int stuCount = 0;
-                                //标准差
-                                double powSum = 0;
-                                List<string> losStu = new List<string>();
-                                //先与第一个值取并集
-                                if (examResults.Count > 0)
-                                {
-                                    losStu = losStu.Union(examResults[0].lostStus).ToList();
-                                    foreach (ExamResult examResult in examResults)
-                                    {
-                                        if (info.id == examResult.examId)
-                                        {
-                                            foreach (List<double> sc in examResult.studentScores)
-                                            {
-                                                score += sc.Sum();
-                                            }
-                                            stuCount = examResult.studentIds.Count;
-                                        }
-                                        //powSum += Math.Pow(score - examResult.studentIds.Count > 0 ? Math.Round(score * 1.0 / examResult.studentIds.Count, 2) : 0, 2);
-                                        //取交集
-                                        losStu = losStu.Intersect(examResult.lostStus).ToList();
-                                    }
-                                }
-                                double NewsRateScore = stuCount > 0 ? Math.Round(score * 1.0 / stuCount, 2) : 0;
-                                foreach (PaperSimple simple in info.papers)
-                                {
-                                    allScore += simple.point.Sum();
-                                }
-                                //计算全科标准差
-                                foreach (string id in examResults[0].studentIds)
-                                {
-                                    double sc = 0;
-                                    foreach (ExamResult result in examResults)
-                                    {
-                                        sc += result.studentScores[result.studentIds.IndexOf(id)].Sum();
-                                    }
-                                    powSum += Math.Pow(sc - NewsRateScore, 2);
-                                }
-                                info.standard = Math.Round(examResults[0].studentIds.Count > 0 ? Math.Pow(powSum / examResults[0].studentIds.Count, 0.5) : 0, 2);
-                                double NewsRate = allScore > 0 ? Math.Round(NewsRateScore / allScore * 100, 2) : 0;
-                                info.lostStu = losStu;
-                                /*//补充历史数据的容器名称
-                                if (string.IsNullOrEmpty(info.cn)) {
-                                    if (info.scope.Equals("school"))
-                                    {
-                                        info.cn = info.school;
-                                    }
-                                    else {
-                                        info.cn = info.creatorId;
-                                    }
-                                }*/
-                                //判断均分是否发生变化,便于实时的更新评测基本信息
-                                if (info.sRate != NewsRate || info.average != NewsRateScore)
-                                {
-                                    info.sRate = NewsRate;
-                                    info.average = NewsRateScore;
-                                    await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ExamInfo>(info, info.id, new Azure.Cosmos.PartitionKey(info.code));
-                                }
-                            }
-                            catch (Exception e)
-                            {
-                                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测finish状态异常{e.Message}\n{e.StackTrace}", GroupNames.成都开发測試群組);
-                            }
-                            break;
-                    }
-                }
-
-            }
-            catch (CosmosException e)
-            {
-                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDB异常{e.Message}\n{e.Status}", GroupNames.成都开发測試群組);
-            } catch (Exception e) {
-                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-评测结算异常{e.Message}\n{e.StackTrace}", GroupNames.成都开发測試群組);
-            }
-
-        }
-        //处理全部学生选题计数
-        public static async Task examRecordCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, ExamResult result, List<ExamClassResult> classResults, AzureCosmosFactory _azureCosmos)
-        {
-            try
-            {
-                List<double> scores = new List<double>();
-                foreach (List<double> sc in result.studentScores)
-                {
-                    scores.Add(sc.Sum());
-                }
-                //确定高分组 最低分数
-                scores.Sort((s1, s2) => { return s2.CompareTo(s1); });
-                double rhwCount = Math.Floor(scores.Count * 0.27);
-                double rhw = rhwCount > 0 ? scores[int.Parse(rhwCount.ToString("0"))] : 0;
-                //确定低分组 最高分数
-                //scores.Sort((s1, s2) => { return s1.CompareTo(s2); });
-                double rhlCount = Math.Ceiling(scores.Count * 0.73);
-                double rhl = rhlCount > 0 ? scores[int.Parse(rhlCount.ToString("0")) - 1] : 0;
-                //存放高分组学生ID
-                List<string> phId = new List<string>();
-                List<string> plId = new List<string>();
-                List<List<List<string>>> opth = new List<List<List<string>>>();
-                List<List<List<string>>> optl = new List<List<List<string>>>();
-                await knowledgeCount(info, subject, _dingDing, no, classResults, rhwCount, rhw, rhlCount, rhl, _azureCosmos);
-                await fieldCount(info, subject, _dingDing, no, classResults, rhwCount, rhw, rhlCount, rhl, _azureCosmos);
-                int PHCount = 0;
-                int PLCount = 0;
-                foreach (ExamClassResult classResult in classResults)
-                {
-                    if (classResult.subjectId.Equals(subject.id))
-                    {
-                        foreach (string id in classResult.studentIds)
-                        {
-                            int index = classResult.studentIds.IndexOf(id);
-                            if (classResult.studentScores.Count > 0)
-                            {
-                                if (classResult.studentScores[index].Sum() >= rhw && PHCount < rhwCount)
-                                {
-                                    if (classResult.ans.Count > 0)
-                                    {
-                                        opth.Add(classResult.ans[index]);
-                                        PHCount++;
-                                        continue;
-                                    }
-
-                                }
-                                if (classResult.studentScores[index].Sum() <= rhl && PLCount < (scores.Count - rhlCount))
-                                {
-                                    if (classResult.ans.Count > 0)
-                                    {
-                                        optl.Add(classResult.ans[index]);
-                                        PLCount++;
-                                        continue;
-                                    }
-                                }
-
-                            }
-
-                        }
-                    }
-                }
-                result.phc = getMore(info, no, opth);
-                result.plc = getMore(info, no, optl);
-            }
-            catch (Exception ex)
-            {
-                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测作答记录结算异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
-            }
-        }
-        public static async Task<(List<string> classes, List<RGroupList> members)> Activity(ExamInfo info, CosmosClient client, DingDing _dingDing, List<string> sub) {
-            List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
-            if (info.groupLists.Count > 0)
-            {
-                var group = info.groupLists;
-                foreach (var gp in group)
-                {
-                    foreach (KeyValuePair<string, List<string>> pp in gp)
-                    {
-                        ps.Add((pp.Key, pp.Value));
-                    }
-                }
-            }
-            List<string> classes = ExamService.getClasses(info.classes, info.stuLists);
-            (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(client, _dingDing, classes, info.school, ps);
-            var addStudentsCls = tchList.FindAll(x => x.type == 2);
-            var addTmdidsCls = tchList.FindAll(x => x.type == 1);
-            List<StuActivity> stuActivities = new List<StuActivity>();
-            List<StuActivity> tmdActivities = new List<StuActivity>();
-            if (addTmdidsCls.IsNotEmpty())
-            {
-                addTmdidsCls.ForEach(x =>
-                {
-                    tmdActivities.Add(new StuActivity
-                    {
-                        pk = "Activity",
-                        id = info.id,
-                        code = $"Activity-{x.id}",
-                        type = "Exam",
-                        name = info.name,
-                        source = info.source,
-                        startTime = info.startTime,
-                        endTime = info.endTime,
-                        scode = info.code,
-                        scope = info.scope,
-                        school = info.school,
-                        creatorId = info.creatorId,
-                        subjects = sub,
-                        blob = null,
-                        owner = info.owner,
-                        createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
-                        taskStatus = -1,
-                        classIds = classes
-
-                    });
-                });
-            }
-            if (addStudentsCls.IsNotEmpty())
-            {
-                addStudentsCls.ForEach(x =>
-                {
-                    stuActivities.Add(new StuActivity
-                    {
-                        pk = "Activity",
-                        id = info.id,
-                        code = $"Activity-{x.code.Replace("Base-", "")}-{x.id}",
-                        type = "Exam",
-                        name = info.name,
-                        source = info.source,
-                        startTime = info.startTime,
-                        endTime = info.endTime,
-                        scode = info.code,
-                        scope = info.scope,
-                        school = info.school,
-                        creatorId = info.creatorId,
-                        subjects = sub,
-                        blob = null,
-                        owner = info.owner,
-                        classIds = classes,
-                        createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
-                        taskStatus = -1
-                    });
-                });
-            }
-            await ActivityService.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities, null);
-            return (classes, classLists);
-        }
-
-        public static async Task knowledgeCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, List<ExamClassResult> classResults,
-            double rhwCount, double rhw, double rhlCount, double rhl, AzureCosmosFactory _azureCosmos)
-        {
-            try
-            {
-                int phcount = 0;
-                int plcount = 0;
-                //存放并去重知识点
-                HashSet<string> kname = new HashSet<string>();
-                if (info.papers[no].knowledge.Count > 0)
-                {
-                    info.papers[no].knowledge.ForEach(kno =>
-                    {
-                        kno.ForEach(k =>
-                        {
-                            kname.Add(k);
-                        });
-                    });
-                    List<string> knowledgeName = new List<string>();
-                    foreach (string cla in kname)
-                    {
-                        knowledgeName.Add(cla);
-                    }
-                    for (int k = 0; k < knowledgeName.Count; k++)
-                    {
-                        if (null == knowledgeName[k])
-                        {
-                            knowledgeName.Remove(knowledgeName[k]);
-                        }
-                    }
-
-                    foreach (ExamClassResult classResult in classResults)
-                    {
-                        if (classResult.subjectId.Equals(subject.id))
-                        {
-                            //List<int> phc = new List<int>();
-                            List<int> ph = new List<int>();
-                            List<int> pl = new List<int>();
-                            List<int> pc = new List<int>();
-                            List<double> persent = new List<double>();
-                            for (int i = 0; i < knowledgeName.Count; i++)
-                            {
-                                //初始化单个知识点得分
-                                double score = 0;
-                                double allScore = 0;
-                                int n = 0;
-                                int phCount = 0;
-                                int plCount = 0;
-                                int pCount = 0;
-                                foreach (List<string> str in info.papers[no].knowledge)
-                                {
-                                    if (str.Contains(knowledgeName[i]))
-                                    {
-                                        var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
-                                        allScore += info.papers[no].point.Count > 0 ? info.papers[no].point[n] * itemPersent : 0;
-                                        foreach (string id in classResult.studentIds)
-                                        {
-                                            int index = classResult.studentIds.IndexOf(id);
-                                            if (classResult.studentScores.Count > 0)
-                                            {
-                                                if (classResult.studentScores[index].Count > 0)
-                                                {
-                                                    score += classResult.studentScores[index][n] == -1 ? 0 : classResult.studentScores[index][n];
-                                                    if (classResult.studentScores[index].Sum() >= rhw && phcount < rhwCount)
-                                                    {
-                                                        if (classResult.studentScores[index][n] <= 0)
-                                                        {
-                                                            phCount++;
-                                                        }
-                                                        phcount++;
-                                                        continue;
-                                                    }
-                                                    if (classResult.studentScores[index].Sum() <= rhl && plcount < (info.stuCount - rhlCount))
-                                                    {
-                                                        if (classResult.studentScores[index][n] <= 0)
-                                                        {
-                                                            plCount++;
-                                                        }
-                                                        plcount++;
-                                                        continue;
-                                                    }
-                                                    if (classResult.studentScores[index][n] <= 0)
-                                                    {
-                                                        pCount++;
-                                                    }
-                                                }
-                                            }
-
-                                        }
-                                    }
-                                    n++;
-                                }
-                                pc.Add(pCount);
-                                ph.Add(phCount);
-                                pl.Add(plCount);
-                                double per = classResult.studentIds.Count > 0 ? Math.Round(score / classResult.studentIds.Count, 2) : 0;
-                                persent.Add(allScore > 0 ? per / allScore : 0);
-                            }
-                            classResult.phc = ph;
-                            classResult.plc = pl;
-                            classResult.pc = pc;
-                            classResult.krate = persent;
-                        }
-                        //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new Azure.Cosmos.PartitionKey($"{classResult.code}"));
-                    }
-                }
-
-            }
-            catch (Exception ex)
-            {
-                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测知识点结算异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
-            }
-        }
-
-        public static async Task fieldCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, List<ExamClassResult> classResults,
-            double rhwCount, double rhw, double rhlCount, double rhl, AzureCosmosFactory _azureCosmos)
-        {
-            try
-            {
-                int phcount = 0;
-                int plcount = 0;
-                //存放并去重知识点
-                List<int> knowledgeName = new List<int>() { 1,2,3,4,5,6};
-/*                knowledgeName.Add(1);
-                knowledgeName.Add(2);
-                knowledgeName.Add(3);
-                knowledgeName.Add(4);
-                knowledgeName.Add(5);
-                knowledgeName.Add(6);*/
-                foreach (ExamClassResult classResult in classResults)
-                {
-                    if (classResult.subjectId.Equals(subject.id))
-                    {
-                        //List<int> phc = new List<int>();
-                        List<int> ph = new List<int>();
-                        List<int> pl = new List<int>();
-                        List<int> pc = new List<int>();
-                        List<double> persent = new List<double>();
-                        for (int i = 0; i < knowledgeName.Count; i++)
-                        {
-                            //初始化单个知识点得分
-                            double score = 0;
-                            double allScore = 0;
-                            int n = 0;
-                            int phCount = 0;
-                            int plCount = 0;
-                            int pCount = 0;
-                            if (info.papers[no].field.Count > 0)
-                            {
-                                foreach (int str in info.papers[no].field)
-                                {
-                                    if (str == knowledgeName[i])
-                                    {
-                                        var itemPersent = 1;
-                                        allScore += info.papers[no].point.Count > 0 ? info.papers[no].point[n] * itemPersent : 0;
-                                        foreach (string id in classResult.studentIds)
-                                        {
-                                            int index = classResult.studentIds.IndexOf(id);
-                                            if (classResult.studentScores.Count > 0)
-                                            {
-                                                if (classResult.studentScores[index].Count > 0)
-                                                {
-                                                    score += classResult.studentScores[index][n] == -1 ? 0 : classResult.studentScores[index][n];
-                                                    if (classResult.studentScores[index].Sum() >= rhw && phcount < rhwCount)
-                                                    {
-                                                        if (classResult.studentScores[index][n] <= 0)
-                                                        {
-                                                            phCount++;
-                                                        }
-                                                        phcount++;
-                                                        continue;
-                                                    }
-                                                    if (classResult.studentScores[index].Sum() <= rhl && plcount < (info.stuCount - rhlCount))
-                                                    {
-                                                        if (classResult.studentScores[index][n] <= 0)
-                                                        {
-                                                            plCount++;
-                                                        }
-                                                        plcount++;
-                                                        continue;
-                                                    }
-                                                    if (classResult.studentScores[index][n] <= 0)
-                                                    {
-                                                        pCount++;
-                                                    }
-                                                }
-                                            }
-                                        }
-                                    }
-                                    n++;
-                                }
-                                pc.Add(pCount);
-                                ph.Add(phCount);
-                                pl.Add(plCount);
-                                double per = classResult.studentIds.Count > 0 ? Math.Round(score / classResult.studentIds.Count, 2) : 0;
-                                persent.Add(allScore > 0 ? per / allScore : 0);
-                            }
-                        }
-                        classResult.fphc = ph;
-                        classResult.fplc = pl;
-                        classResult.fpc = pc;
-                        classResult.frate = persent;
-                    }
-                    //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new Azure.Cosmos.PartitionKey($"{classResult.code}"));
-                }
-            }
-            catch (Exception ex)
-            {
-                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测认知层次结算异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
-            }
-        }
-        //处理选题计数
-        public static List<Dictionary<string, int>> getMore(ExamInfo info, int no, List<List<List<string>>> list)
-        {
-            List<Dictionary<string, int>> recorde = new List<Dictionary<string, int>>();
-            try
-            {
-                for (int i = 0; i < info.papers[no].answers.Count; i++)
-                {
-                    if (info.papers[no].answers[i].Count <= 0)
-                    {
-                        recorde.Add(new Dictionary<string, int>());
-                        continue;
-                    }
-                    Dictionary<string, int> optCount = new Dictionary<string, int>();
-                    foreach (List<List<string>> stu in list)
-                    {
-                        if (stu.Count == info.papers[no].answers.Count)
-                        {
-
-                            var item = stu[i];
-                            foreach (string opt in item)
-                            {
-                                if (optCount.ContainsKey(opt))
-                                {
-                                    optCount[opt] = optCount[opt] + 1;
-                                }
-                                else
-                                {
-                                    optCount[opt] = 1;
-                                }
-                            }
-
-                        }
-                    }
-                    recorde.Add(optCount);
-                }
-                return recorde;
-            }
-            catch (Exception)
-            {
-                return recorde;
-            }
-        }
-        public static async Task createClassResultAsync(ExamInfo info, List<ExamClassResult> examClassResults, ExamSubject subject, int no, AzureCosmosFactory _azureCosmos, DingDing _dingDing, AzureStorageFactory _azureStorage)
-        {
-            //保证试卷信息与科目信息同步
-            ExamResult result = new ExamResult();
-            //人数总和
-            int Count = 0;
-            int m = 0;
-            double score = 0;
-            //标准差
-            double powSum = 0;
-            double allScore = info.papers[no].point.Sum();
-            List<ClassRange> classRanges = new List<ClassRange>();
-            List<string> lostStu = new List<string>();
-            List<double> csRate = new List<double>();
-            List<List<List<string>>> opt = new List<List<List<string>>>();
-            foreach (ExamClassResult classResult in examClassResults)
-            {
-                double classSrate = 0;
-                if (classResult.subjectId.Equals(subject.id))
-                {
-                    foreach (List<List<string>> op in classResult.ans)
-                    {
-                        opt.Add(op);
-                    }
-                    //记录缺考学生索引位置
-                    int index = 0;
-                    foreach (List<double> scores in classResult.studentScores)
-                    {
-                        List<double> newScores = new List<double>();
-                        int count = 0;
-                        foreach (double sc in scores)
-                        {
-                            newScores.Add(sc > -1 ? sc : 0);
-                            if (sc == -1)
-                            {
-                                count++;
-                            }
-                        }
-                        if (count == scores.Count)
-                        {
-                            lostStu.Add(classResult.studentIds[index]);
-                            //mcount++;
-                        }
-                        classSrate += newScores.Sum();
-                        score += newScores.Sum();
-                        result.studentScores.Add(newScores);
-                        index++;
-                    }
-
-                    //处理班级信息
-                    ClassRange range = new ClassRange();
-                    range.id = classResult.info.id;
-                    range.name = classResult.info.name;
-                    range.gradeId = classResult.gradeId;
-                    List<int> ran = new List<int>();
-                    int stuCount = classResult.studentIds.Count;
-                    Count += stuCount;
-                    if (m == 0)
-                    {
-                        ran.Add(0);
-                        ran.Add(stuCount - 1);
-                    }
-                    else
-                    {
-                        ran.Add(Count - stuCount);
-                        ran.Add(Count - 1);
-                    }
-                    m++;
-                    range.range = ran;
-                    classRanges.Add(range);
-                    //处理学生ID 
-                    foreach (string id in classResult.studentIds)
-                    {
-                        result.studentIds.Add(id);
-                    }
-                    if (allScore > 0)
-                    {
-                        csRate.Add(classResult.studentIds.Count > 0 ? Math.Round(classSrate * 1.0 / classResult.studentIds.Count, 2) : 0 / allScore);
-
-                    }
-                    else
-                    {
-                        csRate.Add(0);
-                    }
-
-                    //powSum += Math.Pow(classSrate - result.average, 2);
-                    //处理选项计数内容
-                }
-            }
-            await examRecordCount(info, subject, _dingDing, no, result, examClassResults, _azureCosmos);
-            result.record = getMore(info, no, opt);
-            result.average = result.studentIds.Count > 0 ? Math.Round(score * 1.0 / result.studentIds.Count, 2) : 0;
-            double stand = 0;
-            int sco = 0;
-            foreach (ExamClassResult classResult in examClassResults)
-            {
-
-                //double classSrate = 0;
-                if (classResult.subjectId.Equals(subject.id))
-                {
-                    stand += classResult.standard;
-                    sco++;
-                }
-
-            }
-            result.standard = sco > 0 ? Math.Round(stand / sco, 2) : 0;
-            result.csRate = csRate;
-            result.lostStus = lostStu;
-
-            result.sRate = allScore > 0 ? Math.Round(result.average / allScore * 100, 2) : 0;
-            result.classes = classRanges;
-            result.code = "ExamResult-" + info.id;
-            result.school = info.school;
-            result.id = subject.id;
-            result.examId = info.id;
-            result.subjectId = subject.id;
-            result.year = info.year;
-            result.paper = info.papers[no];
-            //result.point = info.papers[j].point;
-            result.scope = info.scope;
-            result.name = info.name;
-            result.time = info.startTime;
-
-            await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").UpsertItemAsync(result, new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}"));
-
-        }
-    }
-}

+ 0 - 170
TEAMModelFunction/TriggerExamLite.cs

@@ -1,170 +0,0 @@
-using Azure.Cosmos;
-using Azure.Messaging.ServiceBus;
-using HTEXLib.COMM.Helpers;
-using Microsoft.Azure.Documents;
-using Microsoft.Extensions.Configuration;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using TEAMModelOS.SDK;
-using TEAMModelOS.SDK.DI;
-using TEAMModelOS.SDK.Extension;
-using TEAMModelOS.SDK.Models;
-using TEAMModelOS.SDK.Models.Cosmos.Common;
-
-namespace TEAMModelFunction
-{
-    public static class TriggerExamLite
-    {
-        public static async Task Trigger(AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
-                    CosmosClient client, Document input, TriggerData tdata, AzureRedisFactory _azureRedis, IConfiguration _configuration)
-        {
-            try
-            {
-                if ((tdata.status != null && tdata.status.Value == 404) || tdata.ttl > 0)
-                {
-                    return;
-                }
-                var adid = tdata.id;
-                var adcode = "";
-                string blobcntr = null;
-                if (tdata.scope.Equals("school"))
-                {
-                    adcode = $"Activity-{tdata.school}";
-                    blobcntr = tdata.school;
-                }
-                else
-                {
-                    adcode = $"Activity-{tdata.creatorId}";
-                    blobcntr = tdata.creatorId;
-                }
-                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}研修评测活动【{tdata.name}-{tdata.id}-ttl={tdata.ttl}】正在操作", GroupNames.成都开发測試群組);
-                ExamLite lite = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamLite>(input.Id, new Azure.Cosmos.PartitionKey($"{tdata.code}"));
-                
-                if (lite != null)
-                {
-                    string PartitionKey = string.Format("{0}{1}{2}", lite.code, "-", lite.progress);
-                    List<ChangeRecord> changeRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", PartitionKey } });
-                    switch (lite.progress)
-                    {
-                        case "pending":
-                            var messageWork = new ServiceBusMessage(new { id = input.Id, progress = "going", code = tdata.code }.ToJsonString());
-                            messageWork.ApplicationProperties.Add("name", "ExamLite");
-                            if (changeRecords.Count > 0)
-                            {
-                                await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), changeRecords[0].sequenceNumber);
-                                long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWork, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
-                                changeRecords[0].sequenceNumber = start;
-                                await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
-                            }
-                            else
-                            {
-                                long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWork, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
-                                ChangeRecord changeRecord = new ChangeRecord
-                                {
-                                    RowKey = input.Id,
-                                    PartitionKey = PartitionKey,
-                                    sequenceNumber = start,
-                                    msgId = messageWork.MessageId
-                                };
-                                await _azureStorage.Save<ChangeRecord>(changeRecord);
-                            }
-                            break;
-                        case "going":
-                            List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
-                            if (lite.groupLists.Count > 0)
-                            {
-                                var group = lite.groupLists;
-                                foreach (var gp in group)
-                                {
-                                    foreach (KeyValuePair<string, List<string>> pp in gp)
-                                    {
-                                        ps.Add((pp.Key, pp.Value));
-                                    }
-                                }
-                            }
-                            (List<RMember> tchList, List<RGroupList> classInfos) = await GroupListService.GetStutmdidListids(client, _dingDing, lite.tchLists, lite.school, ps);
-                            List<StuActivity> tchActivities = new List<StuActivity>();
-                            (string standard, List<string> tmdids, string school, List<string> update, int statistics)  list =    (null,null, null, new List<string> { StatisticsService.TeacherExamLite }, 0)  ;
-                            if (tchList.IsNotEmpty())
-                            {
-                                list.tmdids = tchList.Select(x => x.id).ToList();
-                                School school = null;
-                                if (!string.IsNullOrEmpty(lite.school))
-                                {
-                                    school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(lite.school, new Azure.Cosmos.PartitionKey("Base"));
-                                    list.school = school.id;
-                                    list.standard = school.standard;
-                                }
-                                tchList.ForEach(x =>
-                                {
-                                    tchActivities.Add(new StuActivity
-                                    {
-                                        pk = "Activity",
-                                        id = lite.id,
-                                        code = $"Activity-{x.id}",
-                                        type = "ExamLite",
-                                        name = lite.name,
-                                        startTime = lite.startTime,
-                                        endTime = lite.endTime,
-                                        scode = lite.code,
-                                        scope = lite.scope,
-                                        school = lite.school,
-                                        creatorId = lite.creatorId,
-                                        subjects = new List<string> { "" },
-                                        blob = null,
-                                        owner = lite.owner,
-                                        createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
-                                        taskStatus = -1,
-                                        classIds = lite.tchLists
-                                    });
-                                   
-                                });
-                              
-                            }
-                            await ActivityService.SaveStuActivity(client, _dingDing, null, null, tchActivities);
-                            await StatisticsService.SendServiceBus(list, _configuration, _serviceBus,   client);
-                            var messageWorkEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = tdata.code }.ToJsonString());
-                            messageWorkEnd.ApplicationProperties.Add("name", "ExamLite");
-                            if (changeRecords.Count > 0)
-                            {
-                                long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWorkEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
-                                await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), changeRecords[0].sequenceNumber);
-                                changeRecords[0].sequenceNumber = end;
-                                await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
-                            }
-                            else
-                            {
-                                long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWorkEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
-                                ChangeRecord changeRecord = new ChangeRecord
-                                {
-                                    RowKey = input.Id,
-                                    PartitionKey = PartitionKey,
-                                    sequenceNumber = end,
-                                    msgId = messageWorkEnd.MessageId
-                                };
-                                await _azureStorage.Save<ChangeRecord>(changeRecord);
-                            }
-                            break;
-                        case "finish":
-                            break;
-                    }
-
-
-                }
-
-            }
-            catch (CosmosException e)
-            {
-                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDB异常{e.Message}\n{e.Status}", GroupNames.成都开发測試群組);
-            }
-            catch (Exception ex)
-            {
-                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}研修评测异常{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
-            }
-
-        }
-    }
-}

+ 0 - 229
TEAMModelFunction/TriggerHomework.cs

@@ -1,229 +0,0 @@
-using Azure.Cosmos;
-using Azure.Messaging.ServiceBus;
-using HTEXLib.COMM.Helpers;
-using Microsoft.Azure.Documents;
-using Microsoft.Extensions.Configuration;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using TEAMModelOS.SDK;
-using TEAMModelOS.SDK.DI;
-using TEAMModelOS.SDK.Extension;
-using TEAMModelOS.SDK.Models;
-using TEAMModelOS.SDK.Models.Cosmos.Common;
-using TEAMModelOS.SDK.Models.Service;
-
-namespace TEAMModelFunction
-{
-    public static class TriggerHomework
-    {
-        public static async Task Trigger(AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
-                    CosmosClient client, Document input, TriggerData tdata, AzureRedisFactory _azureRedis, IConfiguration _configuration)
-        {
-            try
-            {
-                if ((tdata.status != null && tdata.status.Value == 404) || tdata.ttl > 0)
-                {
-                    return;
-                }
-                var adid = tdata.id;
-                var adcode = "";
-                string blobcntr = null;
-                if (tdata.scope.Equals("school"))
-                {
-                    adcode = $"Activity-{tdata.school}";
-                    blobcntr = tdata.school;
-                }
-                else
-                {
-                    adcode = $"Activity-{tdata.creatorId}";
-                    blobcntr = tdata.creatorId;
-                }
-                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}作业活动【{tdata.name}-{tdata.id}-ttl={tdata.ttl}】正在操作", GroupNames.成都开发測試群組);
-                Homework work = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Homework>(input.Id, new Azure.Cosmos.PartitionKey($"{tdata.code}"));
-                
-                if (work != null)
-                {
-                    string PartitionKey = string.Format("{0}{1}{2}", work.code, "-", work.progress);
-                    List<ChangeRecord> changeRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", PartitionKey } });
-                    switch (work.progress)
-                    {
-                        case "pending":
-                            var messageWork = new ServiceBusMessage(new { id = input.Id, progress = "going", code = tdata.code }.ToJsonString());
-                            messageWork.ApplicationProperties.Add("name", "Homework");
-                            if (changeRecords.Count > 0)
-                            {
-                                await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), changeRecords[0].sequenceNumber);
-                                long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWork, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
-                                changeRecords[0].sequenceNumber = start;
-                                await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
-                            }
-                            else
-                            {
-                                long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWork, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
-                                ChangeRecord changeRecord = new ChangeRecord
-                                {
-                                    RowKey = input.Id,
-                                    PartitionKey = PartitionKey,
-                                    sequenceNumber = start,
-                                    msgId = messageWork.MessageId
-                                };
-                                await _azureStorage.Save<ChangeRecord>(changeRecord);
-                            }
-                            break;
-                        case "going":
-                            List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
-                            if (work.groupLists.Count > 0)
-                            {
-                                var group = work.groupLists;
-                                foreach (var gp in group)
-                                {
-                                    foreach (KeyValuePair<string, List<string>> pp in gp)
-                                    {
-                                        ps.Add((pp.Key, pp.Value));
-                                    }
-                                }
-                            }
-                            List<string> classes = ExamService.getClasses(work.classes, work.stuLists);
-                            (List<RMember> tmdids, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(client, _dingDing, classes, work.school, ps);
-                            var addStudentsCls = tmdids.FindAll(x => x.type == 2);
-                            var addTmdidsCls = tmdids.FindAll(x => x.type == 1);
-                            List<StuActivity> stuActivities = new List<StuActivity>();
-                            List<StuActivity> tmdActivities = new List<StuActivity>();
-                            List<StuActivity> tchActivities = new List<StuActivity>();
-                            if (addTmdidsCls.IsNotEmpty())
-                            {
-                                addTmdidsCls.ForEach(x =>
-                                {
-                                    tmdActivities.Add(new StuActivity
-                                    {
-                                        pk = "Activity",
-                                        id = work.id,
-                                        code = $"Activity-{x.id}",
-                                        type = "Homework",
-                                        name = work.name,
-                                        startTime = work.startTime,
-                                        endTime = work.endTime,
-                                        scode = work.code,
-                                        scope = work.scope,
-                                        school = work.school,
-                                        creatorId = work.creatorId,
-                                        subjects = new List<string> { "" },
-                                        blob = work.blob,
-                                        owner = work.owner,
-                                        createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
-                                        taskStatus = -1,
-                                        classIds = classes
-                                    });
-                                });
-                            }
-                            if (addStudentsCls.IsNotEmpty())
-                            {
-                                addStudentsCls.ForEach(x =>
-                                {
-                                    stuActivities.Add(new StuActivity
-                                    {
-                                        pk = "Activity",
-                                        id = work.id,
-                                        code = $"Activity-{x.code.Replace("Base-", "")}-{x.id}",
-                                        type = "Homework",
-                                        name = work.name,
-                                        startTime = work.startTime,
-                                        endTime = work.endTime,
-                                        scode = work.code,
-                                        scope = work.scope,
-                                        school = work.school,
-                                        creatorId = work.creatorId,
-                                        subjects = new List<string> { "" },
-                                        blob = work.blob,
-                                        owner = work.owner,
-                                        createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
-                                        taskStatus = -1,
-                                        classIds = classes
-                                    });
-                                });
-                            }
-                            (List<RMember> tchList, List<RGroupList> classInfos) = await GroupListService.GetStutmdidListids(client, _dingDing, work.tchLists, work.school,ps);
-                            (string standard, List<string> tmdids, string school, List<string> update, int statistics) list = (null, null, null, new List<string> { StatisticsService.OfflineRecord }, 0);
-                            if (tchList.IsNotEmpty())
-                            {
-                                list.tmdids = tchList.Select(x => x.id).ToList();
-                                School school = null;
-                                if (!string.IsNullOrEmpty(work.school))
-                                {
-                                    school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(work.school, new Azure.Cosmos.PartitionKey("Base"));
-                                    list.school = school.id;
-                                    list.standard = school.standard;
-                                }
-                                tchList.ForEach(x =>
-                                {
-                                    tchActivities.Add(new StuActivity
-                                    {
-                                        pk = "Activity",
-                                        id = work.id,
-                                        code = $"Activity-{x.id}",
-                                        type = "Homework",
-                                        name = work.name,
-                                        startTime = work.startTime,
-                                        endTime = work.endTime,
-                                        scode = work.code,
-                                        scope = work.scope,
-                                        school = work.school,
-                                        creatorId = work.creatorId,
-                                        subjects = new List<string> { "" },
-                                        blob = work.blob,
-                                        owner = work.owner,
-                                        createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
-                                        taskStatus = -1,
-                                        classIds = work.tchLists
-                                    });
-                                     
-                                });
-                            }
-                            await ActivityService.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities, tchActivities);
-                            await StatisticsService.SendServiceBus(list, _configuration, _serviceBus, client);
-                            var messageWorkEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = tdata.code }.ToJsonString());
-                            messageWorkEnd.ApplicationProperties.Add("name", "Homework");
-                            if (changeRecords.Count > 0)
-                            {
-                                long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWorkEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
-                                await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), changeRecords[0].sequenceNumber);
-                                changeRecords[0].sequenceNumber = end;
-                                await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
-                            }
-                            else
-                            {
-                                long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWorkEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
-                                ChangeRecord changeRecord = new ChangeRecord
-                                {
-                                    RowKey = input.Id,
-                                    PartitionKey = PartitionKey,
-                                    sequenceNumber = end,
-                                    msgId = messageWorkEnd.MessageId
-                                };
-                                await _azureStorage.Save<ChangeRecord>(changeRecord);
-                            }
-                            //if (bustasks.IsNotEmpty())
-                            //{
-                            //    await Task.WhenAll(bustasks);
-                            //}
-                            break;
-                        case "finish":
-                            break;
-                    }
-
-                }
-            }
-            catch (CosmosException e)
-            {
-                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDB异常{e.Message}\n{e.Status}", GroupNames.成都开发測試群組);
-            }
-            catch (Exception ex)
-            {
-                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}研修作业活动异常{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
-            }
-        }
-    }
-}

+ 0 - 175
TEAMModelFunction/TriggerStudy.cs

@@ -1,175 +0,0 @@
-using Azure.Cosmos;
-using Azure.Messaging.ServiceBus;
-using HTEXLib.COMM.Helpers;
-using Microsoft.Azure.Documents;
-using Microsoft.Extensions.Configuration;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using TEAMModelOS.SDK;
-using TEAMModelOS.SDK.DI;
-using TEAMModelOS.SDK.Extension;
-using TEAMModelOS.SDK.Models;
-using TEAMModelOS.SDK.Models.Cosmos.Common;
-
-namespace TEAMModelFunction
-{
-    public static class TriggerStudy
-    {
-        public static async Task Trigger(AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
-                    CosmosClient client, Document input, TriggerData tdata, AzureRedisFactory _azureRedis, IConfiguration _configuration)
-        {
-            try
-            {
-                if ((tdata.status != null && tdata.status.Value == 404) || tdata.ttl > 0 || tdata.publish == 1)
-                {
-                    return;
-                }
-                var adid = tdata.id;
-                var adcode = "";
-                string blobcntr = null;
-                if (tdata.scope.Equals("school"))
-                {
-                    adcode = $"Activity-{tdata.school}";
-                    blobcntr = tdata.school;
-                }
-                else
-                {
-                    adcode = $"Activity-{tdata.creatorId}";
-                    blobcntr = tdata.creatorId;
-                }
-              
-                Study study = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Study>(input.Id, new Azure.Cosmos.PartitionKey($"{tdata.code}"));
-                
-                if (study != null)
-                {
-                    string PartitionKey = string.Format("{0}{1}{2}", study.code, "-", study.progress);
-                    List<ChangeRecord> changeRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", PartitionKey } });
-                    switch (study.progress)
-                    {
-                        case "pending":
-                            var messageWork = new ServiceBusMessage(new { id = input.Id, progress = "going", code = tdata.code }.ToJsonString());
-                            messageWork.ApplicationProperties.Add("name", "Study");
-                            if (changeRecords.Count > 0)
-                            {
-                                await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), changeRecords[0].sequenceNumber);
-                                long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWork, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
-                                changeRecords[0].sequenceNumber = start;
-                                await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
-                            }
-                            else
-                            {
-                                long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWork, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
-                                ChangeRecord changeRecord = new ChangeRecord
-                                {
-                                    RowKey = input.Id,
-                                    PartitionKey = PartitionKey,
-                                    sequenceNumber = start,
-                                    msgId = messageWork.MessageId
-                                };
-                                await _azureStorage.Save<ChangeRecord>(changeRecord);
-                            }
-                            break;
-                        case "going":
-                            try {
-                                List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
-                                if (study.groupLists.Count > 0)
-                                {
-                                    var group = study.groupLists;
-                                    foreach (var gp in group)
-                                    {
-                                        foreach (KeyValuePair<string, List<string>> pp in gp)
-                                        {
-                                            ps.Add((pp.Key, pp.Value));
-                                        }
-                                    }
-                                }
-                                (List<RMember> tchList, List<RGroupList> classInfos) = await GroupListService.GetStutmdidListids(client, _dingDing, study.tchLists, study.school, ps);
-                                List<StuActivity> tchActivities = new List<StuActivity>();
-                                (string standard, List<string> tmdids, string school, List<string> update, int statistics) list = (null, null, null, new List<string> { StatisticsService.OfflineRecord }, 0);
-                                if (tchList.IsNotEmpty())
-                                {
-                                    list.tmdids = tchList.Select(x => x.id).ToList();
-                                    School school = null;
-                                    if (!string.IsNullOrEmpty(study.school))
-                                    {
-                                        school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(study.school, new Azure.Cosmos.PartitionKey("Base"));
-                                        list.school = school.id;
-                                        list.standard = school.standard;
-                                    }
-                                    tchList.ForEach(x =>
-                                    {
-                                        tchActivities.Add(new StuActivity
-                                        {
-                                            pk = "Activity",
-                                            id = study.id,
-                                            code = $"Activity-{x.id}",
-                                            type = "Study",
-                                            name = study.name,
-                                            startTime = study.startTime,
-                                            endTime = study.endTime,
-                                            scode = study.code,
-                                            scope = study.scope,
-                                            school = study.school,
-                                            creatorId = study.creatorId,
-                                            subjects = new List<string> { "" },
-                                            blob = null,
-                                            owner = study.owner,
-                                            createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
-                                            taskStatus = -1,
-                                            classIds = study.tchLists
-                                        });
-                                    });
-
-                                }
-
-                                await ActivityService.SaveStuActivity(client, _dingDing, null, null, tchActivities);
-                                await StatisticsService.SendServiceBus(list, _configuration, _serviceBus,client);
-                                var messageWorkEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = tdata.code }.ToJsonString());
-                                messageWorkEnd.ApplicationProperties.Add("name", "Study");
-                                if (changeRecords.Count > 0)
-                                {
-                                    long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWorkEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
-                                    await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), changeRecords[0].sequenceNumber);
-                                    changeRecords[0].sequenceNumber = end;
-                                    await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
-                                }
-                                else
-                                {
-                                    long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWorkEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
-                                    ChangeRecord changeRecord = new ChangeRecord
-                                    {
-                                        RowKey = input.Id,
-                                        PartitionKey = PartitionKey,
-                                        sequenceNumber = end,
-                                        msgId = messageWorkEnd.MessageId
-                                    };
-                                    await _azureStorage.Save<ChangeRecord>(changeRecord);
-                                }
-
-                            }
-                            catch (Exception ex) {
-                                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}研修活动异常-going {ex.Message}{ex.StackTrace}{tdata.ToJsonString()}{input}", GroupNames.成都开发測試群組);
-                            }
-                           
-                            break;
-                        case "finish":
-                            break;
-                    }
-                }
-
-            }
-            catch (CosmosException e)
-            {
-                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDB异常{e.Message}\n{e.Status}", GroupNames.成都开发測試群組);
-            }
-            catch (Exception ex)
-            {
-                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}研修活动异常{ex.Message}{ex.StackTrace}{tdata.ToJsonString()}{input}", GroupNames.成都开发測試群組);
-            }
-
-        }
-    }
-}

+ 0 - 398
TEAMModelFunction/TriggerSurvey.cs

@@ -1,398 +0,0 @@
-using Azure.Cosmos;
-using Azure.Messaging.ServiceBus;
-using Azure.Storage.Blobs.Models;
-using Azure.Storage.Sas;
-using Microsoft.Azure.Documents;
-using System;
-using System.Collections.Generic;
-using System.Net.Http;
-using System.Text;
-using System.Text.Json;
-using System.Threading.Tasks;
-using TEAMModelOS.SDK.DI;
-using TEAMModelOS.SDK.Extension;
-using TEAMModelOS.SDK;
-using TEAMModelOS.SDK.Models;
-using TEAMModelOS.SDK.Models.Cosmos;
-using TEAMModelOS.SDK.Models.Cosmos.Common;
-using TEAMModelOS.SDK.Models.Cosmos.Common.Inner;
-using TEAMModelOS.SDK.Module.AzureBlob.Configuration;
-using TEAMModelOS.SDK.Models.Service;
-using HTEXLib.COMM.Helpers;
-using Microsoft.Extensions.Configuration;
-using System.Linq;
-
-namespace TEAMModelFunction
-{
-    public class TriggerSurvey
-    {
-        public static async Task Trigger(AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
-               CosmosClient client, Document input, TriggerData tdata, AzureRedisFactory _azureRedis, IConfiguration _configuration)
-        {
-            try
-            {
-                if ((tdata.status != null && tdata.status.Value == 404) || tdata.ttl > 0)
-                {
-                    _azureRedis.GetRedisClient(8).KeyDelete($"Survey:Record:{tdata.id}");
-                    _azureRedis.GetRedisClient(8).KeyDelete($"Survey:Submit:{tdata.id}");
-                    return;
-                }
-                var adid = tdata.id;
-                var adcode = "";
-                string blobcntr = null;
-                if (tdata.scope.Equals("school"))
-                {
-                    adcode = $"Activity-{tdata.school}";
-                    blobcntr = tdata.school;
-                }
-                else
-                {
-                    adcode = $"Activity-{tdata.creatorId}";
-                    blobcntr = tdata.creatorId;
-                }
-                Survey survey = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Survey>(input.Id, new Azure.Cosmos.PartitionKey($"{tdata.code}"));
-
-                if (survey != null)
-                {
-                    string PartitionKey = string.Format("{0}{1}{2}", survey.code, "-", survey.progress);
-                    List<ChangeRecord> changeRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", PartitionKey } });
-                    switch (survey.progress)
-                    {
-                        case "pending":
-                            var messageSurvey = new ServiceBusMessage(new { id = input.Id, progress = "going", code = tdata.code }.ToJsonString());
-                            messageSurvey.ApplicationProperties.Add("name", "Survey");
-                            if (changeRecords.Count > 0)
-                            {
-                                await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), changeRecords[0].sequenceNumber);
-                                long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageSurvey, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
-                                changeRecords[0].sequenceNumber = start;
-                                await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
-                            }
-                            else
-                            {
-                                long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageSurvey, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
-                                ChangeRecord changeRecord = new ChangeRecord
-                                {
-                                    RowKey = input.Id,
-                                    PartitionKey = PartitionKey,
-                                    sequenceNumber = start,
-                                    msgId = messageSurvey.MessageId
-                                };
-                                await _azureStorage.Save<ChangeRecord>(changeRecord);
-                            }
-                            break;
-                        case "going":
-                            List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
-                            if (survey.groupLists.Count > 0)
-                            {
-                                var group = survey.groupLists;
-                                foreach (var gp in group)
-                                {
-                                    foreach (KeyValuePair<string, List<string>> pp in gp)
-                                    {
-                                        ps.Add((pp.Key, pp.Value));
-                                    }
-                                }
-                            }
-                            List<string> classes = ExamService.getClasses(survey.classes, survey.stuLists);
-                            (List<RMember> tmdIds, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(client, _dingDing, classes, survey.school);
-                            var addStudentsCls = tmdIds.FindAll(x => x.type == 2);
-                            var addTmdidsCls = tmdIds.FindAll(x => x.type == 1);
-#if DEBUG
-                            await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查{tdata.id}写入学生表作为活动列表!", GroupNames.成都开发測試群組);
-#endif
-                            List<StuActivity> stuActivities = new List<StuActivity>();
-                            List<StuActivity> tmdActivities = new List<StuActivity>();
-                            List<StuActivity> tchActivities = new List<StuActivity>();
-                            if (addTmdidsCls.IsNotEmpty())
-                            {
-                                addTmdidsCls.ForEach(x =>
-                                {
-                                    tmdActivities.Add(new StuActivity
-                                    {
-                                        pk = "Activity",
-                                        id = survey.id,
-                                        code = $"Activity-{x.id}",
-                                        type = "Survey",
-                                        name = survey.name,
-                                        startTime = survey.startTime,
-                                        endTime = survey.endTime,
-                                        scode = survey.code,
-                                        scope = survey.scope,
-                                        school = survey.school,
-                                        creatorId = survey.creatorId,
-                                        subjects = new List<string> { "" },
-                                        blob = survey.blob,
-                                        owner = survey.owner,
-                                        createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
-                                        taskStatus = -1,
-                                        classIds = classes
-                                    });
-                                });
-                            }
-                            if (addStudentsCls.IsNotEmpty())
-                            {
-                                addStudentsCls.ForEach(x =>
-                                {
-                                    stuActivities.Add(new StuActivity
-                                    {
-                                        pk = "Activity",
-                                        id = survey.id,
-                                        code = $"Activity-{x.code.Replace("Base-", "")}-{x.id}",
-                                        type = "Survey",
-                                        name = survey.name,
-                                        startTime = survey.startTime,
-                                        endTime = survey.endTime,
-                                        scode = survey.code,
-                                        scope = survey.scope,
-                                        school = survey.school,
-                                        creatorId = survey.creatorId,
-                                        subjects = new List<string> { "" },
-                                        blob = survey.blob,
-                                        owner = survey.owner,
-                                        createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
-                                        taskStatus = -1,
-                                        classIds = classes
-                                    });
-                                });
-                            }
-                            (List<RMember> tchList, List<RGroupList> classInfos) = await GroupListService.GetStutmdidListids(client, _dingDing, survey.tchLists, survey.school, ps);
-                            (string standard, List<string> tmdids, string school, List<string> update, int statistics) list = (null, null, null, new List<string> { StatisticsService.TeacherSurvey }, 0);
-                            if (tchList.IsNotEmpty())
-                            {
-                                list.tmdids = tchList.Select(x => x.id).ToList();
-                                School school = null;
-                                if (!string.IsNullOrEmpty(survey.school))
-                                {
-                                    school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(survey.school, new Azure.Cosmos.PartitionKey("Base"));
-                                    list.school = school.id;
-                                    list.standard = school.standard;
-                                }
-                                tchList.ForEach(x =>
-                                {
-                                    tchActivities.Add(new StuActivity
-                                    {
-                                        pk = "Activity",
-                                        id = survey.id,
-                                        code = $"Activity-{x.id}",
-                                        type = "Survey",
-                                        name = survey.name,
-                                        startTime = survey.startTime,
-                                        endTime = survey.endTime,
-                                        scode = survey.code,
-                                        scope = survey.scope,
-                                        school = survey.school,
-                                        creatorId = survey.creatorId,
-                                        subjects = new List<string> { "" },
-                                        blob = survey.blob,
-                                        owner = survey.owner,
-                                        createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
-                                        taskStatus = -1,
-                                        classIds = survey.tchLists
-                                    });
-                                });
-
-                            }
-                            await ActivityService.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities, tchActivities);
-                            await StatisticsService.SendServiceBus(list, _configuration, _serviceBus, client);
-                            //向学生或醍摩豆账号发起通知
-                            #region
-                            //Notice notice = new Notice()
-                            //{
-                            //    creation = survey.startTime,
-                            //    expire = survey.endTime,
-                            //    creatorId = survey.creatorId,
-                            //    stuids = students,
-                            //    tmdids = tmdids,
-                            //    type = "notice",//问卷参加参加通知
-                            //    priority = "normal",
-                            //    //data = new { }.ToJsonString()
-                            //    msgId = survey.id,
-                            //    school = survey.school,
-                            //    scope = survey.scope,
-                            //    body = new Body { sid = survey.id, scode = survey.code, spk = survey.pk, biztype = "survey-join" }
-
-                            //};
-                            //var messageBlob = new ServiceBusMessage(notice.ToJsonString());
-                            //messageBlob.ApplicationProperties.Add("name", "Notice");
-                            //await _serviceBus.GetServiceBusClient().SendMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageBlob);
-                            #endregion
-#if DEBUG
-                            await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查{tdata.id}写入完成!", GroupNames.成都开发測試群組);
-#endif
-                            var messageSurveyEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = tdata.code }.ToJsonString());
-                            messageSurveyEnd.ApplicationProperties.Add("name", "Survey");
-                            if (changeRecords.Count > 0)
-                            {
-                                long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageSurveyEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
-                                await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), changeRecords[0].sequenceNumber);
-                                changeRecords[0].sequenceNumber = end;
-                                await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
-                            }
-                            else
-                            {
-                                long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageSurveyEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
-                                ChangeRecord changeRecord = new ChangeRecord
-                                {
-                                    RowKey = input.Id,
-                                    PartitionKey = PartitionKey,
-                                    sequenceNumber = end,
-                                    msgId = messageSurveyEnd.MessageId
-                                };
-                                await _azureStorage.Save<ChangeRecord>(changeRecord);
-                            }
-#if DEBUG
-                            await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查{tdata.id}将于:{tdata.etime}完成并结算!", GroupNames.成都开发測試群組);
-#endif
-                            break;
-                        case "finish":
-#if DEBUG
-                            await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查{tdata.id}开始结算{tdata.etime}!", GroupNames.成都开发測試群組);
-#endif
-                            var records = await _azureRedis.GetRedisClient(8).HashGetAllAsync($"Survey:Record:{survey.id}");
-                            var submits = await _azureRedis.GetRedisClient(8).SetMembersAsync($"Survey:Submit:{survey.id}");
-                            List<dynamic> recs = new List<dynamic>();
-                            foreach (var rcd in records)
-                            {
-                                var value = rcd.Value.ToString().ToObject<JsonElement>();
-                                recs.Add(new { index = rcd.Name.ToString(), ans = value });
-                            }
-
-                            List<dynamic> userids = new List<dynamic>();
-                            foreach (var submit in submits)
-                            {
-                                var value = submit.ToString();
-                                userids.Add(value);
-                            }
-
-                            List<QuestionRecord> questionRecords = new List<QuestionRecord>();
-                            //结算每道题的答题情况
-                            var ContainerClient = _azureStorage.GetBlobContainerClient(blobcntr);
-                            List<Task<string>> tasks = new List<Task<string>>();
-                            //获取
-                            List<SurveyRecord> surveyRecords = new List<SurveyRecord>();
-                            try
-                            {
-                                List<string> items = await ContainerClient.List($"survey/{survey.id}/urecord");
-
-                                foreach (string item in items)
-                                {
-                                    var Download = await _azureStorage.GetBlobContainerClient(blobcntr).GetBlobClient(item).DownloadAsync();
-                                    var json = await JsonDocument.ParseAsync(Download.Value.Content);
-                                    var Record = json.RootElement.ToObject<SurveyRecord>();
-                                    surveyRecords.Add(Record);
-                                }
-#if DEBUG
-                                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查问题结算数据{surveyRecords.ToJsonString()}", GroupNames.成都开发測試群組);
-#endif
-                                for (int index = 0; index < survey.answers.Count; index++)
-                                {
-                                    string url = $"{survey.id}/qrecord/{index}.json";
-                                    QuestionRecord question = new QuestionRecord() { index = index };
-                                    foreach (SurveyRecord record in surveyRecords)
-                                    {
-                                        if (record.ans.Count == survey.answers.Count)
-                                        {
-                                            foreach (var an in record.ans[index])
-                                            {
-                                                //
-                                                if (question.opt.ContainsKey(an))
-                                                {
-                                                    if (question.opt[an] != null)
-                                                    {
-                                                        question.opt[an].Add(record.userid);
-                                                    }
-                                                    else
-                                                    {
-                                                        question.opt[an] = new HashSet<string>() { record.userid };
-                                                    }
-                                                }
-                                                else
-                                                {
-                                                    if (survey.answers[index].Contains(an))
-                                                    {
-                                                        //如果是客观题code
-                                                        question.opt.Add(an, new HashSet<string> { record.userid });
-                                                    }
-                                                    else
-                                                    {
-                                                        //如果不是客观code
-                                                        question.other[record.userid] = an;
-                                                    }
-                                                }
-                                            }
-                                        }
-                                    }
-                                    questionRecords.Add(question);
-                                    tasks.Add(_azureStorage.UploadFileByContainer(blobcntr, question.ToJsonString(), "survey", url));
-                                }
-                                await Task.WhenAll(tasks);
-                            }
-                            catch (Exception ex)
-                            {
-                                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查问题结算异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
-                            }
-                            var cods = new { records = recs, userids, question = questionRecords, urecord = surveyRecords };
-                            //问卷整体情况
-                            await _azureStorage.UploadFileByContainer(blobcntr, cods.ToJsonString(), "survey", $"{survey.id}/record.json");
-                            if (string.IsNullOrEmpty(survey.recordUrl))
-                            {
-                                survey.recordUrl = $"/survey/{survey.id}/record.json";
-                                await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<Survey>(survey, survey.id, new Azure.Cosmos.PartitionKey(survey.code));
-                            }
-                            else
-                            {
-                                _azureRedis.GetRedisClient(8).KeyDelete($"Survey:Record:{survey.id}");
-                                _azureRedis.GetRedisClient(8).KeyDelete($"Survey:Submit:{survey.id}");
-                                break;
-                            }
-
-                            //更新结束状态
-                            //data.progress = "finish";
-                            //if (survey.scope .Equals("school"))
-                            //{
-                            //    await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<ActivityData>(data, data.id, new Azure.Cosmos.PartitionKey(data.code));
-                            //}
-                            //else if (survey.scope .Equals("private"))
-                            //{
-                            //    await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<ActivityData>(data, data.id, new Azure.Cosmos.PartitionKey(data.code));
-                            //}
-
-                            break;
-                    }
-                }
-            }
-
-            catch (CosmosException e)
-            {
-                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDB异常{e.Message}\n{e.Status}", GroupNames.成都开发測試群組);
-            }
-            catch (Exception ex)
-            {
-                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
-
-            }
-        }
-    }
-    /**
-     * {survey.id}/qrecord/{index}.json
-        {
-            "opt": {
-                "A": [
-                    "userid1",
-                    "userid2",
-                    "userid3"
-                ],
-                "B": [
-                    "userid1",
-                    "userid2",
-                    "userid3"
-                ]
-            },
-            "other": {
-                "userid1": "建议XXXX1",
-                "userid2": "建议XXXX2"
-            }
-        }
-     **/
-}

+ 0 - 318
TEAMModelFunction/TriggerVote.cs

@@ -1,318 +0,0 @@
-using Azure.Cosmos;
-using Azure.Messaging.ServiceBus;
-using Microsoft.Azure.Documents;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Text.Json;
-using System.Threading.Tasks;
-using TEAMModelOS.SDK.DI;
-using TEAMModelOS.SDK.Extension;
-using TEAMModelOS.SDK;
-using TEAMModelOS.SDK.Models;
-using TEAMModelOS.SDK.Models.Cosmos;
-using TEAMModelOS.SDK.Models.Cosmos.Common;
-using TEAMModelOS.SDK.Models.Cosmos.Common.Inner;
-using TEAMModelOS.SDK.Models.Service;
-using HTEXLib.COMM.Helpers;
-using Microsoft.Extensions.Configuration;
-
-namespace TEAMModelFunction
-{
-    public static class TriggerVote
-    {
-
-        public static async Task Trigger(AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
-            CosmosClient client, Document input, TriggerData tdata, AzureRedisFactory _azureRedis, IConfiguration _configuration)
-        {
-            try
-            {
-                if ((tdata.status != null && tdata.status.Value == 404) || tdata.ttl > 0)
-                {
-                    //异动,且已经有结算记录则不必再继续。
-                    _azureRedis.GetRedisClient(8).KeyDelete($"Vote:Record:{tdata.id}");
-                    _azureRedis.GetRedisClient(8).KeyDelete($"Vote:Count:{tdata.id}");
-                    return;
-                }
-                var adid = tdata.id;
-                var adcode = "";
-                string blobcntr = null;
-                if (tdata.scope.Equals("school"))
-                {
-                    adcode = $"Activity-{tdata.school}";
-                    blobcntr = tdata.school;
-                }
-                else
-                {
-                    adcode = $"Activity-{tdata.creatorId}";
-                    blobcntr = tdata.creatorId;
-                }
-                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}投票活动【{tdata.name}-{tdata.id}-ttl={tdata.ttl}】正在操作", GroupNames.成都开发測試群組);
-                Vote vote = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Vote>(input.Id, new Azure.Cosmos.PartitionKey($"{tdata.code}"));
-
-                if (vote != null)
-                {
-                    string PartitionKey = string.Format("{0}{1}{2}", vote.code, "-", vote.progress);
-                    List<ChangeRecord> voteRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", PartitionKey } });
-                    switch (vote.progress)
-                    {
-                        case "pending":
-                            var messageVote = new ServiceBusMessage(new { id = input.Id, progress = "going", code = tdata.code }.ToJsonString());
-                            messageVote.ApplicationProperties.Add("name", "Vote");
-                            if (voteRecords.Count > 0)
-                            {
-                                long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVote, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
-                                await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), voteRecords[0].sequenceNumber);
-                                voteRecords[0].sequenceNumber = start;
-                                await _azureStorage.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
-                            }
-                            else
-                            {
-                                long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVote, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
-                                ChangeRecord changeRecord = new ChangeRecord
-                                {
-                                    RowKey = input.Id,
-                                    PartitionKey = PartitionKey,
-                                    sequenceNumber = start,
-                                    msgId = messageVote.MessageId
-                                };
-                                await _azureStorage.Save<ChangeRecord>(changeRecord);
-                            }
-                            break;
-                        case "going":
-                            List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
-                            if (vote.groupLists.Count > 0)
-                            {
-                                var group = vote.groupLists;
-                                foreach (var keys in group)
-                                {
-                                    foreach (KeyValuePair<string, List<string>> pp in keys)
-                                    {
-                                        ps.Add((pp.Key, pp.Value));
-                                    }
-                                }
-                            }
-                            List<string> classes = ExamService.getClasses(vote.classes, vote.stuLists);
-                            (List<RMember> tmdIds, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(client, _dingDing, classes, vote.school, ps);
-                            var addStudentsCls = tmdIds.FindAll(x => x.type == 2);
-                            var addTmdidsCls = tmdIds.FindAll(x => x.type == 1);
-                            //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 (addTmdidsCls.IsNotEmpty())
-                            {
-                                tmds.AddRange(addTmdidsCls.Select(x => x.id).ToList());
-                            }
-                            List<StuActivity> stuActivities = new List<StuActivity>();
-                            List<StuActivity> tmdActivities = new List<StuActivity>();
-                            List<StuActivity> tchActivities = new List<StuActivity>();
-                            if (tmds.IsNotEmpty())
-                            {
-                                tmds.ForEach(x =>
-                                {
-                                    tmdActivities.Add(new StuActivity
-                                    {
-                                        pk = "Activity",
-                                        id = vote.id,
-                                        code = $"Activity-{x}",
-                                        type = "Vote",
-                                        name = vote.name,
-                                        startTime = vote.startTime,
-                                        endTime = vote.endTime,
-                                        scode = vote.code,
-                                        scope = vote.scope,
-                                        school = vote.school,
-                                        creatorId = vote.creatorId,
-                                        subjects = new List<string> { "" },
-                                        blob = null,
-                                        owner = vote.owner,
-                                        createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
-                                        taskStatus = -1,
-                                        classIds = classes
-                                    });
-                                });
-                            }
-                            if (addStudentsCls.IsNotEmpty())
-                            {
-                                addStudentsCls.ForEach(x =>
-                                {
-                                    stuActivities.Add(new StuActivity
-                                    {
-                                        pk = "Activity",
-                                        id = vote.id,
-                                        code = $"Activity-{x.code.Replace("Base-", "")}-{x.id}",
-                                        type = "Vote",
-                                        name = vote.name,
-                                        startTime = vote.startTime,
-                                        endTime = vote.endTime,
-                                        scode = vote.code,
-                                        scope = vote.scope,
-                                        school = vote.school,
-                                        creatorId = vote.creatorId,
-                                        subjects = new List<string> { "" },
-                                        blob = null,
-                                        owner = vote.owner,
-                                        createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
-                                        taskStatus = -1,
-                                        classIds = classes
-                                    });
-                                });
-                            }
-                            (List<RMember> tchList, List<RGroupList> classInfos) = await GroupListService.GetStutmdidListids(client, _dingDing, vote.tchLists, vote.school, ps);
-                            (string standard, List<string> tmdids, string school, List<string> update, int statistics) list = (null, null, null, new List<string> { StatisticsService.TeacherVote }, 0);
-                            if (tchList.IsNotEmpty())
-                            {
-                                list.tmdids = tchList.Select(x => x.id).ToList();
-                                School school = null;
-                                if (!string.IsNullOrEmpty(vote.school))
-                                {
-                                    school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(vote.school, new Azure.Cosmos.PartitionKey("Base"));
-                                    list.school = school.id;
-                                    list.standard = school.standard;
-                                }
-                                tchList.ForEach(x =>
-                                {
-                                    tchActivities.Add(new StuActivity
-                                    {
-                                        pk = "Activity",
-                                        id = vote.id,
-                                        code = $"Activity-{x.id}",
-                                        type = "Vote",
-                                        name = vote.name,
-                                        startTime = vote.startTime,
-                                        endTime = vote.endTime,
-                                        scode = vote.code,
-                                        scope = vote.scope,
-                                        school = vote.school,
-                                        creatorId = vote.creatorId,
-                                        subjects = new List<string> { "" },
-                                        blob = null,
-                                        owner = vote.owner,
-                                        createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
-                                        taskStatus = -1,
-                                        classIds = classes
-                                    });
-                                });
-
-                            }
-                            //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}投票活动,:教研组活动:" +
-
-                            //   $"{tchActivities.ToJsonString()}\n", GroupNames.成都开发測試群組);
-                            await ActivityService.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities, tchActivities);
-                            await StatisticsService.SendServiceBus(list, _configuration, _serviceBus, client);
-                            //向学生或醍摩豆账号发起通知
-                            #region
-                            //Notice notice = new Notice()
-                            //{
-
-                            //    creation = vote.startTime,
-                            //    expire = vote.endTime,
-                            //    creatorId = vote.creatorId,
-                            //    stuids = students,
-                            //    tmdids = tmdids,
-                            //    type = "notice",//问卷参加参加通知
-                            //    priority = "normal",
-                            //    msgId=vote.id,
-                            //    school = vote.school,
-                            //    scope = vote.scope,
-                            //    //data = new { }.ToJsonString()
-                            //    body = new Body { sid = vote.id, scode = vote.code, spk = vote.pk,  biztype = "vote-join" }
-
-                            //};
-
-                            //var messageBlob = new ServiceBusMessage(notice.ToJsonString());
-                            //messageBlob.ApplicationProperties.Add("name", "Notice");
-                            //await _serviceBus.GetServiceBusClient().SendMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:NoticeTask"), messageBlob);
-                            #endregion
-                            var messageVoteEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = tdata.code }.ToJsonString());
-                            messageVoteEnd.ApplicationProperties.Add("name", "Vote");
-                            if (voteRecords.Count > 0)
-                            {
-                                long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
-                                await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), voteRecords[0].sequenceNumber);
-                                voteRecords[0].sequenceNumber = end;
-                                await _azureStorage.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
-                            }
-                            else
-                            {
-                                long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
-                                ChangeRecord changeRecord = new ChangeRecord
-                                {
-                                    RowKey = input.Id,
-                                    PartitionKey = PartitionKey,
-                                    sequenceNumber = end,
-                                    msgId = messageVoteEnd.MessageId
-                                };
-                                await _azureStorage.Save<ChangeRecord>(changeRecord);
-                            }
-#if DEBUG
-                            await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}投票活动{tdata.id}将于:{tdata.etime}完成并结算!", GroupNames.成都开发測試群組);
-#endif
-                            break;
-                        case "finish":
-#if DEBUG
-                            await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}投票活动{tdata.id}开始结算{tdata.etime}!", GroupNames.成都开发測試群組);
-#endif
-                            //获取投票活动的所有投票记录
-                            var records = await _azureRedis.GetRedisClient(8).HashGetAllAsync($"Vote:Record:{vote.id}");
-                            //获取投票活动的选项及投票数
-                            var counts = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Vote:Count:{vote.id}");
-                            List<dynamic> countcds = new List<dynamic>();
-                            if (counts != null && counts.Length > 0)
-                            {
-                                foreach (var count in counts)
-                                {
-                                    countcds.Add(new { code = count.Element.ToString(), count = (int)count.Score });
-                                }
-                            }
-                            List<Task<string>> tasks = new List<Task<string>>();
-                            List<VoteRecord> recordsBlob = new List<VoteRecord>();
-                            foreach (var rcd in records)
-                            {
-                                var value = rcd.Value.ToString().ToObject<VoteRecord>();
-                                recordsBlob.Add(value);
-                            }
-                            //分组每个人的 
-                            var gp = recordsBlob.GroupBy(x => x.userid).Select(x => new { key = x.Key, list = x.ToList() });
-                            foreach (var g in gp)
-                            {
-                                tasks.Add(_azureStorage.UploadFileByContainer(blobcntr, g.list.ToJsonString(), "vote", $"{vote.id}/urecord/{g.key}.json"));
-                            }
-                            //处理活动方的记录, 
-                            string url = $"/vote/{vote.id}/record.json";
-                            tasks.Add(_azureStorage.UploadFileByContainer(blobcntr, new { options = countcds, records = recordsBlob }.ToJsonString(), "vote", $"{vote.id}/record.json"));
-                            //处理投票者的记录
-
-                            if (string.IsNullOrEmpty(vote.recordUrl))
-                            {
-                                vote.recordUrl = url;
-                                await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync<Vote>(vote, vote.id, new Azure.Cosmos.PartitionKey(vote.code));
-                            }
-                            else
-                            {
-                                //异动,且已经有结算记录则不必再继续。
-                                _azureRedis.GetRedisClient(8).KeyDelete($"Vote:Record:{vote.id}");
-                                _azureRedis.GetRedisClient(8).KeyDelete($"Vote:Count:{vote.id}");
-                                break;
-                            }
-                            await Task.WhenAll(tasks);
-                            break;
-                    }
-                }
-            }
-            catch (CosmosException e)
-            {
-                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDB异常{e.Message}\n{e.Status}", GroupNames.成都开发測試群組);
-            }
-            catch (Exception ex)
-            {
-                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}投票活动异常{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
-            }
-
-        }
-    }
-}

+ 0 - 19
TEAMModelFunction/host.json

@@ -1,19 +0,0 @@
-{
-  "version": "2.0",
-  "cosmosDB": {
-    "connectionMode": "Direct",
-    "protocol": "Tcp"
-  },
-  "logging": {
-    "console": {
-      "isEnabled": "true"
-    },
-    "applicationInsights": {
-      "samplingExcludedTypes": "Request",
-      "samplingSettings": {
-        "isEnabled": true,
-        "ExcludedTypes": "Request"
-      }
-    }
-  }
-}

+ 0 - 21
TEAMModelFunction/local.settings.json

@@ -1,21 +0,0 @@
-{
-  "IsEncrypted": false,
-  "Values": {
-    "AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=teammodellog;AccountKey=lxVDrgs+6rKtmASL3k1WrarrEd5Rk42wS1Mu5+sqQlPya1JLSlFDtnZUvMPeHHe7zlESfn/1NY7CZdGviy2UCw==;EndpointSuffix=core.chinacloudapi.cn",
-    "Azure:Storage:ConnectionString": "DefaultEndpointsProtocol=https;AccountName=teammodelstorage;AccountKey=Yq7D4dE6cFuer2d2UZIccTA/i0c3sJ/6ITc8tNOyW+K5f+/lWw9GCos3Mxhj47PyWQgDL8YbVD63B9XcGtrMxQ==;EndpointSuffix=core.chinacloudapi.cn",
-    "Azure:ServiceBus:ConnectionString": "Endpoint=sb://teammodelos.servicebus.chinacloudapi.cn/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=Sy4h4EQ8zP+7w/lOLi1X3tGord/7ShFHimHs1vC50Dc=",
-    //"Azure:Cosmos:ConnectionString": "AccountEndpoint=https://teammodelos.documents.azure.cn:443/;AccountKey=clF73GwPECfP1lKZTCvs8gLMMyCZig1HODFbhDUsarsAURO7TcOjVz6ZFfPqr1HzYrfjCXpMuVD5TlEG5bFGGg==;",
-    //"Azure:Redis:ConnectionString": "CoreRedisCN.redis.cache.chinacloudapi.cn:6380,password=LyJWP1ORJdv+poXWofAF97lhCEQPg1wXWqvtzXGXQuE=,ssl=True,abortConnect=False",
-    //"Azure:ServiceBus:ActiveTask": "active-task",
-    //"Azure:ServiceBus:NoticeTask": "notice-task",
-    "Azure:Cosmos:ConnectionString": "AccountEndpoint=https://cdhabookdep-free.documents.azure.cn:443/;AccountKey=JTUVk92Gjsx17L0xqxn0X4wX2thDPMKiw4daeTyV1HzPb6JmBeHdtFY1MF1jdctW1ofgzqkDMFOtcqS46by31A==;",
-    "Azure:Redis:ConnectionString": "106.12.23.251:6379,password=habook,ssl=false,abortConnect=False,writeBuffer=10240",
-    "Azure:ServiceBus:ActiveTask": "dep-active-task",
-    "Azure:ServiceBus:ItemCondQueue": "dep-itemcond",
-    "Option:Location": "China-Dep",
-    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
-    "HaBookAuth:CoreService:sendnotification": "https://api2.teammodel.net/service/sendnotification",
-    "HaBookAuth:CoreService:clientID": "c7317f88-7cea-4e48-ac57-a16071f7b884",
-    "HaBookAuth:CoreService:clientSecret": "kguxh:V.PLmxBdaI@jnrTrDSth]A3346"
-  }
-}

+ 0 - 35
TEAMModelGrpc/Dockerfile

@@ -1,35 +0,0 @@
-#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.
-
-FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base
-WORKDIR /app
-EXPOSE 80
-EXPOSE 443
-EXPOSE 5000
-
-FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
-WORKDIR /app
-RUN dotnet dev-certs https --clean
-RUN dotnet dev-certs https -ep TEAMModelGrpc/habook.pfx  -p habook
-#RUN dotnet dev-certs https --trust
-COPY ["TEAMModelGrpc/habook.pfx", "/app"]
-
-WORKDIR /src
-COPY ["TEAMModelGrpc/habook.pfx", "TEAMModelGrpc/"]
-COPY ["TEAMModelGrpc/nuget.config", "TEAMModelGrpc/"]
-COPY ["TEAMModelGrpc/Protos", "TEAMModelGrpc/"]
-COPY ["TEAMModelGrpc/TEAMModelGrpc.csproj", "TEAMModelGrpc/"]
-COPY ["TEAMModelOS.SDK/TEAMModelOS.SDK.csproj", "TEAMModelOS.SDK/"]
-COPY ["TEAMModelOS.Service/TEAMModelOS.Service.csproj", "TEAMModelOS.Service/"]
-RUN dotnet restore "TEAMModelGrpc/TEAMModelGrpc.csproj" --configfile "TEAMModelGrpc/nuget.config"
-COPY . .
-WORKDIR "/src/TEAMModelGrpc"
-RUN dotnet build "TEAMModelGrpc.csproj" -c Release -o /app/build
-
-FROM build AS publish
-RUN dotnet publish "TEAMModelGrpc.csproj" -c Release -o /app/publish
-COPY ["TEAMModelGrpc/habook.pfx", "/app/publish"]
-
-FROM base AS final
-WORKDIR /app
-COPY --from=publish /app/publish .
-ENTRYPOINT ["dotnet", "TEAMModelGrpc.dll"]

+ 0 - 46
TEAMModelGrpc/GrpcHealthCheck/GrpcHealthChecksEndpointRouteBuilderExtensions.cs

@@ -1,46 +0,0 @@
-#region Copyright notice and license
-
-// Copyright 2019 The gRPC Authors
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//     http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#endregion
-
-using System;
-using Grpc.HealthCheck;
-using Microsoft.AspNetCore.Routing;
-
-namespace Microsoft.AspNetCore.Builder
-{
-    /// <summary>
-    /// Provides extension methods for <see cref="IEndpointRouteBuilder"/> to add gRPC service endpoints.
-    /// </summary>
-    public static class GrpcHealthChecksEndpointRouteBuilderExtensions
-    {
-        /// <summary>
-        /// Maps incoming requests to the gRPC health checks service.
-        /// This service can be queried to discover the health of the server.
-        /// </summary>
-        /// <param name="builder">The <see cref="IEndpointRouteBuilder"/> to add the route to.</param>
-        /// <returns>An <see cref="GrpcServiceEndpointConventionBuilder"/> for endpoints associated with the service.</returns>
-        public static GrpcServiceEndpointConventionBuilder MapGrpcHealthChecksService(this IEndpointRouteBuilder builder)
-        {
-            if (builder == null)
-            {
-                throw new ArgumentNullException(nameof(builder));
-            }
-
-            return builder.MapGrpcService<HealthServiceImpl>();
-        }
-    }
-}

+ 0 - 56
TEAMModelGrpc/GrpcHealthCheck/GrpcHealthChecksPublisher.cs

@@ -1,56 +0,0 @@
-#region Copyright notice and license
-
-// Copyright 2019 The gRPC Authors
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//     http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#endregion
-
-using System.Threading;
-using System.Threading.Tasks;
-using Grpc.Health.V1;
-using Grpc.HealthCheck;
-using Microsoft.Extensions.Diagnostics.HealthChecks;
-
-namespace Grpc.AspNetCore.HealthChecks
-{
-    internal class GrpcHealthChecksPublisher : IHealthCheckPublisher
-    {
-        private readonly HealthServiceImpl _healthService;
-
-        public GrpcHealthChecksPublisher(HealthServiceImpl healthService)
-        {
-            _healthService = healthService;
-        }
-
-        public Task PublishAsync(HealthReport report, CancellationToken cancellationToken)
-        {
-            foreach (var entry in report.Entries)
-            {
-                var status = entry.Value.Status;
-
-                _healthService.SetStatus(entry.Key, ResolveStatus(status));
-            }
-
-            return Task.CompletedTask;
-        }
-
-        private static HealthCheckResponse.Types.ServingStatus ResolveStatus(HealthStatus status)
-        {
-            return status == HealthStatus.Unhealthy
-                ? HealthCheckResponse.Types.ServingStatus.NotServing
-                : HealthCheckResponse.Types.ServingStatus.Serving;
-        }
-    }
-
-}

+ 0 - 52
TEAMModelGrpc/GrpcHealthCheck/GrpcHealthChecksServiceExtensions.cs

@@ -1,52 +0,0 @@
-#region Copyright notice and license
-
-// Copyright 2019 The gRPC Authors
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//     http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#endregion
-
-using System;
-using Grpc.AspNetCore.HealthChecks;
-using Grpc.HealthCheck;
-using Microsoft.Extensions.DependencyInjection.Extensions;
-using Microsoft.Extensions.Diagnostics.HealthChecks;
-
-namespace Microsoft.Extensions.DependencyInjection
-{
-    /// <summary>
-    /// Extension methods for the gRPC health checks services.
-    /// </summary>
-    public static class GrpcHealthChecksServiceExtensions
-    {
-        /// <summary>
-        /// Adds gRPC health check services to the specified <see cref="IServiceCollection" />.
-        /// </summary>
-        /// <param name="services">The <see cref="IServiceCollection"/> for adding services.</param>
-        /// <returns>An instance of <see cref="IHealthChecksBuilder"/> from which health checks can be registered.</returns>
-        public static IHealthChecksBuilder AddGrpcHealthChecks(this IServiceCollection services)
-        {
-            if (services == null)
-            {
-                throw new ArgumentNullException(nameof(services));
-            }
-
-            // HealthServiceImpl is designed to be a singleton
-            services.TryAddSingleton<HealthServiceImpl>();
-
-            services.TryAddEnumerable(ServiceDescriptor.Singleton<IHealthCheckPublisher, GrpcHealthChecksPublisher>());
-
-            return services.AddHealthChecks();
-        }
-    }
-}

+ 0 - 52
TEAMModelGrpc/Program.cs

@@ -1,52 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Hosting;
-using Microsoft.Extensions.Configuration;
-using Microsoft.Extensions.Hosting;
-
-namespace TEAMModelGrpc
-{
-    public class Program
-    {
-        public static void Main(string[] args)
-        {
-            CreateHostBuilder(args).Build().Run();
-        }
-
-        // Additional configuration is required to successfully run gRPC on macOS.
-        // For instructions on how to configure Kestrel and gRPC clients on macOS, visit https://go.microsoft.com/fwlink/?linkid=2099682
-        public static IHostBuilder CreateHostBuilder(string[] args) {
-            //var config = new ConfigurationBuilder()
-            //            .SetBasePath(Directory.GetCurrentDirectory())
-            //            .AddJsonFile("hostsettings.json", optional: true, reloadOnChange: true)//
-            //            .AddCommandLine(args)
-            //            .Build();
-            return Host.CreateDefaultBuilder(args)
-                    .ConfigureWebHostDefaults(webBuilder =>
-                    {
-                        //webBuilder.UseKestrel(option =>
-                        //{
-                        //    option.Listen(System.Net.IPAddress.Any, 5000, (lop) =>
-                        //    {
-                        //        lop.UseHttps("3518566__teammodel.cn.pfx", "cJNBFxFs");
-
-                        //        //参数为证书文件名称,证书密码
-                        //    });
-                        //});
-                        //webBuilder.UseConfiguration(config);
-                        //webBuilder.UseIISIntegration();
-                        //webBuilder.UseUrls("https://0.0.0.0:443");
-                        //可以不通过配置文件,通过UseUrls该方法指定一组url以分号分隔
-                        //webBuilder.UseKestrel(opt => {
-                        //    opt.ConfigureHttpsDefaults("teammodel.cn.pfx");
-                        //});
-                        webBuilder.UseStartup<Startup>();
-                    });
-        }
-
-           
-    }
-}

+ 0 - 17
TEAMModelGrpc/Properties/launchSettings.json

@@ -1,17 +0,0 @@
-{
-  "profiles": {
-    "TEAMModelGrpc": {
-      "commandName": "Project",
-      "environmentVariables": {
-        "ASPNETCORE_ENVIRONMENT": "Development"
-      },
-      "applicationUrl": "https://localhost:5001"
-    },
-    "Docker": {
-      "commandName": "Docker",
-      "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}",
-      "publishAllPorts": true,
-      "useSSL": true
-    }
-  }
-}

+ 0 - 26
TEAMModelGrpc/Protos/BlobSASService.proto

@@ -1,26 +0,0 @@
-syntax = "proto3";
-option csharp_namespace = "TMDGrpc.BlobSASService";
-option java_package = "TMDGrpc.BlobSASService";
-package TMDGrpc;
-
-
-service BlobSASService {
-   rpc GetContainerSasUri(Empty) returns(BlobSASDto);
-
-   rpc GetContainerSASRead(BlobSASDto) returns(BlobSASDto);
-
-}
-
-
-
-message Empty {
-}
-
-message BlobSASDto {
-   //Blob的URL地址
-   string Url = 1;
-   //容器名
-   string Container = 2;
-   //Blob的SAS签名
-   string SAS = 3;
-}

+ 0 - 162
TEAMModelGrpc/Protos/ClassroomService.proto

@@ -1,162 +0,0 @@
-syntax = "proto3";
-option csharp_namespace = "TMDGrpc.ClassroomService";
-option java_package = "TMDGrpc.ClassroomService";
-package TMDGrpc;
-
-
-service ClassroomService {
-   //保存教室
-   rpc SaveOrUpdateVolume(stream Classroom) returns(stream Classroom);
-
-   //查询教室
-   rpc FindVolume(Dict) returns(stream Classroom);
-
-   //删除教室
-   rpc Delete(ListPid) returns(ListPid);
-
-}
-
-
-
-message Classroom {
-   //classroomCode
-   string id = 1;
-   string scopeCode = 2;
-   string classroomCode = 3;
-   Point point = 4;
-   string classroomName = 5;
-   string headMaster = 6;
-   string periodCode = 7;
-   string gradeCode = 8;
-   string hiteach = 9;
-   int32 studentCount = 10;
-   string classroomType = 11;
-   int32 status = 12;
-}
-
-message Point {
-   float x = 1;
-   float y = 2;
-}
-
-//请求参数Dict
-message Dict {
-   //数字Dict
-   map<string,double> NMap = 1;
-   //字符串Dict
-   map<string,string> SMap = 2;
-   //布尔Dict
-   map<string,bool> BMap = 3;
-   //字符串ListMap
-   repeated LSMap LSMap = 4;
-   //数字ListMap
-   repeated LNMap LNMap = 5;
-   //Byte ListMap
-   repeated LBMap LBMap = 6;
-}
-
-//Byte[] Map
-message LBMap {
-   //Key
-   string Key = 1;
-   //byte数组
-   bytes Value = 2;
-}
-
-//数字ListMap
-message LNMap {
-   //Key
-   string Key = 1;
-   //数字数组
-   repeated double Value = 2 [packed = false];
-}
-
-//字符串ListMap
-message LSMap {
-   //数字Dict
-   string Key = 1;
-   //字符串数组
-   repeated string Value = 2;
-}
-
-enum HttpStatusCode {
-   option allow_alias = true;
-   ZERO = 0; // proto3 requires a zero value as the first item (it can be named anything)
-   Continue = 100;
-   SwitchingProtocols = 101;
-   Processing = 102;
-   EarlyHints = 103;
-   OK = 200;
-   Created = 201;
-   Accepted = 202;
-   NonAuthoritativeInformation = 203;
-   NoContent = 204;
-   ResetContent = 205;
-   PartialContent = 206;
-   MultiStatus = 207;
-   AlreadyReported = 208;
-   IMUsed = 226;
-   Ambiguous = 300;
-   MultipleChoices = 300;
-   MovedPermanently = 301;
-   Moved = 301;
-   Found = 302;
-   Redirect = 302;
-   SeeOther = 303;
-   RedirectMethod = 303;
-   NotModified = 304;
-   UseProxy = 305;
-   Unused = 306;
-   TemporaryRedirect = 307;
-   RedirectKeepVerb = 307;
-   PermanentRedirect = 308;
-   BadRequest = 400;
-   Unauthorized = 401;
-   PaymentRequired = 402;
-   Forbidden = 403;
-   NotFound = 404;
-   MethodNotAllowed = 405;
-   NotAcceptable = 406;
-   ProxyAuthenticationRequired = 407;
-   RequestTimeout = 408;
-   Conflict = 409;
-   Gone = 410;
-   LengthRequired = 411;
-   PreconditionFailed = 412;
-   RequestEntityTooLarge = 413;
-   RequestUriTooLong = 414;
-   UnsupportedMediaType = 415;
-   RequestedRangeNotSatisfiable = 416;
-   ExpectationFailed = 417;
-   MisdirectedRequest = 421;
-   UnprocessableEntity = 422;
-   Locked = 423;
-   FailedDependency = 424;
-   UpgradeRequired = 426;
-   PreconditionRequired = 428;
-   TooManyRequests = 429;
-   RequestHeaderFieldsTooLarge = 431;
-   UnavailableForLegalReasons = 451;
-   InternalServerError = 500;
-   NotImplemented = 501;
-   BadGateway = 502;
-   ServiceUnavailable = 503;
-   GatewayTimeout = 504;
-   HttpVersionNotSupported = 505;
-   VariantAlsoNegotiates = 506;
-   InsufficientStorage = 507;
-   LoopDetected = 508;
-   NotExtended = 510;
-   NetworkAuthenticationRequired = 511;
-}
-
-message IdPk {
-   string id = 1;
-   string pk = 2;
-   HttpStatusCode StatusCode = 3;
-}
-
-message ListPid {
-   //list IdPk
-   repeated IdPk idPks = 1;
-}

+ 0 - 33
TEAMModelGrpc/Protos/ClassroomStudentService.proto

@@ -1,33 +0,0 @@
-syntax = "proto3";
-option csharp_namespace = "TMDGrpc.ClassroomStudentService";
-option java_package = "TMDGrpc.ClassroomStudentService";
-package TMDGrpc;
-
-
-service ClassroomStudentService {
-   //保存 或 修改 教室学生关联
-   rpc SaveOrUpdateClassroomStudent(stream ClassroomStudent) returns(stream ClassroomStudent);
-
-   //学生加入教室 或者 修改座位号
-   rpc AddClassroomAsync(stream ClassroomStudent) returns(stream ClassroomStudent);
-
-   //学生退出教室
-   rpc DelClassroom(stream ClassroomStudent) returns(stream ClassroomStudent);
-
-   //查询学生在哪些教室
-   rpc FindStudents(StringDto) returns(stream ClassroomStudent);
-
-}
-
-
-
-message ClassroomStudent {
-   //classroomCode
-   string id = 1;
-   string scopeCode = 2;
-   repeated string studentId = 3;
-}
-
-message StringDto {
-   string name = 1;
-}

+ 0 - 189
TEAMModelGrpc/Protos/CourseService.proto

@@ -1,189 +0,0 @@
-syntax = "proto3";
-option csharp_namespace = "TMDGrpc.CourseService";
-option java_package = "TMDGrpc.CourseService";
-package TMDGrpc;
-
-
-service CourseService {
-   //查询课程
-   rpc FindCourseByDict(Dict) returns(stream Course);
-
-   //保存课程
-   rpc SaveCourse(stream Course) returns(stream Course);
-
-   //删除课程
-   rpc DeleteCourse(ListPid) returns(ListPid);
-
-}
-
-
-
-//请求参数Dict
-message Dict {
-   //数字Dict
-   map<string,double> NMap = 1;
-   //字符串Dict
-   map<string,string> SMap = 2;
-   //布尔Dict
-   map<string,bool> BMap = 3;
-   //字符串ListMap
-   repeated LSMap LSMap = 4;
-   //数字ListMap
-   repeated LNMap LNMap = 5;
-   //Byte ListMap
-   repeated LBMap LBMap = 6;
-}
-
-//Byte[] Map
-message LBMap {
-   //Key
-   string Key = 1;
-   //byte数组
-   bytes Value = 2;
-}
-
-//数字ListMap
-message LNMap {
-   //Key
-   string Key = 1;
-   //数字数组
-   repeated double Value = 2 [packed = false];
-}
-
-//字符串ListMap
-message LSMap {
-   //数字Dict
-   string Key = 1;
-   //字符串数组
-   repeated string Value = 2;
-}
-
-//基础信息
-message BaseInfo {
-   //课程编码
-   string courseCode = 1;
-   //课程名称
-   string courseName = 2;
-   //学段编码
-   string periodCode = 3;
-   //年级编码
-   string gradeCode = 4;
-   //学科编码
-   string subjectCode = 5;
-   //课程公告
-   string notice = 6;
-}
-
-//课程
-message Course {
-   //学校编码 如果是教师个人知识点 则为 personal(写死) 否则为学校编码
-   string scopeCode = 1;
-   //基础信息
-   BaseInfo baseInfo = 2;
-   //协同教师
-   repeated string assistTeacher = 3;
-   //上课时间表
-   repeated CourseTime courseTime = 4;
-   //课程“教室” Classroom
-   repeated string classroom = 5;
-   //关联课纲 SyllabusNode
-   repeated string syllabus = 6;
-   //id
-   string id = 7;
-}
-
-//上课时间表
-message CourseTime {
-   //上课频率 每日、每周、每月、临时课程
-   string frequencyCode = 1;
-   //课程开始时间
-   string beginTime = 2;
-   //课程结束时间
-   string endTime = 3;
-   //上课班级/教室
-   string classroomCode = 4;
-   //临时课程
-   repeated string frequencyName = 5;
-}
-
-enum HttpStatusCode {
-   option allow_alias = true;
-   ZERO = 0; // proto3 requires a zero value as the first item (it can be named anything)
-   Continue = 100;
-   SwitchingProtocols = 101;
-   Processing = 102;
-   EarlyHints = 103;
-   OK = 200;
-   Created = 201;
-   Accepted = 202;
-   NonAuthoritativeInformation = 203;
-   NoContent = 204;
-   ResetContent = 205;
-   PartialContent = 206;
-   MultiStatus = 207;
-   AlreadyReported = 208;
-   IMUsed = 226;
-   Ambiguous = 300;
-   MultipleChoices = 300;
-   MovedPermanently = 301;
-   Moved = 301;
-   Found = 302;
-   Redirect = 302;
-   SeeOther = 303;
-   RedirectMethod = 303;
-   NotModified = 304;
-   UseProxy = 305;
-   Unused = 306;
-   TemporaryRedirect = 307;
-   RedirectKeepVerb = 307;
-   PermanentRedirect = 308;
-   BadRequest = 400;
-   Unauthorized = 401;
-   PaymentRequired = 402;
-   Forbidden = 403;
-   NotFound = 404;
-   MethodNotAllowed = 405;
-   NotAcceptable = 406;
-   ProxyAuthenticationRequired = 407;
-   RequestTimeout = 408;
-   Conflict = 409;
-   Gone = 410;
-   LengthRequired = 411;
-   PreconditionFailed = 412;
-   RequestEntityTooLarge = 413;
-   RequestUriTooLong = 414;
-   UnsupportedMediaType = 415;
-   RequestedRangeNotSatisfiable = 416;
-   ExpectationFailed = 417;
-   MisdirectedRequest = 421;
-   UnprocessableEntity = 422;
-   Locked = 423;
-   FailedDependency = 424;
-   UpgradeRequired = 426;
-   PreconditionRequired = 428;
-   TooManyRequests = 429;
-   RequestHeaderFieldsTooLarge = 431;
-   UnavailableForLegalReasons = 451;
-   InternalServerError = 500;
-   NotImplemented = 501;
-   BadGateway = 502;
-   ServiceUnavailable = 503;
-   GatewayTimeout = 504;
-   HttpVersionNotSupported = 505;
-   VariantAlsoNegotiates = 506;
-   InsufficientStorage = 507;
-   LoopDetected = 508;
-   NotExtended = 510;
-   NetworkAuthenticationRequired = 511;
-}
-
-message IdPk {
-   string id = 1;
-   string pk = 2;
-   HttpStatusCode StatusCode = 3;
-}
-
-message ListPid {
-   //list IdPk
-   repeated IdPk idPks = 1;
-}

+ 0 - 194
TEAMModelGrpc/Protos/HomeWorkService.proto

@@ -1,194 +0,0 @@
-syntax = "proto3";
-option csharp_namespace = "TMDGrpc.HomeWorkService";
-option java_package = "TMDGrpc.HomeWorkService";
-package TMDGrpc;
-
-
-service HomeWorkService {
-   //学生作业打分评论
-   rpc StudentScoring(HomeWorkCommentDto) returns(HomeWorkStudent);
-
-   //教师作业打分评论
-   rpc TeacherScoring(HomeWorkScoringDto) returns(HomeWorkStudent);
-
-   //查询教师评语罐头
-   rpc FindTeacherComments(Dict) returns(stream TeacherComments);
-
-}
-
-
-
-message HomeWorkCommentDto {
-   string id = 1;
-   string homeWorkId = 2;
-   string commentid = 3;
-   string fromId = 4;
-   string toId = 5;
-   string identity = 6;
-   string comment = 7;
-   double score = 8;
-}
-
-message HomeWorkScoringDto {
-   string id = 1;
-   string homeWorkId = 2;
-   double score = 3;
-   string comments = 4;
-   string TEAMModelId = 5;
-   double start = 6;
-}
-
-//请求参数Dict
-message Dict {
-   //数字Dict
-   map<string,double> NMap = 1;
-   //字符串Dict
-   map<string,string> SMap = 2;
-   //布尔Dict
-   map<string,bool> BMap = 3;
-   //字符串ListMap
-   repeated LSMap LSMap = 4;
-   //数字ListMap
-   repeated LNMap LNMap = 5;
-   //Byte ListMap
-   repeated LBMap LBMap = 6;
-}
-
-//Byte[] Map
-message LBMap {
-   //Key
-   string Key = 1;
-   //byte数组
-   bytes Value = 2;
-}
-
-//数字ListMap
-message LNMap {
-   //Key
-   string Key = 1;
-   //数字数组
-   repeated double Value = 2 [packed = false];
-}
-
-//字符串ListMap
-message LSMap {
-   //数字Dict
-   string Key = 1;
-   //字符串数组
-   repeated string Value = 2;
-}
-
-message ClassroomItem {
-   string name = 1;
-   string code = 2;
-}
-
-//作业评论
-message HomeWorkComment {
-   //评论者身份 教师 学生
-   string identity = 1;
-   //评语
-   string comment = 2;
-   //评论时间
-   int64 createTime = 3;
-   //醍摩豆id 或者学生id
-   string TEAMModelId = 4;
-}
-
-//作业内容
-message HomeWorkContent {
-   //作答记录
-   string answers = 1;
-   //其他模式url 及name
-   repeated ProcessRes resource = 2;
-}
-
-//作业数据
-message HomeWorkStudent {
-   string id = 1;
-   string homeWorkId = 2;
-   //姓名
-   string name = 3;
-   //醍摩豆id
-   string TEAMModelId = 4;
-   //上课班级
-   ClassroomItem classroom = 5;
-   //原生班级
-   ClassroomItem nativeroom = 6;
-   //学号
-   string studentId = 7;
-   //是否提交
-   bool submissionBool = 8;
-   //提交时间
-   int64 submissionTime = 9;
-   //分数
-   double score = 10;
-   //作业内容
-   repeated HomeWorkContent content = 11;
-   //作业评论 (同学互评)
-   repeated StudentComment studentComments = 12;
-   //教师评语
-   HomeWorkComment teacherComments = 13;
-}
-
-//作业附件
-message ProcessRes {
-   //文件名字
-   string fileName = 1;
-   string blobUrl = 2;
-   int32 order = 3;
-   //文件大小
-   int64 size = 4;
-   //缩略图链接  图片视频有 文件没有
-   string compressUrl = 5;
-   //文件类型
-   string type = 6;
-   //唯一编码
-   string sha1Code = 7;
-}
-
-//评论回复
-message Reply {
-   //评论者id 醍摩豆或studenId
-   string fromId = 1;
-   //被评论者id 醍摩豆或studenId
-   string toId = 2;
-   //评论者身份 教师 学生
-   string identity = 3;
-   //评语
-   string comment = 4;
-   int64 createTime = 5;
-}
-
-message StudentComment {
-   //评论id
-   string commentid = 1;
-   //评论者id 醍摩豆或studenId
-   string fromId = 2;
-   //被评论者id 醍摩豆或studenId
-   string toId = 3;
-   //学生打分
-   double score = 4;
-   //评论者身份 教师 学生
-   string identity = 5;
-   //评语
-   string comment = 6;
-   //评论时间
-   int64 createTime = 7;
-   repeated Reply reply = 8;
-}
-
-message Comment {
-   string comment = 1;
-   int64 createTime = 2;
-   string id = 3;
-   int32 order = 4;
-}
-
-message TeacherComments {
-   string id = 1;
-   //评语
-   repeated Comment comment = 2;
-   //醍摩豆id 或者学生id
-   string TEAMModelId = 3;
-}

+ 0 - 167
TEAMModelGrpc/Protos/KnowledgeService.proto

@@ -1,167 +0,0 @@
-syntax = "proto3";
-option csharp_namespace = "TMDGrpc.KnowledgeService";
-option java_package = "TMDGrpc.KnowledgeService";
-package TMDGrpc;
-
-
-service KnowledgeService {
-   //查询知识点
-   rpc FinKnowledge(Dict) returns(stream Knowledge);
-
-   //保存知识点
-   rpc SaveKnowledge(stream Knowledge) returns(stream Knowledge);
-
-   //删除知识点
-   rpc DeleteKnowledge(ListPid) returns(ListPid);
-
-}
-
-
-
-//请求参数Dict
-message Dict {
-   //数字Dict
-   map<string,double> NMap = 1;
-   //字符串Dict
-   map<string,string> SMap = 2;
-   //布尔Dict
-   map<string,bool> BMap = 3;
-   //字符串ListMap
-   repeated LSMap LSMap = 4;
-   //数字ListMap
-   repeated LNMap LNMap = 5;
-   //Byte ListMap
-   repeated LBMap LBMap = 6;
-}
-
-//Byte[] Map
-message LBMap {
-   //Key
-   string Key = 1;
-   //byte数组
-   bytes Value = 2;
-}
-
-//数字ListMap
-message LNMap {
-   //Key
-   string Key = 1;
-   //数字数组
-   repeated double Value = 2 [packed = false];
-}
-
-//字符串ListMap
-message LSMap {
-   //数字Dict
-   string Key = 1;
-   //字符串数组
-   repeated string Value = 2;
-}
-
-//知识点
-message Knowledge {
-   string id = 1;
-   //标记为知识块,0=知识块 ,1 知识点
-   int32 type = 2;
-   //名称
-   string name = 3;
-   //描述
-   string alias = 4;
-   //学科
-   string subjectCode = 5;
-   //学校编码 如果是教师个人知识点为醍摩豆id 否则为学校编码
-   string scopeCode = 6;
-   int32 order = 7;
-   //删除状态0 删除 1 有效
-   int32 status = 8;
-   //知识点 id
-   repeated string points = 9;
-   //来自于标准表 Rowkey
-   string knowledgeId = 10;
-   //0 标准,1自建,2.....
-   int32 source = 11;
-   //学段 私有的没有学段
-   string period = 12;
-}
-
-enum HttpStatusCode {
-   option allow_alias = true;
-   ZERO = 0; // proto3 requires a zero value as the first item (it can be named anything)
-   Continue = 100;
-   SwitchingProtocols = 101;
-   Processing = 102;
-   EarlyHints = 103;
-   OK = 200;
-   Created = 201;
-   Accepted = 202;
-   NonAuthoritativeInformation = 203;
-   NoContent = 204;
-   ResetContent = 205;
-   PartialContent = 206;
-   MultiStatus = 207;
-   AlreadyReported = 208;
-   IMUsed = 226;
-   Ambiguous = 300;
-   MultipleChoices = 300;
-   MovedPermanently = 301;
-   Moved = 301;
-   Found = 302;
-   Redirect = 302;
-   SeeOther = 303;
-   RedirectMethod = 303;
-   NotModified = 304;
-   UseProxy = 305;
-   Unused = 306;
-   TemporaryRedirect = 307;
-   RedirectKeepVerb = 307;
-   PermanentRedirect = 308;
-   BadRequest = 400;
-   Unauthorized = 401;
-   PaymentRequired = 402;
-   Forbidden = 403;
-   NotFound = 404;
-   MethodNotAllowed = 405;
-   NotAcceptable = 406;
-   ProxyAuthenticationRequired = 407;
-   RequestTimeout = 408;
-   Conflict = 409;
-   Gone = 410;
-   LengthRequired = 411;
-   PreconditionFailed = 412;
-   RequestEntityTooLarge = 413;
-   RequestUriTooLong = 414;
-   UnsupportedMediaType = 415;
-   RequestedRangeNotSatisfiable = 416;
-   ExpectationFailed = 417;
-   MisdirectedRequest = 421;
-   UnprocessableEntity = 422;
-   Locked = 423;
-   FailedDependency = 424;
-   UpgradeRequired = 426;
-   PreconditionRequired = 428;
-   TooManyRequests = 429;
-   RequestHeaderFieldsTooLarge = 431;
-   UnavailableForLegalReasons = 451;
-   InternalServerError = 500;
-   NotImplemented = 501;
-   BadGateway = 502;
-   ServiceUnavailable = 503;
-   GatewayTimeout = 504;
-   HttpVersionNotSupported = 505;
-   VariantAlsoNegotiates = 506;
-   InsufficientStorage = 507;
-   LoopDetected = 508;
-   NotExtended = 510;
-   NetworkAuthenticationRequired = 511;
-}
-
-message IdPk {
-   string id = 1;
-   string pk = 2;
-   HttpStatusCode StatusCode = 3;
-}
-
-message ListPid {
-   //list IdPk
-   repeated IdPk idPks = 1;
-}

+ 0 - 124
TEAMModelGrpc/Protos/SyllabusService.proto

@@ -1,124 +0,0 @@
-syntax = "proto3";
-option csharp_namespace = "TMDGrpc.SyllabusService";
-option java_package = "TMDGrpc.SyllabusService";
-package TMDGrpc;
-
-
-service SyllabusService {
-   //查找课纲
-   rpc FindSyllabusTree(Dict) returns(stream SyllabusTreeDto);
-
-   //按节点新增课纲
-   rpc SaveOrUpdateAsNodes(stream SyllabusNode) returns(Response);
-
-   //按树形新增课纲结构
-   rpc SaveOrUpdateAsTree(stream SyllabusTreeDto) returns(stream SyllabusTreeDto);
-
-   //删除课纲
-   rpc DeleteSyllabus(Dict) returns(stream SyllabusTreeDto);
-
-}
-
-
-
-//请求参数Dict
-message Dict {
-   //数字Dict
-   map<string,double> NMap = 1;
-   //字符串Dict
-   map<string,string> SMap = 2;
-   //布尔Dict
-   map<string,bool> BMap = 3;
-   //字符串ListMap
-   repeated LSMap LSMap = 4;
-   //数字ListMap
-   repeated LNMap LNMap = 5;
-   //Byte ListMap
-   repeated LBMap LBMap = 6;
-}
-
-//Byte[] Map
-message LBMap {
-   //Key
-   string Key = 1;
-   //byte数组
-   bytes Value = 2;
-}
-
-//数字ListMap
-message LNMap {
-   //Key
-   string Key = 1;
-   //数字数组
-   repeated double Value = 2 [packed = false];
-}
-
-//字符串ListMap
-message LSMap {
-   //数字Dict
-   string Key = 1;
-   //字符串数组
-   repeated string Value = 2;
-}
-
-message SyllabusNode {
-   string id = 1;
-   //标题
-   string title = 2;
-   //是否展开
-   bool expand = 3;
-   //是否编辑
-   bool editable = 4;
-   //版本
-   string version = 5;
-   //排序
-   int32 order = 6;
-   //类型
-   int32 type = 7;
-   //节点Key
-   string nodeKey = 8;
-   //父级
-   string pid = 9;
-   //册别编码
-   string volumeCode = 10;
-   //数据状态
-   int32 status = 11;
-   repeated string resources = 12;
-   repeated string knowledges = 13;
-   bool resource = 14;
-   bool knowledge = 15;
-}
-
-message SyllabusTreeDto {
-   string id = 1;
-   //标题
-   string title = 2;
-   //是否展开
-   bool expand = 3;
-   //是否编辑
-   bool editable = 4;
-   //版本
-   string version = 5;
-   //排序
-   int32 order = 6;
-   //类型
-   int32 type = 7;
-   //节点Key
-   string nodeKey = 8;
-   //父级
-   string pid = 9;
-   //册别编码
-   string volumeCode = 10;
-   //数据状态
-   int32 status = 11;
-   repeated string resources = 12;
-   repeated string knowledges = 13;
-   bool resource = 14;
-   bool knowledge = 15;
-   repeated SyllabusTreeDto children = 16;
-}
-
-message Response {
-   string message = 1;
-   int32 code = 2;
-}

+ 0 - 168
TEAMModelGrpc/Protos/VolumeService.proto

@@ -1,168 +0,0 @@
-syntax = "proto3";
-option csharp_namespace = "TMDGrpc.VolumeService";
-option java_package = "TMDGrpc.VolumeService";
-package TMDGrpc;
-
-
-service VolumeService {
-   //保存册别
-   rpc SaveOrUpdateVolume(stream SyllabusVolume) returns(stream SyllabusVolume);
-
-   //查询册别
-   rpc FindVolume(Dict) returns(stream SyllabusVolume);
-
-   //删除册别
-   rpc Delete(ListPid) returns(ListPid);
-
-}
-
-
-
-message SyllabusVolume {
-   //id生成规则
-   string id = 1;
-   //0默认教学课纲的册别 1个人或单独的专题课纲册别 2,系统课纲
-   int32 type = 2;
-   //Type 如果为0 则是学校编码  如果为1 则是seminar 专题/研讨/培训
-   string scopeCode = 3;
-   //学段
-   string periodCode = 4;
-   //学科
-   string subjectCode = 5;
-   //年级
-   string gradeCode = 6;
-   //学期code
-   string semesterCode = 7;
-   //状态
-   int32 status = 8;
-   //册别name
-   string volumeName = 9;
-   //册别code
-   string volumeCode = 10;
-   //创建者醍摩豆id
-   string TEAMModelId = 11;
-   //共编使用者 的醍摩豆id
-   repeated string editors = 12;
-}
-
-//请求参数Dict
-message Dict {
-   //数字Dict
-   map<string,double> NMap = 1;
-   //字符串Dict
-   map<string,string> SMap = 2;
-   //布尔Dict
-   map<string,bool> BMap = 3;
-   //字符串ListMap
-   repeated LSMap LSMap = 4;
-   //数字ListMap
-   repeated LNMap LNMap = 5;
-   //Byte ListMap
-   repeated LBMap LBMap = 6;
-}
-
-//Byte[] Map
-message LBMap {
-   //Key
-   string Key = 1;
-   //byte数组
-   bytes Value = 2;
-}
-
-//数字ListMap
-message LNMap {
-   //Key
-   string Key = 1;
-   //数字数组
-   repeated double Value = 2 [packed = false];
-}
-
-//字符串ListMap
-message LSMap {
-   //数字Dict
-   string Key = 1;
-   //字符串数组
-   repeated string Value = 2;
-}
-
-enum HttpStatusCode {
-   option allow_alias = true;
-   ZERO = 0; // proto3 requires a zero value as the first item (it can be named anything)
-   Continue = 100;
-   SwitchingProtocols = 101;
-   Processing = 102;
-   EarlyHints = 103;
-   OK = 200;
-   Created = 201;
-   Accepted = 202;
-   NonAuthoritativeInformation = 203;
-   NoContent = 204;
-   ResetContent = 205;
-   PartialContent = 206;
-   MultiStatus = 207;
-   AlreadyReported = 208;
-   IMUsed = 226;
-   Ambiguous = 300;
-   MultipleChoices = 300;
-   MovedPermanently = 301;
-   Moved = 301;
-   Found = 302;
-   Redirect = 302;
-   SeeOther = 303;
-   RedirectMethod = 303;
-   NotModified = 304;
-   UseProxy = 305;
-   Unused = 306;
-   TemporaryRedirect = 307;
-   RedirectKeepVerb = 307;
-   PermanentRedirect = 308;
-   BadRequest = 400;
-   Unauthorized = 401;
-   PaymentRequired = 402;
-   Forbidden = 403;
-   NotFound = 404;
-   MethodNotAllowed = 405;
-   NotAcceptable = 406;
-   ProxyAuthenticationRequired = 407;
-   RequestTimeout = 408;
-   Conflict = 409;
-   Gone = 410;
-   LengthRequired = 411;
-   PreconditionFailed = 412;
-   RequestEntityTooLarge = 413;
-   RequestUriTooLong = 414;
-   UnsupportedMediaType = 415;
-   RequestedRangeNotSatisfiable = 416;
-   ExpectationFailed = 417;
-   MisdirectedRequest = 421;
-   UnprocessableEntity = 422;
-   Locked = 423;
-   FailedDependency = 424;
-   UpgradeRequired = 426;
-   PreconditionRequired = 428;
-   TooManyRequests = 429;
-   RequestHeaderFieldsTooLarge = 431;
-   UnavailableForLegalReasons = 451;
-   InternalServerError = 500;
-   NotImplemented = 501;
-   BadGateway = 502;
-   ServiceUnavailable = 503;
-   GatewayTimeout = 504;
-   HttpVersionNotSupported = 505;
-   VariantAlsoNegotiates = 506;
-   InsufficientStorage = 507;
-   LoopDetected = 508;
-   NotExtended = 510;
-   NetworkAuthenticationRequired = 511;
-}
-
-message IdPk {
-   string id = 1;
-   string pk = 2;
-   HttpStatusCode StatusCode = 3;
-}
-
-message ListPid {
-   //list IdPk
-   repeated IdPk idPks = 1;
-}

+ 0 - 21
TEAMModelGrpc/Protos/greet.proto

@@ -1,21 +0,0 @@
-syntax = "proto3";
-
-option csharp_namespace = "TEAMModelGrpc";
-
-package greet;
-
-// The greeting service definition.
-service Greeter {
-  // Sends a greeting
-  rpc SayHello (HelloRequest) returns (HelloReply);
-}
-
-// The request message containing the user's name.
-message HelloRequest {
-  string name = 1;
-}
-
-// The response message containing the greetings.
-message HelloReply {
-  string message = 1;
-}

+ 0 - 10
TEAMModelGrpc/Services/IBusinessService.cs

@@ -1,10 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-
-namespace TEAMModelOS.SDK.Context.Configuration
-{
-    public interface IBusinessService
-    {
-    }
-}

+ 0 - 149
TEAMModelGrpc/Startup.cs

@@ -1,149 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IdentityModel.Tokens.Jwt;
-using System.Linq;
-using System.Security.Claims;
-using System.Text.Json;
-using System.Threading.Tasks; 
-using Microsoft.AspNetCore.Authentication.JwtBearer;
-using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Hosting;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.Configuration;
-using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.Hosting;
-using Microsoft.Extensions.Primitives;
-using Microsoft.IdentityModel.Tokens;
-using TEAMModelOS.SDK.Context.Configuration;
-using TEAMModelOS.SDK.DI;
-using Microsoft.Extensions.Diagnostics.HealthChecks;
-
-namespace TEAMModelGrpc
-{
-    public class Startup
-    {
-        private IConfiguration _conf;
-        public Startup(IConfiguration conf)
-        {
-            _conf = conf;
-        }
-        // This method gets called by the runtime. Use this method to add services to the container.
-        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
-        public void ConfigureServices(IServiceCollection services)
-        {
-            services.AddGrpc();
-            //添加Grpc扩展
-           // services.AddGrpcExtensions(_conf);
-            //Grpc健康检查
-            services.AddGrpcHealthChecks()
-               .AddAsyncCheck("", () =>
-               {
-                   var r = new Random();
-                   var result = r.Next() % 5 == 0
-                       ? HealthCheckResult.Unhealthy()
-                       : HealthCheckResult.Healthy();
-
-                   return Task.FromResult(result);
-               }, Array.Empty<string>());
-
-            services.AddAuthorization(options =>
-            {
-                options.AddPolicy(JwtBearerDefaults.AuthenticationScheme, policy =>
-                {
-                    policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
-                    policy.RequireClaim(ClaimTypes.Name);
-                });
-            });
-            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
-                .AddJwtBearer(options =>
-                {
-                    options.TokenValidationParameters =
-                        new TokenValidationParameters
-                        {
-                            ValidateAudience = false,
-                            ValidateIssuer = false,
-                            ValidateActor = false,
-                            ValidateLifetime = true,
-                            IssuerSigningKey = SecurityKey
-                        };
-                });
-
-            // Table配置
-            //services.AddScoped<IAzureTableDBRepository, AzureTableDBRepository>();
-            //使用Blob配置
-            //services.AddAzureBlobStorage().AddConnection(_conf.GetSection("Azure:Blob").Get<AzureBlobOptions>());
-            //使用CosmosDB
-            //services.AddAzureCosmosDBV3().AddCosmosDBV3Connection(_conf.GetSection("Azure:CosmosDB").Get<AzureCosmosDBOptions>())
-            //    .AddCosmosSerializer(new SystemTextJsonCosmosSerializer(new JsonSerializerOptions() { IgnoreNullValues = true }));
- 
-            //注入CSRedis
-           // var csredis = new CSRedis.CSRedisClient(_conf.GetSection("Azure:Redis:ConnectionString").Get<string>());
-           // RedisHelper.Initialization(csredis);
-
-            //全局扫描基于IBusinessService接口的实现类
-            //services.Scan(scan => scan.FromApplicationDependencies()
-            //   .AddClasses(classes => classes.AssignableTo<IBusinessService>())
-            //       .AsImplementedInterfaces()
-            //       .WithScopedLifetime());
-
-        }
-
-        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
-        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
-        {
-            if (env.IsDevelopment())
-            {
-                app.UseDeveloperExceptionPage();
-            }
-            
-            app.UseRouting();
-
-            //注册 ASP.NET Core 身份验证中间件的顺序很重要。 
-            //始终在 UseRouting 之后和 UseEndpoints 之前调用 UseAuthentication 和 UseAuthorization。
-            app.UseAuthentication();
-            app.UseAuthorization();
-
-            app.UseEndpoints(endpoints =>
-            {
-               // endpoints.MapGrpcService<HomeWorkService>();
-                endpoints.MapGrpcHealthChecksService();
-                endpoints.MapGet("/generateJwtToken", context =>
-                {
-                    return context.Response.WriteAsync(GenerateJwtToken(context.Request.Query["name"]));
-                });
-
-                endpoints.MapGet("/", async context =>
-                {
-                    await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
-                });
-            });
-            //CodeFirst的Grpc(会自动扫描TStartup所在程序集下的IGrpcSerivce)
-
-
-            //app.UseGrpcExtensions<TEAMModelGrpc.Services.HomeWorkService>(options =>
-            //{
-            //    //CodeFirst配制
-            //    options.GlobalPackage = "TMDGrpc";
-            //    options.ProtoNameSpace = "TMDGrpc";
-            //})
-            //CodeFirst生成proto
-            //.UseProtoGenerate("protos", false);
-        }
-
-        private string GenerateJwtToken(string name)
-        {
-            if (string.IsNullOrEmpty(name))
-            {
-                throw new InvalidOperationException("Name is not specified.");
-            }
-
-            var claims = new[] { new Claim(ClaimTypes.Name, name) };
-            var credentials = new SigningCredentials(SecurityKey, SecurityAlgorithms.HmacSha256);
-            var token = new JwtSecurityToken("ExampleServer", "ExampleClients", claims, expires: DateTime.Now.AddSeconds(60), signingCredentials: credentials);
-            return JwtTokenHandler.WriteToken(token);
-        }
-
-        private readonly JwtSecurityTokenHandler JwtTokenHandler = new JwtSecurityTokenHandler();
-        private readonly SymmetricSecurityKey SecurityKey = new SymmetricSecurityKey(Guid.NewGuid().ToByteArray());
-    }
-}

+ 0 - 48
TEAMModelGrpc/TEAMModelGrpc.csproj

@@ -1,48 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk.Web">
-
-  <PropertyGroup>
-    <TargetFramework>net6.0</TargetFramework>
-    <UserSecretsId>eb0da4a0-e9b5-417f-944d-d7a30dbd2cf5</UserSecretsId>
-    <DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
-    <DocumentationFile>TEAMModelOS.GRPC.xml</DocumentationFile>
-  </PropertyGroup>
-  <ItemGroup>
-    <None Remove="Protos\BlobSASService.proto" />
-    <None Remove="Protos\ClassroomService.proto" />
-    <None Remove="Protos\ClassroomStudentService.proto" />
-    <None Remove="Protos\HomeWorkService.proto" />
-    <None Remove="Protos\SyllabusService.proto" />
-    <None Remove="Protos\VolumeService.proto" />
-  </ItemGroup>
-  <ItemGroup>
-    <Protobuf Include="Protos\BlobSASService.proto" GrpcServices="Server" />
-    <Protobuf Include="Protos\ClassroomService.proto" GrpcServices="Server" />
-    <Protobuf Include="Protos\ClassroomStudentService.proto" GrpcServices="Server" />
-    <Protobuf Include="Protos\greet.proto" GrpcServices="Server" />
-    <Protobuf Include="Protos\CourseService.proto" GrpcServices="Server" />
-    <Protobuf Include="Protos\HomeWorkService.proto" GrpcServices="Server" />
-    <Protobuf Include="Protos\KnowledgeService.proto" GrpcServices="Server" />
-    <Protobuf Include="Protos\SyllabusService.proto" GrpcServices="Server" />
-    <Protobuf Include="Protos\VolumeService.proto" GrpcServices="Server" />
-  </ItemGroup>
-
-  <ItemGroup>
-    <PackageReference Include="Grpc.AspNetCore" Version="2.41.0" />
-    <PackageReference Include="Grpc.HealthCheck" Version="2.43.0" />
-    <PackageReference Include="Grpc.Tools" Version="2.43.0">
-      <PrivateAssets>all</PrivateAssets>
-      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
-    </PackageReference>
-    <PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0" />
-    <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.14.0" />
-  </ItemGroup>
-  <ItemGroup>
-    <ProjectReference Include="..\TEAMModelOS.SDK\TEAMModelOS.SDK.csproj" />
-  </ItemGroup>
-  <ItemGroup>
-    <Folder Include="GrpcHealthCheck\" />
-    <Folder Include="Models\" />
-  </ItemGroup>
-</Project>

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 0 - 2263
TEAMModelGrpc/TEAMModelOS.GRPC.xml


+ 0 - 61
TEAMModelGrpc/appsettings.Development.json

@@ -1,61 +0,0 @@
-{
-  "Logging": {
-    "LogLevel": {
-      "Default": "Debug",
-      "System": "Information",
-      "Grpc": "Information",
-      "Microsoft": "Information"
-    }
-  },
-  "urls": "https://*:5000",
-  "GrpcServer": {
-    //蚚衾grpc雄綴蛁聊善督昢楷珋腔ip華硊僇
-    "ServiceAddress": "*.*.*.*:",
-    //岆瘁蚚督昢蛁聊睿督昢楷珋,蘇岆true
-    "EnableDiscovery": false,
-    //督昢楷珋督昢華硊
-    "DiscoveryUrl": "http://106.12.23.251:8500",
-    //蛁聊善督昢楷珋腔督昢靡備
-    "DiscoveryServiceName": "TMDOSgRPC",
-    //督昢楷珋翋雄TTL腔奀潔(鏃)
-    "DiscoveryTTLInterval": 10,
-    //蛁聊善督昢楷珋腔督昢Tag
-    "DiscoveryServiceTags": "v-1.0.0.1",
-    //蘇渣昫鎢
-    "DefaultErrorCode": 4300000,
-    //Jaeger饜秶(OpenTracing)
-    "Jaeger": {
-      //岆瘁蚚Jaeger,蘇false
-      "Enable": false,
-      "AgentIp": "192.168.8.11",
-      "AgentPort": 5775
-    }
-  },
-  "Azure": {
-    "Table": {
-      "ConnectionString": "DefaultEndpointsProtocol=https;AccountName=teammodelostest;AccountKey=QB/zYHHCAtZfl9tf4emL1Y9ZXGc6fqZ+nNbCxIHM70HnziC8dMdEAu7+Pa4mbKLlbswV90wWHAF3nMjrKB54Lw==;EndpointSuffix=core.chinacloudapi.cn"
-    },
-    "Blob": {
-      "ConnectionString": "DefaultEndpointsProtocol=https;AccountName=teammodelostest;AccountKey=QB/zYHHCAtZfl9tf4emL1Y9ZXGc6fqZ+nNbCxIHM70HnziC8dMdEAu7+Pa4mbKLlbswV90wWHAF3nMjrKB54Lw==;EndpointSuffix=core.chinacloudapi.cn", //"DefaultEndpointsProtocol=https;AccountName=teammodelstorage;AccountKey=Yq7D4dE6cFuer2d2UZIccTA/i0c3sJ/6ITc8tNOyW+K5f+/lWw9GCos3Mxhj47PyWQgDL8YbVD63B9XcGtrMxQ==;EndpointSuffix=core.chinacloudapi.cn",
-      "Container": "teammodelos"
-    },
-    "CosmosDB": {
-      "ConnectionString": "https://192.168.8.128:8081",
-      "ConnectionKey": "ddwAeGSf8Lsf1kxPXmdqnyzzi3CkJ0KW2BTPZ7Zq1N7qbJic5j7AaQ+WbF86F3rnzuDgGM1yg8O7BUFo93iA8w==",
-      "Database": "TEAMModelOS",
-      "CollectionThroughput": 400      
-    },
-    "Redis": {
-      "ConnectionString": "106.12.23.251:6379,password=habook,ssl=false,abortConnect=False,defaultDatabase=13,writeBuffer=10240,poolsize=50,prefix=habook:"
-    }
-  },
-  "HaBookAuth": {
-    "TeamModelRegistUrl": "https://account.habookaclass.biz/regist?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJsb2dpbiIsImF1ZCI6ImNoZW5nZHVMb2dpbiIsImlzcyI6Imh0dHBzOi8vYXBpLmhhYm9va2FjbGFzcy5iaXoiLCJpYXQiOjE1MzYxMzUwNDcsIm5iZiI6MTUzNjEzNTA0NywiZXhwIjoxNTY3NTU1MjAwLCJpZHAiOiJIYWJvb2sgQ29yZVNlcnZpY2UifQ.F4AnkbJrMRoZvJ6SC-lqZEYIYSoq5x8lvX6_a3YqSgM&callback=",
-    "TeamModelLoginUrl": "https://account.habookaclass.biz/?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJsb2dpbiIsImF1ZCI6ImNoZW5nZHVMb2dpbiIsImlzcyI6Imh0dHBzOi8vYXBpLmhhYm9va2FjbGFzcy5iaXoiLCJpYXQiOjE1MzYxMzUwNDcsIm5iZiI6MTUzNjEzNTA0NywiZXhwIjoxNTY3NTU1MjAwLCJpZHAiOiJIYWJvb2sgQ29yZVNlcnZpY2UifQ.F4AnkbJrMRoZvJ6SC-lqZEYIYSoq5x8lvX6_a3YqSgM&callback=",
-    "AccountUrl": "https://api.habookaclass.biz/account",
-    "ServiceUrl": "https://api.habookaclass.biz/service",
-    "UserInfoKey": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJpZCIsImF1ZCI6ImNoZW5nZHVJZCIsImlzcyI6Imh0dHBzOi8vYXBpLmhhYm9va2FjbGFzcy5iaXoiLCJpYXQiOjE1MzYwNTIzNjcsIm5iZiI6MTUzNjA1MjM2NywiZXhwIjoxNTY3NTU1MjAwLCJpZHAiOiJIYWJvb2sgQ29yZVNlcnZpY2UifQ.RGKDVtwFEp4OBctlHOuF6yqyI21fTz4cinCxjFCxkSQ",
-    "SchoolCodeKey": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzY2hvb2xDb2RlIiwiYXVkIjoiY2hlbmdkdVNjaG9vbENvZGUiLCJpc3MiOiJodHRwczovL2FwaS5oYWJvb2thY2xhc3MuYml6IiwiaWF0IjoxNTM2MDUyNDI3LCJuYmYiOjE1MzYwNTI0MjcsImV4cCI6MTU2NzU1NTIwMCwiaWRwIjoiSGFib29rIENvcmVTZXJ2aWNlIn0.8m5VH3Nz4N9EdMz8AexTOEuDVitcJZFKy9DfW_UQkSY",
-    "SmsKey": "Basic ZmYwMWM0YTJjODdmZmNkYTUyNjhmMDEwOmE0YTE5YTVjNTU2ZWVhZTNjZmZhNTI0Mg=="
-  }
-}

+ 0 - 67
TEAMModelGrpc/appsettings.json

@@ -1,67 +0,0 @@
-{
-  "Logging": {
-    "LogLevel": {
-      "Default": "Information",
-      "Microsoft": "Warning",
-      "Microsoft.Hosting.Lifetime": "Information"
-    }
-  },
-  "AllowedHosts": "*",
-  "Kestrel": {
-    "EndpointDefaults": {
-      "Protocols": "Http2"
-    }
-  },
-  "urls": "https://*:5000",
-  "GrpcServer": {
-    //蚚衾grpc雄綴蛁聊善督昢楷珋腔ip華硊僇
-    "ServiceAddress": "*.*.*.*:",
-    //岆瘁蚚督昢蛁聊睿督昢楷珋,蘇岆true
-    "EnableDiscovery": true,
-    //督昢楷珋督昢華硊
-    "DiscoveryUrl": "http://106.12.23.251:8500",
-    //蛁聊善督昢楷珋腔督昢靡備
-    "DiscoveryServiceName": "TMDOSgRPC",
-    //督昢楷珋翋雄TTL腔奀潔(鏃)
-    "DiscoveryTTLInterval": 10,
-    //蛁聊善督昢楷珋腔督昢Tag
-    "DiscoveryServiceTags": "v-1.0.0.1",
-    //蘇渣昫鎢
-    "DefaultErrorCode": 4300000,
-    //Jaeger饜秶(OpenTracing)
-    "Jaeger": {
-      //岆瘁蚚Jaeger,蘇false
-      "Enable": false,
-      "AgentIp": "192.168.8.11",
-      "AgentPort": 5775
-    }
-  },
-  "Azure": {
-    "Table": {
-      "ConnectionString": "DefaultEndpointsProtocol=https;AccountName=teammodelstorage;AccountKey=Yq7D4dE6cFuer2d2UZIccTA/i0c3sJ/6ITc8tNOyW+K5f+/lWw9GCos3Mxhj47PyWQgDL8YbVD63B9XcGtrMxQ==;EndpointSuffix=core.chinacloudapi.cn"
-    },
-    "Blob": {
-      "ConnectionString": "DefaultEndpointsProtocol=https;AccountName=teammodelstorage;AccountKey=Yq7D4dE6cFuer2d2UZIccTA/i0c3sJ/6ITc8tNOyW+K5f+/lWw9GCos3Mxhj47PyWQgDL8YbVD63B9XcGtrMxQ==;EndpointSuffix=core.chinacloudapi.cn",
-      "Container": "teammodelos"
-    },
-    "CosmosDB": {
-      "ConnectionString": "https://teammodelos.documents.azure.cn:443/",
-      "ConnectionKey": "clF73GwPECfP1lKZTCvs8gLMMyCZig1HODFbhDUsarsAURO7TcOjVz6ZFfPqr1HzYrfjCXpMuVD5TlEG5bFGGg==",
-      "Database": "TEAMModelOSTest",
-      "CollectionThroughput": 400
-      
-    },
-    "Redis": {
-      "ConnectionString": "teammodel.redis.cache.chinacloudapi.cn:6380,password=9wcTVDiAWiAf0IF5NOjZBvYrZe9JlbEw1E3F1QFcNbo=,ssl=True,abortConnect=False,defaultDatabase=13,writeBuffer=10240,poolsize=50,prefix=habook:"
-    }
-  },
-  "HaBookAuth": {
-    "TeamModelRegistUrl": "https://account.habookaclass.biz/regist?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJsb2dpbiIsImF1ZCI6ImNoZW5nZHVMb2dpbiIsImlzcyI6Imh0dHBzOi8vYXBpLmhhYm9va2FjbGFzcy5iaXoiLCJpYXQiOjE1MzYxMzUwNDcsIm5iZiI6MTUzNjEzNTA0NywiZXhwIjoxNTY3NTU1MjAwLCJpZHAiOiJIYWJvb2sgQ29yZVNlcnZpY2UifQ.F4AnkbJrMRoZvJ6SC-lqZEYIYSoq5x8lvX6_a3YqSgM&callback=",
-    "TeamModelLoginUrl": "https://account.habookaclass.biz/?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJsb2dpbiIsImF1ZCI6ImNoZW5nZHVMb2dpbiIsImlzcyI6Imh0dHBzOi8vYXBpLmhhYm9va2FjbGFzcy5iaXoiLCJpYXQiOjE1MzYxMzUwNDcsIm5iZiI6MTUzNjEzNTA0NywiZXhwIjoxNTY3NTU1MjAwLCJpZHAiOiJIYWJvb2sgQ29yZVNlcnZpY2UifQ.F4AnkbJrMRoZvJ6SC-lqZEYIYSoq5x8lvX6_a3YqSgM&callback=",
-    "AccountUrl": "https://api.habookaclass.biz/account",
-    "ServiceUrl": "https://api.habookaclass.biz/service",
-    "UserInfoKey": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJpZCIsImF1ZCI6ImNoZW5nZHVJZCIsImlzcyI6Imh0dHBzOi8vYXBpLmhhYm9va2FjbGFzcy5iaXoiLCJpYXQiOjE1MzYwNTIzNjcsIm5iZiI6MTUzNjA1MjM2NywiZXhwIjoxNTY3NTU1MjAwLCJpZHAiOiJIYWJvb2sgQ29yZVNlcnZpY2UifQ.RGKDVtwFEp4OBctlHOuF6yqyI21fTz4cinCxjFCxkSQ",
-    "SchoolCodeKey": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzY2hvb2xDb2RlIiwiYXVkIjoiY2hlbmdkdVNjaG9vbENvZGUiLCJpc3MiOiJodHRwczovL2FwaS5oYWJvb2thY2xhc3MuYml6IiwiaWF0IjoxNTM2MDUyNDI3LCJuYmYiOjE1MzYwNTI0MjcsImV4cCI6MTU2NzU1NTIwMCwiaWRwIjoiSGFib29rIENvcmVTZXJ2aWNlIn0.8m5VH3Nz4N9EdMz8AexTOEuDVitcJZFKy9DfW_UQkSY",
-    "SmsKey": "Basic ZmYwMWM0YTJjODdmZmNkYTUyNjhmMDEwOmE0YTE5YTVjNTU2ZWVhZTNjZmZhNTI0Mg=="
-  }
-}

BIN=BIN
TEAMModelGrpc/habook.pfx


+ 0 - 12
TEAMModelGrpc/nuget.config

@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<configuration>
-  <packageSources>
-    <add key="AspNetCore" value="https://dotnet.myget.org/F/aspnetcore-ci-dev/api/v3/index.json" />
-    <add key="AspNetCoreTools" value="https://dotnet.myget.org/F/aspnetcore-tools/api/v3/index.json" />
-    <add key="NuGet" value="https://api.nuget.org/v3/index.json" />
-    <!--这里添加自己的包地址-->
-    <add key="habook" value="http://cs.habook.com.tw:30000/v3/index.json" />
-  </packageSources>
-</configuration>
-
-

+ 1 - 1
TEAMModelOS.FunctionV4/CosmosDB/TriggerExam.cs

@@ -1574,7 +1574,7 @@ namespace TEAMModelOS.FunctionV4
                 if () { 
                 
                 }*/
-                if (errorItems.Count == 0)
+                if (errorItems.Count == 0 && info.qamode != 2)
                 {
                     // 新增逻辑 收集错题内容
                     BlobDownloadResult index_json;

+ 1 - 2
TEAMModelFunction/Properties/ServiceDependencies/teammodelos-func-v4 - Zip Deploy/profile.arm.json

@@ -21,7 +21,7 @@
     },
     "resourceName": {
       "type": "string",
-      "defaultValue": "teammodelos-func-v4",
+      "defaultValue": "test",
       "metadata": {
         "description": "Name of the main resource to be created by this template."
       }
@@ -128,7 +128,6 @@
                     "[variables('function_ResourceId')]"
                   ],
                   "properties": {
-                    "AzureWebJobsDashboard": "[concat('DefaultEndpointsProtocol=https;AccountName=', variables('storage_name'), ';AccountKey=', listKeys(variables('storage_ResourceId'), '2017-10-01').keys[0].value, ';EndpointSuffix=', 'core.windows.net')]",
                     "AzureWebJobsStorage": "[concat('DefaultEndpointsProtocol=https;AccountName=', variables('storage_name'), ';AccountKey=', listKeys(variables('storage_ResourceId'), '2017-10-01').keys[0].value, ';EndpointSuffix=', 'core.windows.net')]",
                     "FUNCTIONS_EXTENSION_VERSION": "~3",
                     "FUNCTIONS_WORKER_RUNTIME": "dotnet"

+ 1 - 1
TEAMModelOS.FunctionV4/TEAMModelOS.FunctionV4.csproj

@@ -51,7 +51,7 @@
 		<PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.15.0" />
 		<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Timer" Version="4.1.0" />
 		<PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.7.0" />
-		<PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.10.0" />
+	
 		<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.0.13" />
 		<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Storage" Version="5.0.1" />
 		<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.ServiceBus" Version="5.7.0" />

+ 1 - 1
TEAMModelOS.FunctionV4/local.settings.json

@@ -5,7 +5,7 @@
     "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
     "Azure:Storage:ConnectionString": "DefaultEndpointsProtocol=https;AccountName=teammodeltest;AccountKey=O2W2vadCqexDxWO+px+QK7y1sHwsYj8f/WwKLdOdG5RwHgW/Dupz9dDUb4c1gi6ojzQaRpFUeAAmOu4N9E+37A==;EndpointSuffix=core.chinacloudapi.cn",
     "Azure:LogStorage:ConnectionString": "DefaultEndpointsProtocol=https;AccountName=teammodellog;AccountKey=lxVDrgs+6rKtmASL3k1WrarrEd5Rk42wS1Mu5+sqQlPya1JLSlFDtnZUvMPeHHe7zlESfn/1NY7CZdGviy2UCw==;EndpointSuffix=core.chinacloudapi.cn",
-    "Azure:ServiceBus:ConnectionString": "Endpoint=sb://teammodelos.servicebus.chinacloudapi.cn/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=Sy4h4EQ8zP+7w/lOLi1X3tGord/7ShFHimHs1vC50Dc=",
+    "Azure:ServiceBus:ConnectionString": "Endpoint=sb://coreservicebuscn.servicebus.chinacloudapi.cn/;SharedAccessKeyName=TEAMModelOS;SharedAccessKey=xO8HcvXXuuEkuFI0KlV5uXs8o6vyuVqTR+ASbPGMhHo=",
     "Azure:Cosmos:ConnectionString": "AccountEndpoint=https://cdhabookdep-free.documents.azure.cn:443/;AccountKey=JTUVk92Gjsx17L0xqxn0X4wX2thDPMKiw4daeTyV1HzPb6JmBeHdtFY1MF1jdctW1ofgzqkDMFOtcqS46by31A==;",
     "Azure:Redis:ConnectionString": "52.130.252.100:6379,password=habook,ssl=false,abortConnect=False,writeBuffer=10240",
     "Azure:ServiceBus:ActiveTask": "dep-active-task",

+ 8 - 1
TEAMModelOS.SDK/Models/Cosmos/Common/Activity.cs

@@ -554,6 +554,7 @@ namespace TEAMModelOS.SDK.Models
         //Contest/赛课活动",  "Training/线上培训", "Research/教研活动
         public string school { get; set; }
         public EnrollContest contest { get; set; }
+        
     }
 
     public class EnrollContest
@@ -561,7 +562,7 @@ namespace TEAMModelOS.SDK.Models
         /// <summary>
         /// 报名时间
         /// </summary>
-        public string enrollTime { get; set; }
+        public long  enrollTime { get; set; }
         /// <summary>
         /// 参赛模式 0 个人,1 团队(是否允许跨校)
         /// </summary>
@@ -580,8 +581,14 @@ namespace TEAMModelOS.SDK.Models
         /// 表单填报信息
         /// </summary>
         public List<EnrollInfo> enrollInfos { get; set; } = new List<EnrollInfo>();
+
+        public EnrollUpload contest { get; set; }
     }
+    public class EnrollUpload 
+    { 
+        
 
+    }
     /// <summary>
     /// 表单填报信息
     /// </summary>

+ 2 - 2
TEAMModelOS.SDK/Models/Cosmos/School/Elegant.cs

@@ -49,12 +49,12 @@ namespace TEAMModelOS.SDK.Models
      
         public List<Attachment> attachments { get; set; } = new List<Attachment>();
         public string target { get; set; }
-      
+
         /// <summary>
         /// 业务类型。elegant 德育, art 艺术,弃用
         /// </summary>
         // public List<string> bizCode { get; set; }
-        public List<string> bizType { get; set; }
+        public List<string> bizType { get; set; } = new List<string>();
         /// <summary>
         /// image  video
         /// </summary>

+ 1 - 1
TEAMModelOS.SDK/TEAMModelOS.SDK.csproj

@@ -40,7 +40,7 @@
     <PackageReference Include="NPinyin.Core" Version="3.0.0" />
     <PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="6.0.0" />
     <PackageReference Include="VueCliMiddleware" Version="6.0.0" />
-	<PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.6.0" />
+	<PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.10.0" />
 	<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Abstractions" Version="1.1.0" />
 	<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.0.13" />
   </ItemGroup>

+ 70 - 0
TEAMModelOS.TEST/Program.cs

@@ -17,6 +17,76 @@ namespace TEAMModelOS.TEST
             //var jsonAuth = System.IO.File.ReadAllText("C:\\Users\\CrazyIter\\Downloads\\492266088181141504\\ActivityInfo.json", Encoding.UTF8);
             //var jsonData = jsonAuth.ToObject<LessonRecordActivityInfo>();
             string path = "C:\\Users\\CrazyIter\\Downloads\\消费清单(2022-2023)\\bill";
+            List<List<string>> inputArray = new List<List<string>>
+            {  
+                new List<string> { "2", "11" },
+                new List<string> { "1", "22" },
+                new List<string> { "1", "11", "111" },
+                new List<string> { "2", "22", "222" },
+                new List<string> { "1", "11" },
+                new List<string> { "1", "11" },
+                new List<string> { "1" },
+                new List<string> { "2", "22", "222" },
+                new List<string> { "2", "22" }  ,
+            };
+
+            // 转换为层级结构
+            List<ClassifiedItem> result = ClassifyHierarchy(inputArray);
+
+            // 输出结果
+            foreach (var item in result)
+            {
+                Console.WriteLine($"id: {item.Id}, count: {item.Count}, pid: {item.Pid}");
+            }
+        }
+        static List<ClassifiedItem> ClassifyHierarchy(List<List<string>> inputArray)
+        {
+            Dictionary<string, int> hierarchyCount = new Dictionary<string, int>();
+            List<ClassifiedItem> result = new List<ClassifiedItem>();
+
+            foreach (var list in inputArray)
+            {
+                for (int i = 0; i < list.Count; i++)
+                {
+                    string currentId = list[i];
+                    string parentId = (i > 0) ? list[i - 1] : null;
+
+                    string hierarchyKey = $"{currentId}|{parentId}";
+
+                    if (hierarchyCount.ContainsKey(hierarchyKey))
+                    {
+                        hierarchyCount[hierarchyKey]++;
+                    }
+                    else
+                    {
+                        hierarchyCount[hierarchyKey] = 1;
+                    }
+                    var item = result.Find(item => item.Id == currentId && item.Pid == parentId);
+                    if (item== null  )
+                    {
+                        result.Add(new ClassifiedItem
+                        {
+                            Id = currentId,
+                            Pid = parentId,
+                            Count = 0
+                        });
+                    }
+                }
+            }
+
+            foreach (var item in result)
+            {
+                string hierarchyKey = $"{item.Id}|{item.Pid}";
+                item.Count = hierarchyCount.ContainsKey(hierarchyKey) ? hierarchyCount[hierarchyKey] : 0;
+            }
+
+            return result;
+        }
+        class ClassifiedItem
+        {
+            public string Id { get; set; }
+            public int Count { get; set; }
+            public string Pid { get; set; }
         }
     }
 

+ 1 - 1
TEAMModelOS.sln

@@ -11,7 +11,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TEAMModelOS", "TEAMModelOS\
 EndProject
 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TEAMModelBI", "TEAMModelBI\TEAMModelBI.csproj", "{54DC5894-D5BA-40AB-9226-FB801E04BA24}"
 EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TEAMModelOS.TEST", "TEAMModelOS.TEST\TEAMModelOS.TEST.csproj", "{335938F6-8418-497A-AB41-CDD006FB8FD6}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TEAMModelOS.TEST", "TEAMModelOS.TEST\TEAMModelOS.TEST.csproj", "{335938F6-8418-497A-AB41-CDD006FB8FD6}"
 EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution

+ 6 - 0
TEAMModelOS/ClientApp/public/lang/en-US.js

@@ -7647,6 +7647,7 @@ const LANG_EN_US = {
             title: 'Device Statistics',
             deviceTotal: 'Total Devices',
             deviceOnline: 'Used Devices',
+            numAndproportion: 'Quantity and Proportion',
         },
         lessons: {
             title: 'Lesson and Application History Chart',
@@ -7662,6 +7663,11 @@ const LANG_EN_US = {
             task: 'Task',
             differentiation: 'Differentiated',
             examination: 'Assessment',
+        },
+        basicsChat: {
+            title: 'Basic data',
+            roomnum: 'Classrooms',
+            teachnum: 'Teachers',
         }
     },
     areaIot: {

+ 7 - 1
TEAMModelOS/ClientApp/public/lang/zh-CN.js

@@ -3731,7 +3731,7 @@ const LANG_ZH_CN = {
             dashTitle: '选择需要查看的数据看板',
             schoolSummary: '展现学校信息、教学资源和课程动态,学校整体风貌,方便学校领导掌握学校情况',
             teacherSummary: '展示智慧课堂和教学法应用数据情况,关注教学质量与成果,助力学生全面发展',
-            studentSummary: '展示学生五育(德、智、体、美、劳)全面发展,传播优良校风,培育健全人格',
+            studentSummary: '采用系统工具赋能自动采集学生数据,以综合素养及课程标准为导向,实现立德树人,科学评价目标。',
             iotSummary: '统计由智慧教室物联网自动汇总本校的智慧课堂使用数据,且不限于IES云课程',
             cols: '显示列',
             title: '校园大数据',
@@ -7648,6 +7648,7 @@ const LANG_ZH_CN = {
             title: '设备统计',
             deviceTotal: '总设备数',
             deviceOnline: '总上线数',
+            numAndproportion:'数量与占比'
         },
         lessons: {
             title: '课堂及历程统计',
@@ -7663,6 +7664,11 @@ const LANG_ZH_CN = {
             task: '任务型态',
             differentiation: '差异化型态',
             examination: '测验型态',
+        },
+        basicsChat: {
+            title: '基础数据',
+            roomnum: '教室数',
+            teachnum: '教师数',
         }
     },
     //学区iot

+ 6 - 0
TEAMModelOS/ClientApp/public/lang/zh-TW.js

@@ -7648,6 +7648,7 @@ const LANG_ZH_TW = {
             title: '裝置統計',
             deviceTotal: '總裝置數',
             deviceOnline: '上線數',
+            numAndproportion: '數量與佔比',
         },
         lessons: {
             title: '課堂與應用歷程統計',
@@ -7663,6 +7664,11 @@ const LANG_ZH_TW = {
             task: '任務型態',
             differentiation: '差異化型態',
             examination: '測驗型態',
+        },
+        basicsChat: {
+            title: '基礎資料',
+            roomnum: '教室數',
+            teachnum: '教師數',
         }
     },
     areaIot: {

+ 2 - 0
TEAMModelOS/ClientApp/src/api/index.js

@@ -44,6 +44,7 @@ import areaOverview from './areaOverview'
 import newCourse from './newCourse'
 import iot from './iot'
 import areaActivity from './areaActivity'
+import schoolDashborad from './schoolDashborad'
 export default {
     accessToken,
     learnActivity,
@@ -88,6 +89,7 @@ export default {
     newCourse,
     iot,
     areaActivity,
+    schoolDashborad,
     // 获取登录跳转链接
     getLoginLink: function (data) {
         return post('api/login/login', data)

+ 6 - 0
TEAMModelOS/ClientApp/src/api/schoolDashborad.js

@@ -0,0 +1,6 @@
+import { fetch, post } from '@/api/http'
+export default {
+    schoolData:function(data){
+        return post('/school/init/get-scstats',data)
+    }
+}

+ 2 - 2
TEAMModelOS/ClientApp/src/common/BaseLayout.vue

@@ -751,7 +751,7 @@
 									permission: "dashboard-read",
 									menuName: "dashCenter",
 									child: [],
-									isShow: !this.isGlobalSite,
+									isShow: true,
 								},
 								// 学校管理
 								{
@@ -1261,7 +1261,7 @@
 									menuName: "ResearchMgt",
 									permission: "research-read|research-upd",
 									child: [],
-									isShow: this.edition !== "artTest" && this.IES5Menu && !this.isGlobalSite
+									isShow: this.edition !== "artTest" && this.IES5Menu && !this.isGlobalSite && this.isOpenLessonRecord
 								},
 								// 学情分析(国际站单独)
 								{

+ 2 - 2
TEAMModelOS/ClientApp/src/view/areaMgmt/AreaEcharts/gradePie.vue

@@ -87,7 +87,7 @@ class InitChart {
     ]
     var data = datas ? datas : defaults
     let datum = data.map((v) => v.value)
-    let color = ['#27D099', '#B458F5', '#FCD54B', '#5684F4', '#81ecec', '#ff7675']
+    let color = ['#27D099', '#B458F5', '#FCD54B', '#5684F4', '#81ecec', '#ff7675','#FFFB7D','#E0C3FC','#97D9E1','#85FFBD','#FBAB7E','#FF5ACD']
     // let data1 = data[0].value + data[1].value + data[2].value + data[3].value
     let baseData = []
     for (var i = 0; i < data.length; i++) {
@@ -96,7 +96,7 @@ class InitChart {
         name: data[i].name,
         itemStyle: {
           normal: {
-            borderWidth: 20,
+            borderWidth: 15,
             shadowBlur: 10,
             borderColor: color[i],
             borderRadius: 5,

+ 166 - 28
TEAMModelOS/ClientApp/src/view/dashboard/school/SchoolDashboard.vue

@@ -1,10 +1,12 @@
 <template>
     <div class="school-dash-container">
-        <div class="schoolanalysebox" >
+        <div class="schoolanalysebox">
+            <Loading v-if="detailsLoding"></Loading>
             <div class="school-analyse-header bgimg">
             <div class="school-analyse-headersbox">
                 <div class="school-analyse-headersbox-name">
-                <span>123456</span>
+                    <img :src="schoolDeatils.picture"/>
+                    <span>{{schoolDeatils.name}}</span>
                 </div>
                 <div class="school-analyse-headersbox-basics">
                 <div class="items-basics">
@@ -42,7 +44,7 @@
             </div>
             <div class="class-total">
                 <div class="class-box total-box total1" v-for="itemD in classroomsData.details" :key="itemD.id">
-                <div class="classbox-num total-num">{{itemD.value}}</div>
+                <div class="classbox-num total-num">{{itemD.value}} <span v-show="itemD.id ===1" class="hours">H</span></div>
                 <div class="classbox-title total-title">{{itemD.name}}</div>
                 </div>
             </div>
@@ -131,7 +133,8 @@ export default {
     data(){
         return{
             schoolDeatils:{
-                name:'123456'
+                name:'',
+                picture:'',
             },
             anSchool:{
                 teachNum: 0,
@@ -145,7 +148,7 @@ export default {
                 classed: [],
                 activitys: [],
                 interacts: [],
-                times: ['11','22'],
+                times: [],
             },
             classroomsData:{
                 attend: [
@@ -195,7 +198,7 @@ export default {
                         show: true,
                         type: 'shadow',
                         },
-                        data: ['1月','2月','3月','4月','5月',],
+                        data: [],
                     },
                     ],
                     yAxis: [
@@ -228,7 +231,7 @@ export default {
                             name: '课例',
                             type: 'bar',
                             barWidth: '20',
-                            data: [11,15,16,18,17],
+                            data: [],
                             itemStyle: {
                             //lenged文本
                             opacity: 1,
@@ -286,7 +289,7 @@ export default {
                         show: true,
                         type: 'shadow',
                         },
-                        data: ['1月','2月','3月','4月','5月',],
+                        data: [],
                     },
                     ],
                     yAxis: [
@@ -320,7 +323,7 @@ export default {
                         name: '活动',
                         type: 'bar',
                         barWidth: '20',
-                        data: [11,15,16,14,18],
+                        data: [],
                         itemStyle: {
                         //lenged文本
                         opacity: 1,
@@ -378,7 +381,7 @@ export default {
                         show: true,
                         type: 'shadow',
                         },
-                        data: ['1月','2月','3月','4月','5月',],
+                        data: [],
                     },
                     ],
                     yAxis: [
@@ -412,7 +415,7 @@ export default {
                         name: '互动',
                         type: 'bar',
                         barWidth: '20',
-                        data: [10,5,9,78,12],
+                        data: [],
                         itemStyle: {
                         //lenged文本
                         opacity: 1,
@@ -464,8 +467,7 @@ export default {
                     },
                     legend: {
                     show: true,
-                    // data: this.anSchool.times,
-                    data:['1月','2月','3月','4月','5月'],
+                    data:[],
                     textStyle: {
                         color: '#000',
                     },
@@ -474,7 +476,7 @@ export default {
                     },
                     xAxis: {
                     type: 'category',
-                    data:['1月','2月','3月','4月','5月'],
+                    data:[],
                     boundaryGap: false,
                     },
                     yAxis: {
@@ -560,10 +562,12 @@ export default {
                     {
                         name: '科目占比',
                         type: 'pie',
-                        radius: '80%',
+                        radius: ['35%', '75%'],
                         center: ['45%', '50%'],
                         itemStyle: {
-                        borderRadius: 2,
+                        borderRadius: 25,
+                        borderWidth:2,
+                        borderColor:'#fff',
                         },
                         label: {
                         normal: {
@@ -576,18 +580,7 @@ export default {
                     ],
                 },
             },
-            detailsGrade:[ {
-                value: 0,
-                name: '123',
-              },
-              {
-                value: 0,
-                name: '456',
-              },
-              {
-                value: 0,
-                name: '789',
-              },],
+            detailsGrade:[],
             detailsbasics:[
             {
                 id: 1,
@@ -650,11 +643,143 @@ export default {
                 todayNum: 0,
             },
             ],
+            detailsLoding:false,
         }
     },
+    created(){
+        this.init()
+    },
     methods:{
         detailsback(){
             this.$router.push('/dashCenter')
+        },
+        init(){
+            let schoolCode=localStorage.cur_schoolCode
+            let data={schoolId:schoolCode}
+            this.detailsLoding=true
+            this.$api.schoolDashborad.schoolData(data).then((res)=>{
+                console.log(res,'school Back')
+             if(res.state == 200){
+                let {lessonStats,scStats,school}=res
+                //基础信息
+                this.schoolDeatils.name=school.name
+                this.schoolDeatils.picture=school.picture
+                this.anSchool.teachNum=scStats.tch
+                this.anSchool.studentNum=scStats.stu
+                this.anSchool.classNum=scStats.room
+                this.anSchool.classInfoNum=lessonStats.resourcesCount
+                //header data
+                this.classroomsData.attend[0].value=lessonStats.cnt
+                this.classroomsData.attend[1].value=lessonStats.dayCnt
+                this.classroomsData.attend[2].value=lessonStats.weekCnt
+                this.classroomsData.attend[3].value=lessonStats.monthCnt
+                this.classroomsData.attend[4].value=0
+
+                this.classroomsData.details[0].value=lessonStats.duration === 0 ? 0 : Number((lessonStats.duration / 60).toFixed(2))
+                this.classroomsData.details[1].value=lessonStats.attendCount
+                this.classroomsData.details[2].value=lessonStats.clientInteractionCount
+                this.classroomsData.details[3].value=lessonStats.workCount
+                this.classroomsData.details[4].value=lessonStats.interactionCount
+
+                //Bar data
+                //课例
+                scStats.lessStats.year.forEach((item) => {
+                    this.anSchool.classed.push(item.cnt)
+                    this.anSchool.class += item.cnt
+                    //处理时间
+                    this.anSchool.times.push(item.id)
+                })
+                //活动
+                scStats.actStats.year.forEach((item) => {
+                    this.anSchool.activitys.push(item.cnt)
+                    this.anSchool.activity += item.cnt
+                })
+                //互动
+                scStats.lessStats.yearInters.forEach((item) => {
+                    this.anSchool.interacts.push(item.cnt)
+                    this.anSchool.interact += item.cnt
+                })
+                this.detailsEchart.bar1.timeline.data = this.anSchool.times
+                this.detailsEchart.bar1.xAxis[0].data = this.anSchool.times
+                this.detailsEchart.bar1.series[0].data = this.anSchool.classed
+
+                this.detailsEchart.bar2.timeline.data = this.anSchool.times
+                this.detailsEchart.bar2.xAxis[0].data = this.anSchool.times
+                this.detailsEchart.bar2.series[0].data = this.anSchool.activitys
+
+                this.detailsEchart.bar3.timeline.data = this.anSchool.times
+                this.detailsEchart.bar3.xAxis[0].data = this.anSchool.times
+                this.detailsEchart.bar3.series[0].data = this.anSchool.interacts
+
+                //center data
+                //课例
+                 this.detailsbasics[0].num=scStats.lessStats.all
+                 this.detailsbasics[0].todayNum =scStats.lessStats.day
+                 this.detailsbasics[0].subheadingNum =scStats.lessStats.lastDay === 0 && scStats.lessStats.day === 0 ? '0%' : scStats.lessStats.lastDay === 0 ? '100%' : ((scStats.lessStats.day - scStats.lessStats.lastDay) / scStats.lessStats.lastDay).toFixed(2) * 100 + '%'
+                 this.detailsbasics[0].subheadNum = this.anSchool.classed[this.anSchool.classed.length - 2] === 0 && this.anSchool.classed[this.anSchool.classed.length - 1] === 0 ? '0%' : this.anSchool.classed[this.anSchool.classed.length - 2] === 0 ? '100%' : ((this.anSchool.classed[this.anSchool.classed.length - 1] - this.anSchool.classed[this.anSchool.classed.length - 2]) / this.anSchool.classed[this.anSchool.classed.length - 2] * 100).toFixed(2) + '%'
+                //活动
+                this.detailsbasics[1].num = scStats.actStats.all
+                this.detailsbasics[1].todayNum = scStats.actStats.dayCnt
+                this.detailsbasics[1].subheadingNum = scStats.actStats.lastDay === 0 && scStats.actStats.dayCnt === 0 ? '0%' : scStats.actStats.lastDay === 0 ? '100%' : ((scStats.actStats.dayCnt - scStats.actStats.lastDay) / scStats.actStats.lastDay).toFixed(2) * 100 + '%'
+                this.detailsbasics[1].subheadNum = this.anSchool.activitys[this.anSchool.activitys.length - 2] === 0 && this.anSchool.activitys[this.anSchool.activitys.length - 1] === 0 ? '0%' : this.anSchool.activitys[this.anSchool.activitys.length - 2] === 0 ? '100%' : ((this.anSchool.activitys[this.anSchool.activitys.length - 1] - this.anSchool.activitys[this.anSchool.activitys.length - 2]) / this.anSchool.activitys[this.anSchool.activitys.length - 2] * 100).toFixed(2) + '%'
+                //互动
+                let alls = scStats.lessStats.yearInters.reduce(function (total, currentValue) { ; return Number(total) + Number(currentValue.cnt) }, 0)
+                this.detailsbasics[2].num = alls
+                this.detailsbasics[2].todayNum = scStats.lessStats.dayInter
+                this.detailsbasics[2].subheadingNum = scStats.lessStats.lastDayInter === 0 && scStats.lessStats.dayInter === 0 ? '0%' : scStats.lessStats.lastDayInter === 0 ? '100%' : ((scStats.lessStats.dayInter - scStats.lessStats.lastDayInter) / scStats.lessStats.lastDayInter).toFixed(2) * 100 + '%'
+                this.detailsbasics[2].subheadNum = this.anSchool.interacts[this.anSchool.interacts.length - 2] === 0 && this.anSchool.interacts[this.anSchool.interacts.length - 1] === 0 ? '0%' : this.anSchool.interacts[this.anSchool.interacts.length - 2] === 0 ? '100%' : ((this.anSchool.interacts[this.anSchool.interacts.length - 1] - this.anSchool.interacts[this.anSchool.interacts.length - 2]) / this.anSchool.interacts[this.anSchool.interacts.length - 2] * 100).toFixed(2) + '%'
+                //总数据
+                let nowYear = scStats.lessStats.all + scStats.actStats.all
+                let lastYear = scStats.lessStats.lastYear + scStats.actStats.lastYear
+                this.detailsbasics[3].subheadNum = nowYear === 0 && lastYear === 0 ? '0%' : lastYear === 0 ? '100%' : (((nowYear - lastYear) / lastYear) * 100).toFixed(2) + '%'
+                let classedDatas =  this.anSchool.classed; let activitysDatas =  this.anSchool.activitys; let interactDatas =  this.anSchool.interacts
+                let tataldata1 = classedDatas.map((index, item) => { return index + activitysDatas[item]; })
+                this.detailsEchart.line.legend.data=this.anSchool.times
+                this.detailsEchart.line.xAxis.data=this.anSchool.times
+                this.detailsEchart.line.series[0].data = tataldata1
+
+                //处理年纪占比
+                let Xdata = [];
+                if(lessonStats.gradeCnt.length >0){
+                    lessonStats.gradeCnt.forEach((item)=>{
+                        let nameNum = Number(item.name)
+                        let stuId = item.periodId
+                        let values = item.value
+                        for(let y in school.period){
+                            if(school.period[y].id === stuId){
+                                let names=school.period[y].grades[nameNum]
+                                Xdata.push({ name: names, value: values })
+                            }
+                        }
+                    })
+                this.detailsGrade = Xdata
+                }else{
+                    this.detailsGrade=[]
+                }
+                //处理科目占比
+                let subjectData = []
+                if(lessonStats.subCnt.length >0){
+                    lessonStats.subCnt.forEach((item)=>{
+                        let nameId = item.name
+                        let values = item.value
+                        for(let i in school.period){
+                            let phaseData = school.period[i].subjects
+                            for (let a in phaseData) {
+                                if (phaseData[a].id === nameId) {
+                                    subjectData.push({ name: phaseData[a].name, value: values })
+                                }
+                            }
+                        }
+                    })
+                    this.detailsEchart.subject.series[0].data = subjectData    
+                }else{
+                    this.detailsEchart.subject.series[0].data =[]    
+                }
+                this.detailsLoding=false
+            }
+            }).catch((error)=>{
+                this.$Message.error(error)
+            })
         }
     }
 }
@@ -706,6 +831,9 @@ export default {
   text-align: center;
   margin-bottom: 2px;
   margin-top: 2%;
+  display: flex;
+  justify-content: center;
+  align-items: center;
 }
 .school-analyse-headersbox-basics {
   width: 100%;
@@ -889,6 +1017,16 @@ export default {
     color: #fff;
     margin-right:5px;
 }
+.hours{
+    font-size:20px;
+    color:#409EFF;
+    margin-left:2px;
+}
+.school-analyse-headersbox-name img{
+    width:55px;
+    height:55px;
+    margin-right:1%;
+}
 .purples {
   /* background: rgba(112, 103, 245, 0.3); */
   background-image: linear-gradient(62deg, #8EC5FC 0%, #E0C3FC 100%);

+ 0 - 0
TEAMModelOS/ClientApp/src/view/elegant/BaseElegantCloud.vue


+ 219 - 0
TEAMModelOS/ClientApp/src/view/elegant/BaseElegantDash.vue

@@ -0,0 +1,219 @@
+<template>
+	<div class="elegant-dash-container">
+		<!-- <div class="title">
+			<span>数据总览</span>
+			<span class="btn-details" @click="goDetails">数据详情 ></span>
+		</div> -->
+		<div class="count-wrap">
+			<div class="count-item">
+				<p class="label">全部活动数</p>
+				<p class="value">41</p>
+                <img src="../../assets/source/folder.png">
+			</div>
+			<div class="count-item">
+				<p class="label">德育风采数</p>
+				<p class="value">23</p>
+                <img src="../../assets/mark/5.png" style="width: 70px">
+			</div>
+			<div class="count-item">
+				<p class="label">艺术特色数</p>
+				<p class="value">18</p>
+                <img src="../../assets/mark/7.png" style="width: 70px">
+			</div>
+			<div class="count-item">
+				<p class="label">图片总数</p>
+				<p class="value">42</p>
+                <img src="../../assets/source/image.png">
+			</div>
+			<div class="count-item">
+				<p class="label">视频总数</p>
+				<p class="value">18</p>
+                <img src="../../assets/source/video.png">
+			</div>
+			<div class="count-item">
+				<p class="label">文档总数</p>
+				<p class="value">48</p>
+                <img src="../../assets/source/pdf.png">
+			</div>
+		</div>
+		<div class="chart-wrap">
+			<div class="chart-block">
+				<div class="chart-title">
+					<p class="title">艺术特色素材类型</p>
+				</div>
+				<div class="chart-content">
+					<BasePie echartsId="pie1"></BasePie>
+				</div>
+			</div>
+			<div class="chart-block chart-right">
+				<div class="chart-title">
+					<p class="title">艺术特色素材类型</p>
+				</div>
+				<div class="chart-content">
+					<BaseBar echartsId="bar1"></BaseBar>
+				</div>
+			</div>
+		</div>
+		<div class="chart-wrap">
+			<div class="chart-block">
+				<div class="chart-title">
+					<p class="title">德育风采素材类型</p>
+				</div>
+				<div class="chart-content">
+					<BasePie echartsId="pie2"></BasePie>
+				</div>
+			</div>
+			<div class="chart-block chart-right">
+				<div class="chart-title">
+					<p class="title">德育风采素材类型</p>
+				</div>
+				<div class="chart-content">
+					<BaseBar echartsId="bar2"></BaseBar>
+				</div>
+			</div>
+		</div>
+		<div class="chart-wrap">
+			<div class="chart-block" style="width: 49.5%">
+				<div class="chart-title">
+					<p class="title">德育风采文字云</p>
+				</div>
+				<div class="chart-content">
+					<!-- <BaseUploadLine></BaseUploadLine> -->
+				</div>
+			</div>
+			<div class="chart-block" style="width: 49.5%; margin-left: 1%">
+				<div class="chart-title">
+					<p class="title">艺术特色文字云</p>
+				</div>
+				<div class="chart-content">
+					<!-- <BaseUploadLine></BaseUploadLine> -->
+				</div>
+			</div>
+		</div>
+		<div class="chart-wrap">
+			<div class="chart-block" style="width: 100%">
+				<div class="chart-title">
+					<p class="title">素材上传趋势图</p>
+				</div>
+				<div class="chart-content">
+					<BaseUploadLine></BaseUploadLine>
+				</div>
+			</div>
+		</div>
+	</div>
+</template>
+
+<script>
+	import BasePie from "./BaseTypePie.vue";
+	import BaseBar from "./BaseTypeBar.vue";
+	import BaseUploadLine from "./BaseUploadLine.vue";
+	export default {
+		components: {
+			BasePie,
+			BaseBar,
+			BaseUploadLine
+		},
+		methods: {
+			goDetails() {
+				this.$emit("goDetails");
+			}
+		}
+	};
+</script>
+
+<style lang="less">
+	.elegant-dash-container {
+		// padding: 30px 50px;
+		// background: #eeeef0;
+		// .title {
+		// 	font-size: 26px;
+		// 	margin-left: 3px;
+		// 	margin-bottom: 20px;
+		// 	display: flex;
+		// 	align-items: center;
+
+		// 	.btn-details {
+		// 		display: inline-block;
+		// 		font-size: 12px;
+		// 		border: 1px solid #2787e0;
+		// 		padding: 5px 10px;
+		// 		border-radius: 50px;
+		// 		margin-left: 10px;
+		// 		color: #0d78be;
+		// 		cursor: pointer;
+		// 	}
+		// }
+		.count-wrap {
+			display: flex;
+			justify-content: space-between;
+			.count-item {
+				width: 15.8%;
+				background-color: #fff;
+				border-radius: 10px;
+				display: flex;
+				flex-direction: column;
+				justify-content: space-between;
+				padding: 20px;
+                position: relative;
+				.label {
+					font-size: 14px;
+					color: #818181;
+					margin-bottom: 20px;
+				}
+				.value {
+					font-size: 28px;
+					font-weight: bold;
+					color: #0d78be;
+					letter-spacing: 1px;
+				}
+                img{
+                    width: 60px;
+                    position: absolute;
+                    bottom: 20px;
+                    right: 20px;
+                    opacity: .3;
+                }
+			}
+		}
+		.chart-wrap {
+			display: flex;
+			margin: 1% 0;
+
+			.chart-block {
+				width: 28%;
+				height: 440px;
+				background-color: #fff;
+				border-radius: 10px;
+				display: flex;
+				flex-direction: column;
+				justify-content: space-between;
+				padding: 20px;
+				padding-bottom: 30px;
+
+				.title {
+					font-size: 14px;
+                    display: flex;
+                    align-items: center;
+					&::before {
+						content: "";
+						display: inline-block;
+						border: 3px solid #0d78be;
+						border-radius: 4px;
+                        height: 14px;
+						margin-right: 10px;
+					}
+				}
+
+				.chart-content {
+					height: 100%;
+					width: 100%;
+				}
+			}
+
+			.chart-right {
+				width: 71%;
+				margin-left: 1%;
+			}
+		}
+	}
+</style>

+ 127 - 0
TEAMModelOS/ClientApp/src/view/elegant/BaseTypeBar.vue

@@ -0,0 +1,127 @@
+<template>
+	<div :id='echartsId' class="art-echart"></div>
+</template>
+<script>
+	export default {
+        props: ['echartsId'],
+		data() {
+			return {
+				option: null,
+				stuIndex: 0,
+				average: 0,
+				classStuArr: []
+			};
+		},
+		methods: {
+			doRender(yData) {
+				let myChart = this.$echarts.init(document.getElementById(this.echartsId));
+				let that = this;
+				var colorList = {
+					type: "linear",
+					x: 0,
+					y: 0,
+					x2: 0,
+					y2: 1,
+					colorStops: [
+						{
+							offset: 0,
+							color: "#06DBF5" // 0% 处的颜色
+						},
+						{
+							offset: 1,
+							color: "#00d386" // 100% 处的颜色
+						}
+					],
+					globalCoord: false // 缺省为 false
+				};
+				let option = {
+					backgroundColor: "#fff",
+					tooltip: {
+						trigger: "axis",
+						axisPointer: {
+							// 坐标轴指示器,坐标轴触发有效
+							type: "shadow" // 默认为直线,可选为:'line' | 'shadow'
+						}
+					},
+					grid: {
+						left: "3%",
+						right: "4%",
+						bottom: "0%",
+						containLabel: true
+					},
+					xAxis: {
+						type: "category",
+						data: that.echartsId === 'bar1' ? [ "演奏", "影视", "舞蹈", "戏剧", "常规活动", "获奖活动"] : ["读书分享","思想沙龙","文学创作","社会服务","文化交流","思德教育","反思日志","小组合作","行为习惯挑战"],
+						// axisTick: {
+						//     alignWithLabel: true
+						// }
+						axisLine: {
+							lineStyle: {
+								color: "#333"
+							}
+						},
+						axisLabel: {
+							interval: 0,
+							textStyle: {
+								fontFamily: "Hm"
+							}
+						}
+					},
+
+					yAxis: {
+						type: "value",
+						axisLine: {
+							lineStyle: {
+								color: "#333"
+							}
+						},
+						splitLine: {
+							show: true,
+							lineStyle: {
+								color: "rgba(255,255,255,0.3)"
+							}
+						},
+						axisLabel: {
+							textStyle: {
+								fontFamily: "Hm"
+							}
+						}
+					},
+
+					series: [
+						{
+							name: "",
+							type: "bar",
+							barWidth: "30",
+							itemStyle: {
+								color: function (params) {
+									return colorList;
+								}
+							},
+							emphasis: {
+								itemStyle: {
+									color: "#FBB419"
+								}
+							},
+							data: [154,132,112,62,55,41,22,32,10,112,62,55,41,22,32,10]
+						}
+					]
+				};
+				myChart.clear();
+				myChart.setOption(option);
+			}
+		},
+		mounted() {
+			this.doRender();
+		}
+	};
+</script>
+
+<style>
+	.art-echart {
+		width: 100%;
+		height: 100%;
+		margin: 0 auto;
+		display: block;
+	}
+</style>

+ 116 - 0
TEAMModelOS/ClientApp/src/view/elegant/BaseTypePie.vue

@@ -0,0 +1,116 @@
+<template>
+	<div :id='echartsId' class="art-echart"></div>
+</template>
+<script>
+	export default {
+        props: ['echartsId'],
+		data() {
+			return {
+				option: null,
+				stuIndex: 0,
+				average: 0,
+				classStuArr: []
+			};
+		},
+		methods: {
+			doRender(yData) {
+				let myChart = this.$echarts.init(document.getElementById(this.echartsId));
+				let that = this;
+				var data = [
+					{
+						value: 6,
+						name: this.echartsId === 'pie1' ? "课程活动" : "理想信念"
+					},
+					{
+						value: 3,
+						name: this.echartsId === 'pie1' ? "艺术社团" : "社会责任"
+					},
+					{
+						value: 8,
+						name: this.echartsId === 'pie1' ? "艺术活动" : "行为习惯"
+					}
+				];
+				let option = {
+					title: {
+						text: this.echartsId === 'pie1' ? "23" : "18",
+						subtext: "活动总数",
+						x: "center",
+						y: "center",
+						textStyle: {
+							fontWeight: "600",
+							fontFamily: "Hm",
+							fontSize: 28
+						},
+						subtextStyle: {
+							fontWeight: "normal",
+							fontFamily: "Hm"
+						}
+					},
+					grid: {
+						bottom: "10%",
+						top: "12%",
+						containLabel: true
+					},
+					tooltip: {
+						show: true,
+						trigger: "item",
+						formatter: "{b}: {c} ({d}%)",
+						textStyle: {
+							fontWeight: "normal",
+							fontFamily: "Hm"
+						}
+					},
+					legend: {
+						orient: "horizontal",
+						textStyle: {
+							fontWeight: "normal",
+							fontFamily: "Hm"
+						},
+						bottom: "0%",
+						data: that.echartsId === 'pie1' ? ["课程活动", "艺术社团", "艺术活动"] : ["理想信念","社会责任","行为习惯"]
+					},
+					series: [
+						{
+							type: "pie",
+							selectedMode: "single",
+							radius: ["38%", "65%"],
+							color: ["#86D560", "#AF89D6", "#59ADF3"],
+							label: {
+								normal: {
+									position: "inner",
+									formatter: "{d}%",
+									textStyle: {
+										color: "#fff",
+										fontWeight: "bold",
+										fontFamily: "Hm",
+										fontSize: 12
+									}
+								}
+							},
+							labelLine: {
+								normal: {
+									show: false
+								}
+							},
+							data: data
+						}
+					]
+				};
+				myChart.clear();
+				myChart.setOption(option);
+			}
+		},
+		mounted() {
+			this.doRender();
+		}
+	};
+</script>
+
+<style>
+	.art-echart {
+		width: 100%;
+		height: 100%;
+		margin: 0 auto;
+		display: block;
+	}
+</style>

+ 216 - 0
TEAMModelOS/ClientApp/src/view/elegant/BaseUploadLine.vue

@@ -0,0 +1,216 @@
+<template>
+	<div id="BaseUploadLine" class="art-echart"></div>
+</template>
+<script>
+	export default {
+		data() {
+			return {
+				option: null,
+				stuIndex: 0,
+				average: 0,
+				classStuArr: []
+			};
+		},
+		methods: {
+			doRender(yData) {
+				let myChart = this.$echarts.init(document.getElementById("BaseUploadLine"));
+
+				let color = ["#8B5CFF", "#00CA69"];
+
+				let xAxisData = ["1", "2", "3", "4", "5", "6", "7", "8"];
+				let yAxisData1 = [100, 138, 350, 173, 180, 150, 180, 230];
+				let yAxisData2 = [233, 233, 200, 180, 199, 233, 210, 180];
+
+				const hexToRgba = (hex, opacity) => {
+					let rgbaColor = "";
+					let reg = /^#[\da-f]{6}$/i;
+					if (reg.test(hex)) {
+						rgbaColor = `rgba(${parseInt("0x" + hex.slice(1, 3))},${parseInt("0x" + hex.slice(3, 5))},${parseInt("0x" + hex.slice(5, 7))},${opacity})`;
+					}
+					return rgbaColor;
+				};
+				let option = {
+					color: color,
+					legend: {
+						top: 20
+					},
+					tooltip: {
+						trigger: "axis",
+						formatter: function (params) {
+							let html = "";
+							params.forEach((v) => {
+								html += `<div style="color: #666;font-size: 14px;line-height: 24px">
+	                <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${color[v.componentIndex]};"></span>
+	                ${v.seriesName}2020.${v.name}
+	                <span style="color:${color[v.componentIndex]};font-weight:700;font-size: 18px;margin-left:5px">${v.value}</span>
+	                个`;
+							});
+							return html;
+						},
+						extraCssText: "background: #fff; border-radius: 0;box-shadow: 0 0 3px rgba(0, 0, 0, 0.2);color: #333;",
+						axisPointer: {
+							type: "shadow",
+							shadowStyle: {
+								color: "#ffffff",
+								shadowColor: "rgba(225,225,225,1)",
+								shadowBlur: 5
+							}
+						}
+					},
+					grid: {
+						left: "2%",
+						right: "2%",
+						bottom: "0",
+						containLabel: true
+					},
+					xAxis: [
+						{
+							type: "category",
+							axisLabel: {
+								margin: 20,
+								formatter: "第{value}周",
+								textStyle: {
+									color: "#333",
+									fontFamily: "Hm"
+								}
+							},
+							axisLine: {
+								lineStyle: {
+									color: "#D9D9D9"
+								}
+							},
+							data: xAxisData
+						}
+					],
+					yAxis: [
+						{
+							type: "value",
+							name: "单位(个)",
+							axisLabel: {
+								textStyle: {
+									color: "#666"
+								}
+							},
+							nameTextStyle: {
+								color: "#666",
+								fontSize: 12,
+								lineHeight: 40
+							},
+							// 分割线
+							splitLine: {
+								lineStyle: {
+									type: "dashed",
+									color: "#E9E9E9"
+								}
+							},
+							axisLine: {
+								show: false
+							},
+							axisTick: {
+								show: false
+							}
+						}
+					],
+					series: [
+						{
+							// name: "2018",
+							name: "德育风采",
+							type: "line",
+							smooth: true,
+							symbolSize: 8,
+							zlevel: 3,
+							lineStyle: {
+								normal: {
+									color: color[0],
+									shadowBlur: 3,
+									shadowColor: hexToRgba(color[0], 0.5),
+									shadowOffsetY: 8
+								}
+							},
+							symbol: "circle", //数据交叉点样式
+							areaStyle: {
+								normal: {
+									color: new echarts.graphic.LinearGradient(
+										0,
+										0,
+										0,
+										1,
+										[
+											{
+												offset: 0,
+												color: hexToRgba(color[0], 0.3)
+											},
+											{
+												offset: 1,
+												color: hexToRgba(color[0], 0.1)
+											}
+										],
+										false
+									),
+									shadowColor: hexToRgba(color[0], 0.1),
+									shadowBlur: 10
+								}
+							},
+							data: yAxisData1
+						},
+						{
+							name: "艺术特色",
+							type: "line",
+							smooth: true,
+							symbolSize: 8,
+							zlevel: 3,
+							lineStyle: {
+								normal: {
+									color: color[1],
+									shadowBlur: 3,
+									shadowColor: hexToRgba(color[1], 0.5),
+									shadowOffsetY: 8
+								}
+							},
+							symbol: "circle", //数据交叉点样式 (实心点)
+							areaStyle: {
+								normal: {
+									color: new echarts.graphic.LinearGradient(
+										0,
+										0,
+										0,
+										1,
+										[
+											{
+												offset: 0,
+												color: hexToRgba(color[1], 0.3)
+											},
+											{
+												offset: 1,
+												color: hexToRgba(color[1], 0.1)
+											}
+										],
+										false
+									),
+									shadowColor: hexToRgba(color[1], 0.1),
+									shadowBlur: 10
+								}
+							},
+							data: yAxisData2
+						}
+					]
+				};
+
+				myChart.clear();
+				myChart.setOption(option);
+			}
+		},
+		mounted() {
+			this.doRender();
+		}
+	};
+</script>
+
+<style>
+	.art-echart {
+		width: 100%;
+		height: 100%;
+		margin: 0 auto;
+		display: block;
+	}
+</style>

+ 128 - 91
TEAMModelOS/ClientApp/src/view/elegant/Elegant.vue

@@ -1,61 +1,70 @@
 <template>
 	<div class="elegant-container">
 		<Spin fix v-if="isLoading"></Spin>
-		<div class="header">
-			<span class="title">学生风采</span>
-			<div>
-				<Button type="success" size="small" @click="onDownloadExcel" icon="md-download" style="margin-right: 10px">导出数据</Button>
-				<Button type="success" size="small" @click="onAddElegant">+ 添加素材</Button>
+		<div class="elegant-details-box">
+			<div class="container-title">
+				<div style="display: flex; align-items: center">
+					<span>{{isShowDash ? '数据总览' : '数据详情'}}</span>
+					<span class="btn-details" @click="isShowDash = !isShowDash">{{!isShowDash ? '数据总览' : '数据详情'}} ></span>
+				</div>
+				<div class="tools">
+					<Button shape="circle" @click="onAddElegant" icon="md-add">添加素材</Button>
+					<Button shape="circle" @click="onDownloadExcel" icon="md-download" style="margin-left: 10px">导出数据</Button>
+				</div>
+			</div>
+			<ElegantDash v-if="isShowDash" @goDetails="isShowDash = false"></ElegantDash>
+			<div class="details-wrap" v-if="!isShowDash">
+				<div class="filter-wrap">
+					<!-- 类型筛选 -->
+					<Select v-model="filterTypeIndex" style="width: 200px" @on-change="onFilterTypeChange">
+						<Option v-for="(item, index) in typeList" :value="index" :key="index">
+							{{ item }}
+						</Option>
+					</Select>
+				</div>
+				<div class="elegant-list">
+					<EmptyData :top="300" v-if="!elegantList.length"></EmptyData>
+					<Timeline v-else>
+						<TimelineItem v-for="(item, index) in elegantList" :key="index">
+							<p class="elegant-title">
+								<span>{{ item.title }}</span>
+								<span style="margin: 0 10px">
+									<Tag color="geekblue" v-if="item.bizType">{{ item.bizType.join("-") }}</Tag>
+									<Tag color="green" v-if="item.classes && item.classes.length">{{ getClassNameById(item.classes[0]) }}</Tag>
+									<Tag color="primary">{{ $tools.formatTime(item.createTime) }}</Tag>
+								</span>
+								<!-- <Icon type="md-create" color="#2d8cf0" @click="onEditElegant(item,index)"></Icon> -->
+								<Icon type="md-trash" color="#2d8cf0" @click="onDelElegant(item, index)"></Icon>
+							</p>
+							<p class="elegant-content">{{ item.content }}</p>
+							<div class="img-list" v-if="item.fileType === 'image'">
+								<div class="img-item" v-for="(img, imgIndex) in item.attachments" :key="imgIndex" @click="onImgClick(item.attachments, imgIndex)">
+									<img :src="getFullPath(img.url)" alt="" />
+								</div>
+							</div>
+							<div class="img-list" v-if="item.fileType === 'video'">
+								<div class="img-item" v-for="(img, imgIndex) in item.attachments" :key="imgIndex">
+									<video :src="getFullPath(img.url)" style="width: 300px" controls="controls"></video>
+								</div>
+							</div>
+							<div class="file-list" v-if="item.fileType === 'doc'">
+								<div class="file-item" v-for="(item, imgIndex) in item.attachments" :key="imgIndex" @click="onPreview(item)">
+									<img src="../../assets/source/word.png" v-if="item.type === 'doc' && docType.includes(getSuffix(item.blob))" />
+									<img src="../../assets/source/excel.png" v-else-if="item.type === 'doc' && excelType.includes(getSuffix(item.name))" />
+									<img src="../../assets/source/ppt.png" v-else-if="item.type === 'doc' && pptType.includes(getSuffix(item.name))" />
+									<img src="../../assets/source/pdf.png" v-else-if="item.type === 'doc' && getSuffix(item.name) === 'pdf'" />
+									<img src="../../assets/source/zip.png" v-else-if="getSuffix(item.name) === 'zip' || getSuffix(item.name) === 'rar'" />
+									<img src="../../assets/source/audio.png" v-else-if="item.type === 'audio'" />
+									<img src="../../assets/source/unknow.png" v-else />
+									<p>{{ item.name }}</p>
+								</div>
+							</div>
+						</TimelineItem>
+					</Timeline>
+				</div>
 			</div>
 		</div>
-		<div class="filter-wrap">
-			<!-- 类型筛选 -->
-			<Select v-model="filterTypeIndex" style="width:200px;"  @on-change="onFilterTypeChange">
-				<Option v-for="(item,index) in typeList" :value="index" :key="index">
-					{{ item }}
-				</Option>
-			</Select>
-		</div>
-		<div class="elegant-list">
-			<EmptyData :top="300" v-if="!elegantList.length"></EmptyData>
-			<Timeline v-else>
-				<TimelineItem v-for="(item, index) in elegantList" :key="index">
-					<p class="elegant-title">
-						<span>{{ item.title }}</span>
-						<span style="margin: 0 10px">
-							<Tag color="geekblue" v-if="item.bizType">{{ item.bizType.join("-") }}</Tag>
-							<Tag color="green" v-if="item.classes && item.classes.length">{{ getClassNameById(item.classes[0]) }}</Tag>
-							<Tag color="primary">{{ $tools.formatTime(item.createTime) }}</Tag>
-						</span>
-						<!-- <Icon type="md-create" color="#2d8cf0" @click="onEditElegant(item,index)"></Icon> -->
-						<Icon type="md-trash" color="#2d8cf0" @click="onDelElegant(item, index)"></Icon>
-					</p>
-					<p class="elegant-content">{{ item.content }}</p>
-					<div class="img-list" v-if="item.fileType === 'image'">
-						<div class="img-item" v-for="(img, imgIndex) in item.attachments" :key="imgIndex" @click="onImgClick(item.attachments, imgIndex)">
-							<img :src="getFullPath(img.url)" alt="" />
-						</div>
-					</div>
-					<div class="img-list" v-if="item.fileType === 'video'">
-						<div class="img-item" v-for="(img, imgIndex) in item.attachments" :key="imgIndex">
-							<video :src="getFullPath(img.url)" style="width: 300px" controls="controls"></video>
-						</div>
-					</div>
-					<div class="file-list" v-if="item.fileType === 'doc'">
-						<div class="file-item" v-for="(item, imgIndex) in item.attachments" :key="imgIndex" @click="onPreview(item)">
-							<img src="../../assets/source/word.png" v-if="item.type === 'doc' && docType.includes(getSuffix(item.blob))" />
-							<img src="../../assets/source/excel.png" v-else-if="item.type === 'doc' && excelType.includes(getSuffix(item.name))" />
-							<img src="../../assets/source/ppt.png" v-else-if="item.type === 'doc' && pptType.includes(getSuffix(item.name))" />
-							<img src="../../assets/source/pdf.png" v-else-if="item.type === 'doc' && getSuffix(item.name) === 'pdf'" />
-							<img src="../../assets/source/zip.png" v-else-if="getSuffix(item.name) === 'zip' || getSuffix(item.name) === 'rar'" />
-							<img src="../../assets/source/audio.png" v-else-if="item.type === 'audio'" />
-							<img src="../../assets/source/unknow.png" v-else />
-							<p>{{ item.name }}</p>
-						</div>
-					</div>
-				</TimelineItem>
-			</Timeline>
-		</div>
+
 		<Drawer :title="isEdit ? '编辑素材' : '添加素材'" :closable="false" v-model="editModal" width="520" :transfer="false" @on-visible-change="onDrawerChange">
 			<Form :model="curElegantItem" label-position="top" v-if="curElegantItem">
 				<FormItem :label="`活动名称`">
@@ -154,13 +163,18 @@
 <script>
 	import BlobTool from "@/utils/blobTool.js";
 	import excel from "@/utils/excel.js";
+	import ElegantDash from "./BaseElegantDash.vue";
 	export default {
+		components: {
+			ElegantDash
+		},
 		data() {
 			return {
-				isLoading:false,
-				allList:[],
-				typeList:['全部风采','德育风采','艺术特色'],
-				filterTypeIndex:0,
+				isShowDash: true,
+				isLoading: false,
+				allList: [],
+				typeList: ["全部风采", "德育风采", "艺术特色"],
+				filterTypeIndex: 0,
 				props: {
 					multiple: false,
 					value: "id",
@@ -177,7 +191,7 @@
 				btnLoading: false,
 				fileArr: [],
 				priviewSrc: "",
-				originList:[],
+				originList: [],
 				imgFilePreviewList: [],
 				videoFilePreviewList: [],
 				docFilePreviewList: [],
@@ -254,27 +268,27 @@
 					etime: null //可选
 				})
 				.then((res) => {
-					this.originList = res.elegants.reverse()
+					this.originList = res.elegants.reverse();
 					this.onFilterTypeChange();
 					this.getTargetList();
 				});
 		},
 		methods: {
-			onDownloadExcel(){
-				this.isLoading = true
+			onDownloadExcel() {
+				this.isLoading = true;
 				let schoolName = this.$store.state.user.schoolProfile.school_base.name;
 				let periodName = this.curPeriod.name;
-				let list = this.originList.map(i => {
+				let list = this.originList.map((i) => {
 					return {
 						schoolName: schoolName,
 						className: this.getClassNameById(i.classes[0]),
 						classId: i.classes[0],
-						bizType: i.bizType ? i.bizType.join('-') : '-', 
-						title:i.title,
-						content:i.content,
+						bizType: i.bizType ? i.bizType.join("-") : "-",
+						title: i.title,
+						content: i.content,
 						time: this.$tools.formatTime(i.createTime)
-					}
-				})
+					};
+				});
 				const params = {
 					title: ["学校名称", "班级名称", "班级ID", "素材类别", "活动名称", "活动描述", "活动时间"],
 					key: ["schoolName", "className", "classId", "bizType", "title", "content", "time"],
@@ -285,9 +299,9 @@
 				excel.export_array_to_excel(params);
 				this.isLoading = false;
 			},
-			onFilterTypeChange(){
-				console.log(this.allList)
-				this.elegantList = this.filterTypeIndex === 0 ? this._.cloneDeep(this.originList) : this.originList.filter(i => i.bizType && i.bizType.includes(this.typeList[this.filterTypeIndex]))
+			onFilterTypeChange() {
+				console.log(this.allList);
+				this.elegantList = this.filterTypeIndex === 0 ? this._.cloneDeep(this.originList) : this.originList.filter((i) => i.bizType && i.bizType.includes(this.typeList[this.filterTypeIndex]));
 			},
 			onPreview(file) {
 				let fullLink = this.getFullPath(file.url);
@@ -317,7 +331,7 @@
 			},
 			getTargetList() {
 				if (!this.curPeriod?.id) return;
-				this.isLoading = true
+				this.isLoading = true;
 				let params = {
 					tmdid: this.$store.state.userInfo.TEAMModelId,
 					schoolId: this.$store.state.userInfo.schoolCode,
@@ -327,11 +341,11 @@
 				this.$api.common.getActivityTarget(params).then(
 					(res) => {
 						this.allList = res.groupLists;
-						this.isLoading = false
+						this.isLoading = false;
 					},
 					(err) => {
 						this.$Messag.error(this.$t("ae.ae15"));
-						this.isLoading = false
+						this.isLoading = false;
 					}
 				);
 			},
@@ -535,10 +549,10 @@
 			}
 		},
 		computed: {
-			getClassNameById(){
-				return id => {
-					return this.allList.length ? this.allList.find(i => i.id === id)?.name : ''
-				}
+			getClassNameById() {
+				return (id) => {
+					return this.allList.length ? this.allList.find((i) => i.id === id)?.name : "";
+				};
 			},
 			getSuffix() {
 				return (name) => {
@@ -615,27 +629,50 @@
 			"$store.state.user.curSemester": {
 				deep: true,
 				handler(n, old) {
-          			this.getTargetList()
+					this.getTargetList();
 				}
 			}
-		},	
+		}
 	};
 </script>
 
 <style lang="less">
 	.elegant-container {
 		height: 100%;
-		.header {
-			width: 100%;
-			display: flex;
-			justify-content: space-between;
-			align-items: center;
-			padding: 10px 15px;
-			border-bottom: 1px solid rgba(204, 204, 204, 0.377);
-			font-size: 16px;
+		background: #eeeef0;
 
-			.title {
-				font-weight: bold;
+		.elegant-details-box {
+			padding: 30px 50px;
+			background: #eeeef0;
+
+			.filter-wrap {
+				padding: 0 0 40px 0;
+			}
+
+			.container-title {
+				font-size: 26px;
+				margin-left: 3px;
+				margin-bottom: 20px;
+				display: flex;
+				align-items: center;
+				justify-content: space-between;
+
+				.btn-details {
+					display: inline-block;
+					font-size: 12px;
+					border: 1px solid #2787e0;
+					padding: 5px 10px;
+					border-radius: 50px;
+					margin-left: 10px;
+					color: #0d78be;
+					cursor: pointer;
+				}
+			}
+
+			.details-wrap {
+				background: #fff;
+				padding: 20px;
+				border-radius: 10px;
 			}
 		}
 
@@ -649,8 +686,8 @@
 			display: flex;
 			justify-content: space-between;
 			align-items: center;
-			padding: 15px;
 			overflow: auto;
+			background: #fff;
 
 			.ivu-timeline {
 				height: 100%;
@@ -680,7 +717,7 @@
 			}
 		}
 
-		.ivu-timeline-item{
+		.ivu-timeline-item {
 			padding-bottom: 40px !important;
 		}
 		.file-list {

+ 7 - 0
TEAMModelOS/ClientApp/src/view/evaluation/components/BaseExerciseList.vue

@@ -558,6 +558,8 @@ export default {
      * @param item
      */
     handleToolEdit(arr, item, index) {
+      console.error(this.errorList)
+      console.error(item)
       this.currentExerciseIndex = this.exerciseList.indexOf(item) // 清单列表下的index
       this.curOrderIndex = index
       if (item.scope === 'school') {
@@ -788,6 +790,11 @@ export default {
         preOrderList.splice(this.curOrderIndex, 1, item)
         this.paper.item = preOrderList
       }
+      /* 如果编辑好的题目是之前错误的题目 则移除掉 */
+      let isErrorItemIndex = this.errorList.findIndex(i => i.id === item.id)
+      if(isErrorItemIndex > -1){
+        this.errorList.splice(isErrorItemIndex, 1)
+      }
     },
 
 

+ 0 - 2
TEAMModelOS/ClientApp/src/view/evaluation/types/BaseJudge.vue

@@ -74,8 +74,6 @@
 		watch:{
 			editInfo:{
 				handler(n){
-					console.log('主观题富文本接收到的数据')
-					console.log(n)
 					if(n){
 						this.stemEditor.txt.html(this.editInfo.question)
 						this.stemContent = this.editInfo.question

+ 2 - 1
TEAMModelOS/ClientApp/src/view/evaluation/types/BaseMultiple.vue

@@ -297,11 +297,12 @@
 			this.$editorTools.initMyEditor(stemEditor,this)
 			stemEditor.create()
 			this.stemEditor = stemEditor
-			this.initEditors()
 
 			if (this.editInfo && this.isEdit) { 
 				console.log('进入多选题Mounted编辑')
 				this.doRender(this.editInfo)
+			}else{
+				this.initEditors()
 			}
 		},
 		computed: {

+ 2 - 1
TEAMModelOS/ClientApp/src/view/evaluation/types/BaseSingle.vue

@@ -248,7 +248,6 @@
 
 			stemEditor.create()
 			this.stemEditor = stemEditor
-			this.initEditors();
 			
 			if (this.editInfo && this.isEdit) {
 				console.log('进入单选题Mounted编辑',this.editInfo)
@@ -263,6 +262,8 @@
 					this.initEditors()
 					this.stemEditor.txt.html(this.editSingleInfo.question)
 				})
+			}else{
+				this.initEditors();
 			}
 		},
 		watch: {

+ 67 - 13
TEAMModelOS/ClientApp/src/view/iot/areaiot.vue

@@ -123,7 +123,7 @@
                     </dv-border-box-11>
                 </div>
                 <div class="restsbox-right">
-                    <dv-border-box-11 :title="$t('schoolIot.device.title')">
+                    <dv-border-box-11 title="数量与占比">
                         <!--设备统计-->
                         <!-- <div class="right-box">
                             <div class="right-box-left">
@@ -137,6 +137,9 @@
                             </div>
                         </div> -->
                          <!--设备统计 end-->
+                         <div class="total-solution">
+                            <Bar title="学期" :cdata="bars"></Bar>
+                         </div>
                     </dv-border-box-11>    
                 </div>
              </div>
@@ -147,7 +150,7 @@
                     <dv-border-box-12>
                         <div class="innerbox">
                             <p class="boxtitles">
-                                <span>{{$t('schoolIot.lessons.title')}}</span>
+                                <span>基础数据</span>
                                 <dv-decoration-3 style="width:200px;height:20px;"/>
                             </p>
                             <div class="innerbox-inside">
@@ -163,7 +166,7 @@
                                 <div class="data-left">
                                     <BaseCircle  circleId="webirs" chatName="WebIRS" :percent="40" subTitle="45" totalNum="77"></BaseCircle>
                                 </div> -->
-                                <barandLine :baldata="baldatas"></barandLine>
+                                <specialBarline  :basics="basicsData"></specialBarline>
                             </div>
                             <!-- <dv-decoration-2 :reverse="true" style="width:5px;height:95%;" :dur="5" /> -->
                             <!-- <div class="data-right">
@@ -178,7 +181,7 @@
                     </dv-border-box-12>    
                 </div>
                 <div class="right-integration">
-                    <div class="bottombox-right">
+                    <div class="bottombox-right ranks">
                         <dv-border-box-12>
                             <div class="innerbox">
                                 <p class="boxtitles">
@@ -196,11 +199,12 @@
                         <dv-border-box-12>
                             <div class="innerbox">
                                 <p class="boxtitles">
-                                    <span>{{$t('schoolIot.morphologyClass.title')}}</span>
+                                    <span>{{$t('schoolIot.lessons.title')}}</span>
                                     <dv-decoration-3 style="width:200px;height:20px;"/>
                                 </p>
                                 <div class="barbox">
-                                    <Bar title="学期" :cdata="bars"></Bar>
+                                    <!-- <specialBarline  :basics="basicsData"></specialBarline> -->
+                                    <barandLine :baldata="baldatas"></barandLine>
                                 </div>
                             </div>
                         </dv-border-box-12>    
@@ -220,6 +224,7 @@ import YPie from './echarts/pie/index'
 import Bar from './echarts/bar/bar'
 import BaseCircle from "./echarts/circle/index";
 import barandLine from './echarts/barandLine/barandLine'
+import specialBarline from './echarts/barandLine/specialBarline.vue';
 export default {
    name:'areaiot',
    components: {
@@ -228,7 +233,8 @@ export default {
     YPie,
     Bar,
     BaseCircle,
-    barandLine
+    barandLine,
+    specialBarline
   },
    data(){
     return{
@@ -315,6 +321,15 @@ export default {
         },
         schoolList: [],
         baldatas: [],
+        basicsData:{
+         rooms:[],
+         teachs:[],
+         students:[],
+         classInfo:[],
+         classTimes:[],
+         classStudenttimes:[],
+         weekNums:0,
+      },
     }
    },
     mounted() {
@@ -464,6 +479,35 @@ export default {
          newArrs.data=newArr
         //  this.config.data = newArr
          this.config = newArrs
+         //处理基础数据
+         let basicsTotal=[]
+          for (let i = 1; i <= weekNum; i++){
+            basicsTotal.push({week:i,room:0,teach:0,student:0,class:0,classTime:0,classStudenttime:0,deviceList:[],tmidList:[]})
+          }
+          res.iotData.forEach((item)=>{
+            let times = new Date(item.year + '-' + item.month + '-' + item.day)
+            let returnWeek = this.calculateWeekNumber(startime, times)
+            let reresultIndex = basicsTotal.findIndex((item) => { return item.week === returnWeek })
+            item.deviceList.forEach((itemA)=>{ basicsTotal[reresultIndex].deviceList.push(itemA)})
+            item.tmidList.forEach((itemS)=>{basicsTotal[reresultIndex].tmidList.push(itemS)})
+            basicsTotal[reresultIndex].student +=item.stuShow
+            basicsTotal[reresultIndex].class +=item.lessonRecord
+            basicsTotal[reresultIndex].classTime +=item.lessonLengMin
+            basicsTotal[reresultIndex].classStudenttime +=item.stuLessonLengMin
+          })
+          basicsTotal.forEach((item)=>{
+            item.deviceList=[...new Set(item.deviceList)]
+            item.room=item.deviceList.length
+            item.tmidList=[...new Set(item.tmidList)]
+            item.teach=item.tmidList.length
+          })
+           this.basicsData.rooms= basicsTotal.map(item =>item.room)
+           this.basicsData.teachs=basicsTotal.map(item=>item.teach)
+           this.basicsData.students=basicsTotal.map(item=>item.student)
+           this.basicsData.classInfo=basicsTotal.map(item=>item.class)
+           this.basicsData.classTimes=basicsTotal.map(item=>item.classTime)
+           this.basicsData.classStudenttimes=basicsTotal.map(item=>item.classStudenttime)
+           this.basicsData.weekNums=this.basicsData.rooms.length
          this.loading=false
       })
      },
@@ -679,10 +723,10 @@ export default {
     justify-content: space-between;
 }
 .restsbox-left{
-    width:100%;
+    width:50%;
 }
 .restsbox-right{
-    width:0%;
+    width:50%;
 }
 .left-item{
   width: 21%;
@@ -692,7 +736,7 @@ export default {
   align-items: center;
   border-radius: 5px;
   background-color: rgba(19, 25, 47, 0.6);
-  margin: 4% 2% 1% 2%;
+  margin: 8% 2% 1% 2%;
 }
 .item-img {
   width: 30%;
@@ -757,7 +801,7 @@ export default {
     height:50vh;
 }
 .bottombox-left{
-    width:55%;
+    width:50%;
     display: flex;
 }
 .innerbox{
@@ -777,7 +821,7 @@ export default {
 }
 .bottombox-right{
     width:100%;
-    height:50%;
+    height:60%;
 }
 .data-left,.data-right{
     width:50%;
@@ -842,7 +886,7 @@ export default {
     line-height: 30px !important;
 }
 .right-integration{
-    width:45%;
+    width:50%;
     display: flex;
     flex-wrap: wrap;
 }
@@ -860,6 +904,16 @@ export default {
 .item-nums-special p .timetag{
     margin:0px 10px;
 }
+.total-solution{
+    width:100%;
+    height:73%;
+    margin:0% 2%;
+    background-color: rgba(19, 25, 47, 0.6);
+    margin-top:5%;
+}
+.ranks{
+    height:40% !important;
+}
 </style>
 <style>
 .schooliotbox .topbox  .border-box-content,.schooliotbox .restsbox .border-box-content{

+ 1 - 1
TEAMModelOS/ClientApp/src/view/iot/echarts/bar/bar.vue

@@ -146,7 +146,7 @@
 							top:'15%',
 							left:'7%',
 							right:'3%',
-							bottom:'8%'
+							bottom:'11%'
 						},
 						toolbox: {
 							show: false

+ 15 - 9
TEAMModelOS/ClientApp/src/view/iot/echarts/barandLine/specialBarline.vue

@@ -135,7 +135,7 @@
               textStyle: {
                 color: '#90979c',
               },
-              data: ['教室数','教师数','学生参与人数','课堂总数','课堂总时数','学生参与总时数']
+              data: [this.$t('schoolIot.basicsChat.roomnum'),this.$t('schoolIot.basicsChat.teachnum'),this.$t('schoolIot.basics.studentnums'),this.$t('schoolIot.basics.classroomTotal'),this.$t('schoolIot.basics.classroomTime'),this.$t('schoolIot.basics.studentTime')]
             },
             calculable: true,
             xAxis: [{
@@ -232,7 +232,8 @@
             }],
             series: [
             {
-                name:'教室数',
+                //教室数
+                name:this.$t('schoolIot.basicsChat.roomnum'),
                 type:'bar',
                 barWidth: 10,
                 symbol: 'circle',
@@ -253,7 +254,8 @@
                 data:this.trendData.rooms
             },
             {
-                name:'教师数',
+                //教师数
+                name:this.$t('schoolIot.basicsChat.teachnum'),
                 type:'bar',
                 barWidth: 10,
                 symbol: 'circle',
@@ -275,7 +277,8 @@
                 data:this.transferJson.rooms
             },
             {
-                name:'学生参与人数',
+                //学生参与人次
+                name:this.$t('schoolIot.basics.studentnums'),
                 type:'bar',
                 // stack: '参与人数',
                 barWidth: 10,
@@ -297,7 +300,8 @@
                 data:this.transferJson.students
             },
             {
-                name:'课堂总数',
+                //课堂总数
+                name:this.$t('schoolIot.basics.classroomTotal'),
                 type:'bar',
                 // stack: '参与人数',
                 barWidth: 10,
@@ -318,8 +322,9 @@
                 },
                 data:this.transferJson.class
             },
-            { //作品数量
-            name: '课堂总时数',
+            { 
+            //课堂总时数
+            name:this.$t('schoolIot.basics.classroomTime'),
             type: 'line',
             yAxisIndex: 1,
             // smooth: true, //是否平滑曲线显示
@@ -366,8 +371,9 @@
             },
             data:this.transferJson.classtimes
             },
-            { //作品数量
-            name: '学生参与总时数',
+            { 
+            //学生参与总时数
+            name:this.$t('schoolIot.basics.studentTime'),
             type: 'line',
             yAxisIndex: 1,
             // smooth: true, //是否平滑曲线显示

+ 3 - 4
TEAMModelOS/ClientApp/src/view/iot/schooliot.vue

@@ -94,7 +94,7 @@
                     </dv-border-box-11>
                 </div>
                 <div class="restsbox-right">
-                    <dv-border-box-11 title="数量与占比">
+                    <dv-border-box-11 :title="$t('schoolIot.device.numAndproportion')">
                         <div class="total-solution">
                             <Bar title="学期" :cdata="bars"></Bar>
                         </div>
@@ -118,11 +118,10 @@
              <!--bottom-->
              <div class="bottombox">
                 <div class="bottombox-left">
-                      
                     <dv-border-box-12>
                         <div class="innerbox">
                             <p class="boxtitles">
-                                <span>基础数据</span>
+                                <span>{{$t('schoolIot.basicsChat.title')}}</span>
                                 <dv-decoration-3 style="width:200px;height:20px;"/>
                             </p>
                             <div class="barbox">
@@ -444,7 +443,7 @@ export default {
      },
      goBack() {
       this.$tools.exitFullscreen()
-      this.$router.push('/dashCenter')
+      this.$router.push('/home/homePage')
     },
    }
 }

+ 20 - 16
TEAMModelOS/Controllers/Common/ActivityController.cs

@@ -1393,26 +1393,30 @@ namespace TEAMModelOS.Controllers
                     
                      }
             }
-            if (tmdid == null  && !string.IsNullOrWhiteSpace($"{_token}"))
+            
+            if (tmdid == null   )
             {
-                var jwt = new JwtSecurityToken(_token.GetString());
-                if (JwtAuthExtension.ValidateAuthTokenRefresh(_token.GetString(), _option.JwtSecretKey))
+                if (!string.IsNullOrWhiteSpace($"{_token}"))
                 {
-                    tmdid = jwt.Payload.Sub;
-
-                    if (HttpContext.Request.Headers.TryGetValue("lang", out var _lang))
+                    var jwt = new JwtSecurityToken(_token.GetString());
+                    if (JwtAuthExtension.ValidateAuthTokenRefresh(_token.GetString(), _option.JwtSecretKey))
                     {
-                        head_lang = $"{_lang}";
+                        tmdid = jwt.Payload.Sub;
+
+                        if (HttpContext.Request.Headers.TryGetValue("lang", out var _lang))
+                        {
+                            head_lang = $"{_lang}";
+                        }
+                        jwt.Payload.TryGetValue("name", out name);
+                        jwt.Payload.TryGetValue("picture", out picture);
+                        jwt.Payload.TryGetValue("lang", out object _jwtlang);
+                        head_lang = !string.IsNullOrWhiteSpace($"{_jwtlang}") ? $"{_jwtlang}" : head_lang;
                     }
-                    jwt.Payload.TryGetValue("name", out name);
-                    jwt.Payload.TryGetValue("picture", out picture);
-                    jwt.Payload.TryGetValue("lang", out object _jwtlang);
-                    head_lang = !string.IsNullOrWhiteSpace($"{_jwtlang}") ? $"{_jwtlang}" : head_lang;
+                    else { return Ok(new { code = 2, msg = "Token验证失败" }); }
                 }
-                else { return Ok(new { code = 2, msg = "Token验证失败" }); }
-
+                else { return Ok(new { code = 3, msg = "凭证验证失败" }); }
             }
-            else { return Ok(new { code = 3, msg = "凭证验证失败" }); }
+           
             teacherInfo = await TeacherService.TeacherInfoLite(_azureCosmos,  $"{name}", $"{picture}", tmdid, _azureStorage, _option, _azureRedis, ip, _httpTrigger, head_lang);
             string sql = $"select value c from c where c.route='{_route}'";
             var result = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).GetList<ActivityWebsite>(sql, "ActivityWebsite");
@@ -1448,8 +1452,8 @@ namespace TEAMModelOS.Controllers
                 { JwtRegisteredClaimNames.Exp,DateTimeOffset.UtcNow.AddHours(2).ToUnixTimeSeconds()},  // 到期的時間,必須為數字
                 { "name",name}, // 用戶的顯示名稱
                 { "picture",picture}, // 用戶頭像
-                { "roles", roles}, // 登入者的角色,角色類型 (Admin、Teacher、Student) 
-                { JwtRegisteredClaimNames.Website,website.route},
+                { "roles", roles.ToArray()}, // 登入者的角色,角色類型 (Admin、Teacher、Student) 
+                { JwtRegisteredClaimNames.Website,website?.route},
             };
             var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_option.JwtSecretKey));
             var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);

+ 0 - 0
TEAMModelOS/Controllers/Common/ExamController.cs


Algúns arquivos non se mostraron porque demasiados arquivos cambiaron neste cambio