Browse Source

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

upon 1 year ago
parent
commit
7aa8a019d2
100 changed files with 3150 additions and 13702 deletions
  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. 1 1
      TEAMModelBI/ClientApp/public/index.html
  15. BIN
      TEAMModelBI/ClientApp/src/assets/img/last-cost.png
  16. BIN
      TEAMModelBI/ClientApp/src/assets/img/now-cost.png
  17. 1 0
      TEAMModelBI/ClientApp/src/components/echarts/Xline.vue
  18. 83 0
      TEAMModelBI/ClientApp/src/components/echarts/commonRadar.vue
  19. 9 0
      TEAMModelBI/ClientApp/src/router/index.js
  20. 11 1
      TEAMModelBI/ClientApp/src/store/index.js
  21. 3 1
      TEAMModelBI/ClientApp/src/view/areaServe/areamanage.vue
  22. 8 0
      TEAMModelBI/ClientApp/src/view/common/aside.vue
  23. 208 6
      TEAMModelBI/ClientApp/src/view/product/index.vue
  24. 1118 0
      TEAMModelBI/ClientApp/src/view/systemConfig/server/index.vue
  25. 69 31
      TEAMModelBI/ClientApp/src/view/userInquire/details.vue
  26. 15 1
      TEAMModelBI/ClientApp/src/view/userInquire/ies.vue
  27. 46 4
      TEAMModelBI/ClientApp/src/view/userInquire/index.vue
  28. 86 58
      TEAMModelBI/ClientApp/src/view/userInquire/iot.vue
  29. 35 14
      TEAMModelBI/ClientApp/src/view/userInquire/socrates.vue
  30. 1 1
      TEAMModelBI/ClientApp/src/view/userInquire/userdetail.vue
  31. 2 2
      TEAMModelBI/Controllers/BIProductAnalysis/ProductAnalysisController.cs
  32. 164 0
      TEAMModelBI/Controllers/BISchool/SchoolController.cs
  33. 1 1
      TEAMModelBI/Controllers/BITest/Ies5TestController.cs
  34. 697 191
      TEAMModelBI/Controllers/BITmid/TmidController.cs
  35. 34 6
      TEAMModelBI/Controllers/Census/SchoolController.cs
  36. 2 1
      TEAMModelBI/Controllers/RepairApi/SchoolRepController.cs
  37. 3 3
      TEAMModelBI/TEAMModelBI.csproj
  38. 131 0
      TEAMModelBI/Tool/Extension/GeoRegion.cs
  39. 0 264
      TEAMModelFunction/.gitignore
  40. 0 548
      TEAMModelFunction/ActivityHttpTrigger.cs
  41. 0 342
      TEAMModelFunction/CourseServiceBus.cs
  42. 0 89
      TEAMModelFunction/LessonHttpTrigger.cs
  43. 0 155
      TEAMModelFunction/MonitorCosmosDB.cs
  44. 0 1033
      TEAMModelFunction/MonitorServicesBus.cs
  45. 0 175
      TEAMModelFunction/Properties/ServiceDependencies/TEAMModelOSFunction - Zip Deploy/profile.arm.json
  46. 0 113
      TEAMModelFunction/Properties/ServiceDependencies/TEAMModelOSFunction - Zip 部署/profile.arm.json
  47. 0 113
      TEAMModelFunction/Properties/ServiceDependencies/TEAMModelOSFunction - 压缩部署/profile.arm.json
  48. 0 175
      TEAMModelFunction/Properties/ServiceDependencies/teammodelosfunction-test - Zip Deploy/profile.arm.json
  49. 0 175
      TEAMModelFunction/Properties/ServiceDependencies/teammodelosfunction__test - 压缩部署/profile.arm.json
  50. 0 8
      TEAMModelFunction/Properties/launchSettings.json
  51. 0 3
      TEAMModelFunction/Properties/serviceDependencies.json
  52. 0 3
      TEAMModelFunction/Properties/serviceDependencies.local.json
  53. 0 611
      TEAMModelFunction/ScsApisHttpTrigger.cs
  54. 0 34
      TEAMModelFunction/Startup.cs
  55. 0 43
      TEAMModelFunction/TEAMModelFunction.csproj
  56. 0 427
      TEAMModelFunction/TriggerCorrect.cs
  57. 0 997
      TEAMModelFunction/TriggerExam.cs
  58. 0 170
      TEAMModelFunction/TriggerExamLite.cs
  59. 0 229
      TEAMModelFunction/TriggerHomework.cs
  60. 0 175
      TEAMModelFunction/TriggerStudy.cs
  61. 0 398
      TEAMModelFunction/TriggerSurvey.cs
  62. 0 318
      TEAMModelFunction/TriggerVote.cs
  63. 0 19
      TEAMModelFunction/host.json
  64. 0 21
      TEAMModelFunction/local.settings.json
  65. 0 35
      TEAMModelGrpc/Dockerfile
  66. 0 46
      TEAMModelGrpc/GrpcHealthCheck/GrpcHealthChecksEndpointRouteBuilderExtensions.cs
  67. 0 56
      TEAMModelGrpc/GrpcHealthCheck/GrpcHealthChecksPublisher.cs
  68. 0 52
      TEAMModelGrpc/GrpcHealthCheck/GrpcHealthChecksServiceExtensions.cs
  69. 0 52
      TEAMModelGrpc/Program.cs
  70. 0 17
      TEAMModelGrpc/Properties/launchSettings.json
  71. 0 26
      TEAMModelGrpc/Protos/BlobSASService.proto
  72. 0 162
      TEAMModelGrpc/Protos/ClassroomService.proto
  73. 0 33
      TEAMModelGrpc/Protos/ClassroomStudentService.proto
  74. 0 189
      TEAMModelGrpc/Protos/CourseService.proto
  75. 0 194
      TEAMModelGrpc/Protos/HomeWorkService.proto
  76. 0 167
      TEAMModelGrpc/Protos/KnowledgeService.proto
  77. 0 124
      TEAMModelGrpc/Protos/SyllabusService.proto
  78. 0 168
      TEAMModelGrpc/Protos/VolumeService.proto
  79. 0 21
      TEAMModelGrpc/Protos/greet.proto
  80. 0 10
      TEAMModelGrpc/Services/IBusinessService.cs
  81. 0 149
      TEAMModelGrpc/Startup.cs
  82. 0 48
      TEAMModelGrpc/TEAMModelGrpc.csproj
  83. 0 2263
      TEAMModelGrpc/TEAMModelOS.GRPC.xml
  84. 0 61
      TEAMModelGrpc/appsettings.Development.json
  85. 0 67
      TEAMModelGrpc/appsettings.json
  86. BIN
      TEAMModelGrpc/habook.pfx
  87. 0 12
      TEAMModelGrpc/nuget.config
  88. 105 95
      TEAMModelOS.FunctionV4/CosmosDB/TriggerExam.cs
  89. 10 10
      TEAMModelOS.FunctionV4/HttpTrigger/IESHttpTrigger.cs
  90. 1 0
      TEAMModelOS.FunctionV4/Program.cs
  91. 1 2
      TEAMModelFunction/Properties/ServiceDependencies/teammodelos-func-v4 - Zip Deploy/profile.arm.json
  92. 5 5
      TEAMModelOS.FunctionV4/ServiceBus/ActiveTaskTopic.cs
  93. 4 4
      TEAMModelOS.FunctionV4/TEAMModelOS.FunctionV4.csproj
  94. 2 1
      TEAMModelOS.FunctionV4/TimeTrigger/IESTimerTrigger.cs
  95. 2 1
      TEAMModelOS.FunctionV4/local.settings.json
  96. 14 1
      TEAMModelOS.SDK/DI/AzureRedis/AzureRedisFactory.cs
  97. 275 41
      TEAMModelOS.SDK/Models/Cosmos/Common/Activity.cs
  98. 2 1
      TEAMModelOS.SDK/Models/Cosmos/Common/ExamClassResult.cs
  99. 1 0
      TEAMModelOS.SDK/Models/Cosmos/School/CourseBase.cs
  100. 0 0
      TEAMModelOS.SDK/Models/Cosmos/School/Elegant.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白名单。

+ 1 - 1
TEAMModelBI/ClientApp/public/index.html

@@ -12,7 +12,7 @@
     </title>
     </title>
 </head>
 </head>
 <script src="https://g.alicdn.com/dingding/dinglogin/0.0.5/ddLogin.js"></script>
 <script src="https://g.alicdn.com/dingding/dinglogin/0.0.5/ddLogin.js"></script>
-<script src="https://at.alicdn.com/t/c/font_2934132_s9rk0x895w8.js"></script>
+<script src="https://at.alicdn.com/t/c/font_2934132_dz617c1kcup.js"></script>
 <script src="../src/access/iconfont.js"></script>
 <script src="../src/access/iconfont.js"></script>
 
 
 <body>
 <body>

BIN
TEAMModelBI/ClientApp/src/assets/img/last-cost.png


BIN
TEAMModelBI/ClientApp/src/assets/img/now-cost.png


+ 1 - 0
TEAMModelBI/ClientApp/src/components/echarts/Xline.vue

@@ -59,6 +59,7 @@ class InitChart {
     this.state.chart.setOption({
     this.state.chart.setOption({
       tooltip: datas.tooltip ? datas.tooltip : '',
       tooltip: datas.tooltip ? datas.tooltip : '',
       legend: datas.legend ? datas.legend : '',
       legend: datas.legend ? datas.legend : '',
+      toolbox: datas.toolbox? datas.toolbox : '',
       grid: datas.grid ? datas.grid : '',
       grid: datas.grid ? datas.grid : '',
       xAxis: datas.xAxis ? datas.xAxis : '',
       xAxis: datas.xAxis ? datas.xAxis : '',
       yAxis: datas.yAxis ? datas.yAxis : '',
       yAxis: datas.yAxis ? datas.yAxis : '',

+ 83 - 0
TEAMModelBI/ClientApp/src/components/echarts/commonRadar.vue

@@ -0,0 +1,83 @@
+<!--基础折线图-->
+<template>
+    <div ref="myEcharts" :style="{ height, width }"></div>
+  </template>
+  <script>
+  import { ref, onMounted, nextTick, watch, getCurrentInstance } from 'vue'
+  import * as echarts from 'echarts'
+  export default {
+    name: 'baseBar',
+    props: {
+      width: {
+        type: String,
+        default: '100%',
+      },
+      height: {
+        type: String,
+        default: '100%',
+      },
+      radarData: {
+        type: Object,
+        default: () => { },
+      },
+      title: {
+        type: String,
+        default: '',
+      },
+    },
+    setup (props) {
+      const myEcharts = ref(null)
+      let { proxy } = getCurrentInstance()
+      const chart = new InitChart(props, myEcharts)
+      onMounted(() => {
+        chart.init(props.radarData, proxy)
+      })
+      watch(
+        props,
+        (nweProps) => {
+          nextTick(() => {
+            nweProps ? chart.init(props.radarData, proxy) : ''
+          })
+        },
+        { immediate: true, deep: true }
+      )
+      return {
+        myEcharts,
+      }
+    },
+  }
+  class InitChart {
+    constructor(props, myEcharts) {
+      this.props = props
+      this.myEcharts = myEcharts
+      this.state = {
+        chart: null,
+      }
+    }
+    init (datas, proxy) {
+      console.log(datas, '简单Radar的调用')
+      this.state.chart && this.destory()
+      this.state.chart = echarts.init(this.myEcharts.value)
+      this.state.chart.setOption({
+        backgroundColor: datas.backgroundColor? datas.backgroundColor : '',
+        tooltip: datas.tooltip ? datas.tooltip : '',
+        grid: datas.grid ? datas.grid : '',
+        radar: datas.radar? datas.radar : '',
+        series: datas.series ? datas.series : '',
+      })
+      window.addEventListener('resize', () => {
+        this.state.chart.resize()
+      })
+    }
+  
+    destory () {
+      this.state.chart.dispose()
+      window.removeEventListener('resize', () => {
+        console.log('事件移除')
+      })
+    }
+  }
+  </script>
+  <style lang="less"></style>
+  
+  

+ 9 - 0
TEAMModelBI/ClientApp/src/router/index.js

@@ -223,6 +223,15 @@ const routes = [{
                 isShow: true,
                 isShow: true,
                 component: () => require.ensure([], (require) => require(`@/view/userInquire/index.vue`))
                 component: () => require.ensure([], (require) => require(`@/view/userInquire/index.vue`))
             },
             },
+            //服务器管理
+            {
+                name: "server",
+                path: "server",
+                permission: "",
+                roles: ['admin'],
+                isShow: true,
+                component: () => require.ensure([], (require) => require(`@/view/systemConfig/server/index.vue`))
+            }
         ]
         ]
     },
     },
     //消息通知跳转页面
     //消息通知跳转页面

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

@@ -22,7 +22,9 @@ export default createStore({
         areaClickschool: {},
         areaClickschool: {},
         areaClickCounselor: '',
         areaClickCounselor: '',
         areaClickRoles: '',
         areaClickRoles: '',
-        msgData: {}
+        msgData: {},
+        transmitvalue:[],
+        hiteachVs:''
     },
     },
     mutations: {
     mutations: {
         //修改组织架构
         //修改组织架构
@@ -99,6 +101,14 @@ export default createStore({
         //复用消息
         //复用消息
         copyMsgs(state, value) {
         copyMsgs(state, value) {
             state.msgData = value
             state.msgData = value
+        },
+        //保存产品使用->ID查询用户列表
+        transmitUsers(state,value){
+            state.transmitvalue=value
+        },
+        //ID查询内  获取HiTeach 最新版本号
+        getHiteachv(state,value){
+            state.hiteachVs=value
         }
         }
     },
     },
     actions: {},
     actions: {},

+ 3 - 1
TEAMModelBI/ClientApp/src/view/areaServe/areamanage.vue

@@ -967,6 +967,7 @@ export default {
           (notjoinSchool.value = [],res.scInfos.forEach((item)=>{!item.areaId ? notaredSchool.push(item):''}),notaredSchool.forEach((item)=>{item.checkstate=false}),notjoinSchool.value=notaredSchool,notjoinPrimitive.value=notaredSchool,loadingSchoolList.value = false):
           (notjoinSchool.value = [],res.scInfos.forEach((item)=>{!item.areaId ? notaredSchool.push(item):''}),notaredSchool.forEach((item)=>{item.checkstate=false}),notjoinSchool.value=notaredSchool,notjoinPrimitive.value=notaredSchool,loadingSchoolList.value = false):
           ''
           ''
         })
         })
+     console.log(notjoinSchool.value,'数据学校')
     }
     }
     //区域内添加学校
     //区域内添加学校
     function areaAddschool (schoolcode) {
     function areaAddschool (schoolcode) {
@@ -1730,6 +1731,7 @@ export default {
 } */
 } */
 .list-school-logo {
 .list-school-logo {
   width: 20%;
   width: 20%;
+  text-align: center;
 }
 }
 
 
 .list-school-name {
 .list-school-name {
@@ -2627,7 +2629,7 @@ export default {
 
 
 .details-list-school .el-image {
 .details-list-school .el-image {
   width: 60%;
   width: 60%;
-  margin: 3% 0% 0% 3%;
+  /* margin: 3% 0% 0% 3%; */
 }
 }
 
 
 .areamanabox .el-table__header-wrapper {
 .areamanabox .el-table__header-wrapper {

+ 8 - 0
TEAMModelBI/ClientApp/src/view/common/aside.vue

@@ -141,6 +141,14 @@ export default {
             isShow: true,
             isShow: true,
             sort: 8,
             sort: 8,
           },
           },
+          // {
+          //   name: '服务器情况',
+          //   router: '/home/server',
+          //   icon: '#icon-fuwuqi2',
+          //   permission: [],
+          //   isShow: true,
+          //   sort: 19,
+          // },
         ],
         ],
       },
       },
       {
       {

+ 208 - 6
TEAMModelBI/ClientApp/src/view/product/index.vue

@@ -1,6 +1,6 @@
 <template>
 <template>
   <!--外层所有数据-->
   <!--外层所有数据-->
-  <div class="productbox" v-loading="" v-if="showState==='default'">
+  <div class="productbox" v-loading="initLoading" v-if="showState==='default'"  element-loading-text="正在准备数据中...">
     <div class="header-select">
     <div class="header-select">
       <el-collapse v-model="activeNames" accordion>
       <el-collapse v-model="activeNames" accordion>
         <el-collapse-item title="数据筛选" name="1">
         <el-collapse-item title="数据筛选" name="1">
@@ -264,6 +264,66 @@
       </template>
       </template>
     </el-dialog>
     </el-dialog>
   </div>
   </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>目前支持同时最多10名用户查询</span>
+          </div>
+        </div>
+      </div>
+      <div class="teachlist-table">
+        <el-table ref="multipleTableRef" :data="teachData" style="width: 100%"  height="50vh" @selection-change="selectTeach"  @sort-change="tablesrotChange">
+          <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" sortable />
+          <el-table-column property="schoolCode" label="弱归户" align="center" sortable>
+            <template #default="scope">
+              <div>{{scope.row.schoolCodeW ? scope.row.schoolCodeW:'无'}}</div>
+            </template>
+          </el-table-column>
+          <el-table-column property="schoolCodeW" label="归户" align="center" sortable>
+            <template #default="scope">
+              <div>{{scope.row.schoolCode ? scope.row.schoolCode:'无'}}</div>
+            </template>
+          </el-table-column>
+          <el-table-column label="所在地" property="city" align="center" sortable>
+            <template #default="scope">
+              <div>
+                <span>{{scope.row.province ?scope.row.province:''}}</span>
+                <span>{{scope.row.city ?scope.row.city:''}}</span>
+                <span>{{scope.row.dist ?scope.row.dist:''}}</span>
+                <span>{{scope.row.unitName ? '-'+scope.row.unitName:''}}</span>
+              </div>
+            </template>
+          </el-table-column>
+          <el-table-column property="levels" label="本学期积分"  align="center" sortable>
+            <!-- <template #default="scope">
+            <div>{{scope.row.points && scope.row.points.level ? scope.row.points.level:0}}</div>
+            </template> -->
+          </el-table-column>
+        </el-table>  
+      </div>
+      <template #footer>
+        <span class="dialog-footer">
+          <el-button @click="teachtableShow = false">关闭</el-button>
+        </span>
+      </template>  
+    </el-dialog>
+  </div>
 </template>
 </template>
 <script setup>
 <script setup>
 import option_cn from '@/static/regions/region_cn.json'
 import option_cn from '@/static/regions/region_cn.json'
@@ -273,8 +333,12 @@ import { ElMessage, TableV2SortOrder, ElLoading, ElCheckbox,HeaderCellSlotProps,
 import { Filter } from '@element-plus/icons'
 import { Filter } from '@element-plus/icons'
 import { multipleSheetExport } from '@/until/multipleSheetExport'
 import { multipleSheetExport } from '@/until/multipleSheetExport'
 import { Search, CirclePlus } from '@element-plus/icons-vue'
 import { Search, CirclePlus } from '@element-plus/icons-vue'
+import { useRouter } from 'vue-router'
+import { useStore } from 'vuex'
 import Details from './details.vue'
 import Details from './details.vue'
 let { proxy } = getCurrentInstance()
 let { proxy } = getCurrentInstance()
+let router=useRouter()
+const store = useStore()
 let drawer = ref(false)
 let drawer = ref(false)
 let direction = ref('ttb')
 let direction = ref('ttb')
 let activeNames = ref(['1'])
 let activeNames = ref(['1'])
@@ -347,13 +411,34 @@ let columns = ref([
     sortable:true
     sortable:true
   },
   },
   {
   {
-    key: "date",
-    dataKey: "date",
-    title: "时间",
-    width: 100,
+    key: "tLesson",
+    dataKey: "tLesson",
+    title: "T课堂",//显示在单元格表头的文本
+    width: 100,//当前列的宽度,必须设置
     headerClass: 'general',
     headerClass: 'general',
     sortable:true
     sortable:true
   },
   },
+  // {
+  //   key: "date",
+  //   dataKey: "date",
+  //   title: "时间",
+  //   width: 100,
+  //   headerClass: 'general',
+  //   sortable:true
+  // },
+  {
+    key: "handle",
+    title: "",
+    width: 150,
+    align: "center",
+    headerClass: 'btn-class',
+    cellRenderer: (data) =>
+    (
+      <>
+        <el-button type="primary"  onClick={examineAllteach.bind(this,data)}>查看所有教师</el-button>
+      </>
+    )
+  },
   {
   {
     key: "handle",
     key: "handle",
     title: "操作",
     title: "操作",
@@ -587,7 +672,7 @@ let optionCopy = option_cn
 // }()
 // }()
 console.log(optionCopy, '省')
 console.log(optionCopy, '省')
 /*地区相关配套json end*/
 /*地区相关配套json end*/
-let changeHight = ref(56)
+let changeHight = ref(51)
 let exportstate = ref(false)
 let exportstate = ref(false)
 let dataForm = ref({
 let dataForm = ref({
   newData: '',
   newData: '',
@@ -666,6 +751,12 @@ let filterType=ref({
    totalShow:true,
    totalShow:true,
    unregistered:true,
    unregistered:true,
 })
 })
+let initLoading=ref(false)
+let teachtableShow=ref(false)
+let teachData=ref([])
+let originalTeachdata=ref([])
+let deleteSchoolArr=ref([])
+let touchNowteach=ref()
 const pickerOptions=function disabledDate(time) {
 const pickerOptions=function disabledDate(time) {
           return time.getTime() > Date.now();
           return time.getTime() > Date.now();
 }
 }
@@ -687,6 +778,7 @@ const monthOptions=function disabledDate(time){
                 const elTimeData = timeyear.toString() + timemonth.toString();
                 const elTimeData = timeyear.toString() + timemonth.toString();
                 return elTimeData >= nowDate; 
                 return elTimeData >= nowDate; 
 }
 }
+
 function changeState (value) {
 function changeState (value) {
   console.log(value)
   console.log(value)
   showState.value = 'details'
   showState.value = 'details'
@@ -703,6 +795,7 @@ function selectBlur (e) {
   dataForm.value.newData = e.target.value;
   dataForm.value.newData = e.target.value;
 }
 }
 function dataInit () {
 function dataInit () {
+  initLoading.value=true
   let dataList = []
   let dataList = []
   proxy.$api.getCapacity({}).then((res) => {
   proxy.$api.getCapacity({}).then((res) => {
     console.log(res, 'areList')
     console.log(res, 'areList')
@@ -728,9 +821,11 @@ function dataInit () {
       tableData.value = res.scInfos
       tableData.value = res.scInfos
       console.log(dataSource.value.composite, '检查是否是所有学校')
       console.log(dataSource.value.composite, '检查是否是所有学校')
       filterloding.value = false
       filterloding.value = false
+      initLoading.value=false
     }).catch((err) => {
     }).catch((err) => {
       ElMessage.error('API异常,基础数据获取异常')
       ElMessage.error('API异常,基础数据获取异常')
       filterloding.value = false
       filterloding.value = false
+      initLoading.value=false
     })
     })
   }).catch((err) => {
   }).catch((err) => {
     ElMessage.error('API异常,基础数据获取异常')
     ElMessage.error('API异常,基础数据获取异常')
@@ -1398,6 +1493,87 @@ function filterSchooltype(){
   console.log(result,'赋值')
   console.log(result,'赋值')
   filterdata.value=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 ?(res.forEach((item)=>{item.levels=item.points && item.points.level ?item.points.level:0}),teachData.value=res,originalTeachdata.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 >10){
+      ElMessage.info('当前查询人数仅支持小于或等于10名用户')
+      return
+  }
+  console.log(deleteSchoolArr.value,'传递出去的参数')
+  store.commit('transmitUsers', deleteSchoolArr.value)
+  router.push({name:'userinquire'})  
+}
+function tablesrotChange(rule){
+  console.log(rule,'规则')
+  let rules=rule.order;let datas=teachData.value
+  //id
+  // if(rule.prop ==="id"){
+  //   rules==='descending' ?  datas.sort((a,b)=>{return b.id -a.id >0}):datas.sort((a,b)=>{return a.id -b.id >0})
+  // }else if(rule.prop !=='id'){
+  //   rules ==="descending" ? datas.sort((a,b)=>{if(b.points && a.points){return b.points.level -a.points.level >0}else{ return false}}):
+  //   datas.sort((a,b)=>{if(b.points && a.points){ return a.points.level -b.points.level >0}else{return false}})
+  // }
+  //积分
+  if(rule.prop ==="levels"){
+    rules ==="descending" ? datas.sort((a,b)=>{if(b.points && a.points){return b.level -a.level >0}}):datas.sort((a,b)=>{if(b.points && a.points){return a.level -b.level >0}})
+  }else if(rule.prop ==="id"){
+    rules==='descending' ?  datas.sort((a,b)=>{return b.id -a.id >0}):datas.sort((a,b)=>{return a.id -b.id >0})
+  }else if(rule.prop ==="schoolCode"){
+    rules==='descending' ? datas.sort((a,b)=>{if(!a.schoolCode ||a.schoolCode === null){return 1}else if(!b.schoolCode || b.schoolCode=== null){return -1}else{return 0}}):datas.sort((a,b)=>{if(!a.schoolCode || a.schoolCode === null){return 0}else if(!b.schoolCode ||b.schoolCode=== null){return 0}else{return -1}})
+  }else if(rule.prop ==="schoolCodeW"){
+    rules==='descending' ? datas.sort((a,b)=>{if(!a.schoolCodeW ||a.schoolCodeW === null){return 1}else if(!b.schoolCodeW ||b.schoolCodeW=== null){return -1}else{return 0}}):datas.sort((a,b)=>{if(!a.schoolCodeW || a.schoolCodeW === null){return 0}else if(!b.schoolCodeW ||b.schoolCodeW=== null){return 0}else{return -1}})
+  }else if(rule.prop ==="city"){
+    rules==='descending' ? datas.sort((a,b)=>{if(a.province && a.city){return -1}else if(b.province && b.city){return -1}else{return 0}}):datas.sort((a,b)=>{if(a.province && a.city){return 1}else if(b.province && b.city){return 1}else{return 0}})
+  }
+
+  // if(rules ==="descending"){
+  //   datas.sort((a,b)=>{
+  //     if(b.points && a.points){
+  //       console.log( b.points.level -a.points.level >0,'进入倒序判断')
+  //       return b.points.level -a.points.level >0
+  //     }else{
+  //       console.log('进入倒序判断error ')
+  //     }
+  //   })
+  // }else{
+  //   datas.sort((a,b)=>{
+  //     if(b.points && a.points){
+  //       console.log('进入正序判断')
+  //       return a.points.level -b.points.level >0
+  //     }else{
+  //       console.log('进入正序判断error')
+  //     }
+  //   })
+  // }
+  console.log(datas,'排序后')
+  teachData.value=JSON.parse(JSON.stringify(datas))
+}
+function filterTag(value){
+  console.log(value,'filter')
+  let datas=originalTeachdata.value
+  let dataArr=[]
+  if(value ==='notDepartment'){
+    datas.forEach((item)=>{!item.schoolCodeW ? dataArr.push(item):''})
+  }else if(value ==='weakDepartment'){
+    datas.forEach((item)=>{item.schoolCodeW ? dataArr.push(item):''})
+  }
+  teachData.value=dataArr
+}
 // init()
 // init()
 dataInit()
 dataInit()
 filterDistrict()
 filterDistrict()
@@ -1601,6 +1777,28 @@ watch(clickNum, (newv) => {
 .school-type {
 .school-type {
   display: flex;
   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>
 <style>
 <style>
 .data-tables .header-class,
 .data-tables .header-class,
@@ -1662,4 +1860,8 @@ watch(clickNum, (newv) => {
 .data-tables .el-table-v2__header-cell:hover .el-icon{
 .data-tables .el-table-v2__header-cell:hover .el-icon{
   display: flex;
   display: flex;
 }
 }
+.dialog-teachlist .el-dialog__header{
+  padding: 5px;
+
+}
 </style>
 </style>

File diff suppressed because it is too large
+ 1118 - 0
TEAMModelBI/ClientApp/src/view/systemConfig/server/index.vue


+ 69 - 31
TEAMModelBI/ClientApp/src/view/userInquire/details.vue

@@ -39,7 +39,7 @@
                 <el-image :src="randomImage" fit="contain" v-else/>
                 <el-image :src="randomImage" fit="contain" v-else/>
             </div>
             </div>
             <div class="topbox-name">
             <div class="topbox-name">
-                <div class="topbox-name-text">{{usernames}}</div>
+                <div class="topbox-name-text">{{usernames ? usernames :'暂无姓名'}} </div>
                 <div class="topbox-name-advance" @click="userdetailState=true">查看账户进阶数据<el-icon><MoreFilled /></el-icon></div>
                 <div class="topbox-name-advance" @click="userdetailState=true">查看账户进阶数据<el-icon><MoreFilled /></el-icon></div>
             </div>
             </div>
            </div>
            </div>
@@ -49,11 +49,11 @@
                   <use :xlink:href="item.icon"></use>
                   <use :xlink:href="item.icon"></use>
                 </svg>
                 </svg>
                 <span class="information-text">{{item.value}}</span>
                 <span class="information-text">{{item.value}}</span>
-                <div :title="[item.correlation ? '已关联':'弱关联,可进行手动修改']" v-show="item.key ==='school'">
+                <!-- <div :title="[item.correlation ? '已关联':'弱关联,可进行手动修改']" v-show="item.key ==='school' && item.value !=='无'">
                     <svg class="hint-icon" aria-hidden="true"  >
                     <svg class="hint-icon" aria-hidden="true"  >
                         <use :xlink:href="[item.correlation ? '#icon-zhengque3':'#icon-tishi2']"></use>
                         <use :xlink:href="[item.correlation ? '#icon-zhengque3':'#icon-tishi2']"></use>
                     </svg>
                     </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 ==='school'&& !item.correlation" class="changebtn">更改</el-button> -->
                 <!-- <el-button type="" size="small" v-show="item.key ==='local'">更改</el-button> -->
                 <!-- <el-button type="" size="small" v-show="item.key ==='local'">更改</el-button> -->
             </div>
             </div>
@@ -216,11 +216,11 @@
                                 </el-carousel-item>
                                 </el-carousel-item>
                             </el-carousel> -->
                             </el-carousel> -->
                             <div class="prodlist">
                             <div class="prodlist">
-                                <div v-if="powerList.length >0">
+                                <div v-show="powerList.length >0">
                                     <div class="prodlist-item" v-for="item in powerList" :key="item">
                                     <div class="prodlist-item" v-for="item in powerList" :key="item">
                                     <div class="rightsbox-item">
                                     <div class="rightsbox-item">
                                         <div class="rightsbox-item-title">
                                         <div class="rightsbox-item-title">
-                                            <p>[ID授权] {{item.name}}</p>
+                                            <!-- <p>[ID授权] {{item.name}}</p> -->
                                         </div>
                                         </div>
                                         <div class="rightsbox-item-time">
                                         <div class="rightsbox-item-time">
                                             <p>
                                             <p>
@@ -228,7 +228,7 @@
                                                 <span class="rightsbox-item-time-num">{{item.startDateText}}~{{item.endDateText}}</span>
                                                 <span class="rightsbox-item-time-num">{{item.startDateText}}~{{item.endDateText}}</span>
                                                 <span>共<span class="rightsbox-item-timenums">{{item.intervalTime}}</span>天</span>
                                                 <span>共<span class="rightsbox-item-timenums">{{item.intervalTime}}</span>天</span>
                                             </p>
                                             </p>
-                                            <p v-show="item.aprule.schoolinfo">
+                                            <p  v-if=" item.aprule &&item.aprule.hasOwnProperty('schoolinfo') ">
                                                 <span>学校:</span>
                                                 <span>学校:</span>
                                                 <span class="rightsbox-item-timenums">{{item.aprule.schoolinfo.name}}</span>
                                                 <span class="rightsbox-item-timenums">{{item.aprule.schoolinfo.name}}</span>
                                             </p>
                                             </p>
@@ -252,7 +252,7 @@
                                     <el-divider /> 
                                     <el-divider /> 
                                 </div>
                                 </div>
                                 </div>
                                 </div>
-                                <div class="power-notdata" v-else>暂无权益内容</div>
+                                <div class="power-notdata" v-show =" powerList.length ==0">暂无权益内容</div>
                                    <!--HiTeach 附加功能-->
                                    <!--HiTeach 附加功能-->
                                 <div class="subjoin">
                                 <div class="subjoin">
                                     <div class="subjoin-item" >
                                     <div class="subjoin-item" >
@@ -352,7 +352,7 @@
                     <div class="logintotal-box-table">
                     <div class="logintotal-box-table">
                         <p class="logintotal-box-table-title">登入详细:</p>
                         <p class="logintotal-box-table-title">登入详细:</p>
                         <el-table :data="logintotalTable" style="width: 100%" height="35vh" border >
                         <el-table :data="logintotalTable" style="width: 100%" height="35vh" border >
-                            <el-table-column prop="product" label="平台" align="center"/>
+                            <el-table-column prop="nameText" label="平台" align="center"/>
                             <el-table-column prop="timeText" label="时间" align="center"/>
                             <el-table-column prop="timeText" label="时间" align="center"/>
                         </el-table>
                         </el-table>
                     </div>
                     </div>
@@ -369,8 +369,9 @@
     </div>
     </div>
 </template>
 </template>
 <script setup>
 <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 { Iphone,More,MoreFilled,ArrowLeft,Right } from '@element-plus/icons'
+import { useStore } from 'vuex'
 import commonHeatmapVue from '../../components/echarts/commonHeatmap.vue'
 import commonHeatmapVue from '../../components/echarts/commonHeatmap.vue'
 import commonGaugeVue from '../../components/echarts/commonGauge.vue'
 import commonGaugeVue from '../../components/echarts/commonGauge.vue'
 import Hiteach from './hiteach.vue'
 import Hiteach from './hiteach.vue'
@@ -381,9 +382,12 @@ import Score from './score.vue'
 import Ticket from './ticket.vue'
 import Ticket from './ticket.vue'
 import Userdetail from './userdetail.vue'
 import Userdetail from './userdetail.vue'
 import replaceHiTeach from './iot.vue'
 import replaceHiTeach from './iot.vue'
+import { useRouter } from 'vue-router'
 let props = defineProps({
 let props = defineProps({
     searchdata: Object,
     searchdata: Object,
 })
 })
+let router=useRouter()
+const store = useStore()
 let {ctx:that,proxy } = getCurrentInstance()
 let {ctx:that,proxy } = getCurrentInstance()
 let activeName = ref('basics')
 let activeName = ref('basics')
 let userdetailState=ref(false)
 let userdetailState=ref(false)
@@ -403,9 +407,10 @@ let productdata = ref([
     { id: 2, title: 'HiTA',value:0,valueText:'',key:'HiTA',state: false },
     { id: 2, title: 'HiTA',value:0,valueText:'',key:'HiTA',state: false },
     { id: 3, title: 'IES', value:0,valueText:'',key:'IES5', state: false },
     { id: 3, title: 'IES', value:0,valueText:'',key:'IES5', state: false },
     { id: 4, title: '苏格拉底', value:0,valueText:'',key:'Sokrates', state: false },
     { id: 4, title: '苏格拉底', value:0,valueText:'',key:'Sokrates', state: false },
-    { id: 5, title: '觀議課 APP', value:0,valueText:'',key:'SokAPP', state: false },
-    { id: 6, title: '通用账号', value:0,valueText:'',key:'Account ', state: false },
-    { id: 7, title: 'WebIRS5', value:0,valueText:'',key:'IRS', state: false },
+    { id: 5, title: '观议課 APP', value:0,valueText:'',key:'SokAPP', state: false },
+    { id: 6, title: '通用账号', value:0,valueText:'',key:'Account', state: false },
+    { id: 7, title: 'HiTeachCC', value:0,valueText:'',key:'HiTeachCC', state: false },
+    { id: 8, title: 'WebIRS5', value:0,valueText:'',key:'IRS', state: false },
 ])
 ])
 let tableData = ref([
 let tableData = ref([
     { time: '2023-07-05 15:33', ip: '222.209.14.199', location: '四川省成都市',platform:'HiTeach' },
     { time: '2023-07-05 15:33', ip: '222.209.14.199', location: '四川省成都市',platform:'HiTeach' },
@@ -732,6 +737,7 @@ let headerData=ref([
     require('@/assets/img/default4.png'),
     require('@/assets/img/default4.png'),
     ])
     ])
 let userPortrait=ref()     //用户头像
 let userPortrait=ref()     //用户头像
+let backtoShow=inject("transmitShow")
 const randomImage = computed(()=>{
 const randomImage = computed(()=>{
     const randomIndex = Math.floor(Math.random() * headerData.value.length);
     const randomIndex = Math.floor(Math.random() * headerData.value.length);
     console.log(randomIndex,'随机头像')
     console.log(randomIndex,'随机头像')
@@ -743,47 +749,66 @@ const handleChildEvent = (payload) => {
 const emits = defineEmits(['parentClick']) 
 const emits = defineEmits(['parentClick']) 
 const backClick = () => {
 const backClick = () => {
     console.log('back init')
     console.log('back init')
-        emits('parentClick','default') // 使用方式和 vue2 this.$emit 一样
+    store.commit('getHiteachv','')
+    if(backtoShow){
+        router.push({name:'analysis'})
+    }else{
+        emits('parentClick','default')
+    }
 }
 }
+// initdata()
 function initdata() {
 function initdata() {
     console.log(detailsData.value,'进入方法查看')
     console.log(detailsData.value,'进入方法查看')
     let transmitData = detailsData.value[transferNum.value]
     let transmitData = detailsData.value[transferNum.value]
     console.log(transmitData,'数据details')
     console.log(transmitData,'数据details')
     //header 基础信息 
     //header 基础信息 
-    let { name,id,mobile, mail, schoolCode, schoolCodeW, points,country,province,city,picture} = transmitData
+    let { name,id,mobile, mail, schoolCode, schoolCodeW, points,country,province,city,picture,dist} = transmitData
     userPortrait.value=picture
     userPortrait.value=picture
     usernames.value=name
     usernames.value=name
-    userdata.value[0].value = id
-    userdata.value[1].value = mobile
+    userdata.value[0].value = id ? id:'暂无'
+    userdata.value[1].value = mobile ?mobile:'暂无'
     userdata.value[2].value = schoolCodeW ? schoolCodeW : schoolCode ? schoolCode:'无'
     userdata.value[2].value = schoolCodeW ? schoolCodeW : schoolCode ? schoolCode:'无'
+    let schoolname= schoolCode ?schoolCode:'无'; let schoolnameW=schoolCodeW ? schoolCodeW:'无'
+    userdata.value[2].value = schoolCodeW || schoolCode ?  schoolnameW   + ' | '  +schoolname:'暂无'
     schoolCodeW ? userdata.value[2].correlation=true:false
     schoolCodeW ? userdata.value[2].correlation=true:false
-    userdata.value[3].value = mail
-    userdata.value[4].value = country && province && city ? country+'-'+province+city:country+'-'+province
+    userdata.value[3].value = mail ? mail:'暂无'
+    //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 {login}=transmitData
     let logintimes = login.length >0 ? login.sort(function(a,b){return b.time-a.time}):'无'
     let logintimes = login.length >0 ? login.sort(function(a,b){return b.time-a.time}):'无'
     console.log(logintimes,'时间!')
     console.log(logintimes,'时间!')
     logintimes !=='无' ?  userdata.value[5].value=proxy.$common.timestampToTime(logintimes[0].time,'all'):userdata.value[5].value='暂无'
     logintimes !=='无' ?  userdata.value[5].value=proxy.$common.timestampToTime(logintimes[0].time,'all'):userdata.value[5].value='暂无'
-    productdata.value.forEach((itema)=>{itema.value =0})
+    productdata.value.forEach((itema)=>{itema.value =0,itema.valueText='',itema.state=false})
     if(login.length >0){
     if(login.length >0){
        console.log('进入到多数组')
        console.log('进入到多数组')
        logintotalTable.value=[]
        logintotalTable.value=[]
        login.forEach(item => {
        login.forEach(item => {
          let typename=item.product
          let typename=item.product
          productdata.value.forEach(items=>{
          productdata.value.forEach(items=>{
-            typename === items.key ? 
-            items.value === 0 ? (items.valueText=proxy.$common.timestampToTime(item.time,'all'),items.value=item.time,items.state=true): 
-            item.time > items.value ? (items.valueText=proxy.$common.timestampToTime(item.time,'all'),items.value=item.time,items.state=true):'':''
-         })
+            if(typename === items.key){
+                items.value === 0 ? (items.valueText=proxy.$common.timestampToTime(item.time,'all'),items.value=item.time,items.state=true): 
+                item.time > items.value ? (items.valueText=proxy.$common.timestampToTime(item.time,'all'),items.value=item.time,items.state=true):''
+                typename === items.key ? item.nameText=items.title:''
+            }
+            // items.value === 0 ? (items.valueText=proxy.$common.timestampToTime(item.time,'all'),items.value=item.time,items.state=true): 
+            // item.time > items.value ? (items.valueText=proxy.$common.timestampToTime(item.time,'all'),items.value=item.time,items.state=true):''
+            // typename === items.key ? item.nameText=items.title:''
+        })
          item.timeText=proxy.$common.timestampToTime(item.time,'all')
          item.timeText=proxy.$common.timestampToTime(item.time,'all')
-         logintotalTable.value.push(item)
        })
        })
+       console.log(logintotalTable.value,'所有登录结果')
     }else{
     }else{
         logintotalTable.value=[]
         logintotalTable.value=[]
         productdata.value.forEach((item)=>{
         productdata.value.forEach((item)=>{
             item.state=false
             item.state=false
         })
         })
     }
     }
+    console.log(logintotalTable.value,'登入数据~')
     //空间与权益
     //空间与权益
     let {usedSize,teachSize,totalSize,surplusSize}=transmitData.ies5
     let {usedSize,teachSize,totalSize,surplusSize}=transmitData.ies5
     let usePercentum=parseInt(((Number(bytesToGB(usedSize))+Number(bytesToGB(teachSize)))/Number(bytesToGB(totalSize)))*100);let useGsize=proxy.$common.convertSize(usedSize)
     let usePercentum=parseInt(((Number(bytesToGB(usedSize))+Number(bytesToGB(teachSize)))/Number(bytesToGB(totalSize)))*100);let useGsize=proxy.$common.convertSize(usedSize)
@@ -809,7 +834,7 @@ function initdata() {
             apruleItem.cloudas ? powerExtension.value[9].state=true:powerExtension.value[9].state=false  //雲端診斷分析系統
             apruleItem.cloudas ? powerExtension.value[9].state=true:powerExtension.value[9].state=false  //雲端診斷分析系統
             apruleItem.cligroup !==0 ? (powerExtension.value[10].state=true,powerExtension.value[10].value=apruleItem.cligroup):powerExtension.value[10].state=false //分組數
             apruleItem.cligroup !==0 ? (powerExtension.value[10].state=true,powerExtension.value[10].value=apruleItem.cligroup):powerExtension.value[10].state=false //分組數
             apruleItem.client_volume !==0 ? (powerExtension.value[11].state=true,powerExtension.value[11].value=apruleItem.client_volume):powerExtension.value[11].state=false  //IRS連線授權數
             apruleItem.client_volume !==0 ? (powerExtension.value[11].state=true,powerExtension.value[11].value=apruleItem.client_volume):powerExtension.value[11].state=false  //IRS連線授權數
-            apruleItem.soknumber !==0 ? (powerExtension.value[12].state=true,powerExtension.value[10].value=apruleItem.soknumber):powerExtension.value[12].state=false //議課人數
+            apruleItem.soknumber !==0 ? (powerExtension.value[12].state=true,powerExtension.value[12].value=apruleItem.soknumber):powerExtension.value[12].state=false //議課人數
             apruleItem.scorsys ? (powerExtension.value[13].state=true,powerExtension.value[13].value=apruleItem.soknumber):powerExtension.value[13].state=false //智慧評分系統
             apruleItem.scorsys ? (powerExtension.value[13].state=true,powerExtension.value[13].value=apruleItem.soknumber):powerExtension.value[13].state=false //智慧評分系統
             apruleItem.hasOwnProperty('irs') ? powerExtension.value[14].state=false:powerExtension.value[14].state=true  //IRS硬體遙控器
             apruleItem.hasOwnProperty('irs') ? powerExtension.value[14].state=false:powerExtension.value[14].state=true  //IRS硬體遙控器
             item.apruleArr=powerExtension.value
             item.apruleArr=powerExtension.value
@@ -865,8 +890,8 @@ function initdata() {
     console.log(transitionUsed,transitionSuplus,transitionTeach,transitionTotal,'结果')
     console.log(transitionUsed,transitionSuplus,transitionTeach,transitionTotal,'结果')
 
 
     //处理上下一个
     //处理上下一个
-    advancevalue.value.next=detailsData.value[transferNum.value+1]
-    loading.value=false
+    // advancevalue.value.next=detailsData.value[transferNum.value+1]
+    
 }
 }
 function bytesToGB(bytes) {
 function bytesToGB(bytes) {
   const gb = bytes / (1024 * 1024 * 1024);
   const gb = bytes / (1024 * 1024 * 1024);
@@ -888,6 +913,14 @@ function init(){
     detailsData.value[transferNum.value].iot.hiteach.day ? (buttonSelect.value[0].disabled=false):(buttonSelect.value[0].disabled=true,buttonSelect.value[0].click=false)
     detailsData.value[transferNum.value].iot.hiteach.day ? (buttonSelect.value[0].disabled=false):(buttonSelect.value[0].disabled=true,buttonSelect.value[0].click=false)
     detailsData.value[transferNum.value].iot.hiteach.month ? (buttonSelect.value[1].disabled=false):(buttonSelect.value[1].disabled=true,buttonSelect.value[1].click=false)
     detailsData.value[transferNum.value].iot.hiteach.month ? (buttonSelect.value[1].disabled=false):(buttonSelect.value[1].disabled=true,buttonSelect.value[1].click=false)
     detailsData.value[transferNum.value].iot.hiteach.year  ? (buttonSelect.value[2].disabled=false):(buttonSelect.value[2].disabled=true,buttonSelect.value[2].click=false)
     detailsData.value[transferNum.value].iot.hiteach.year  ? (buttonSelect.value[2].disabled=false):(buttonSelect.value[2].disabled=true,buttonSelect.value[2].click=false)
+    
+    //获取hiteach 版本号
+     let versionsData=detailsData.value[transferNum.value].iot.hiteach ?.year ?.verList
+    console.log(versionsData)
+     let hiteachV=versionsData ? versionsData.sort((a,b)=>{return b-a}):'暂无'
+     console.log(hiteachV,'版本号')
+     store.commit('getHiteachv', hiteachV[0])
+    loading.value=false
 }
 }
 function selectTime(value){
 function selectTime(value){
     console.log(value,'值')
     console.log(value,'值')
@@ -927,7 +960,8 @@ function cutUser(){
 function nextUser(){
 function nextUser(){
     console.log(transferNum,'值')
     console.log(transferNum,'值')
     transferNum.value=Number(transferNum.value)+1
     transferNum.value=Number(transferNum.value)+1
-    if(transferNum.value === detailsData.value.length){}
+    // if(transferNum.value === detailsData.value.length){}
+    store.commit('getHiteachv','')
 }
 }
 //上一个用户
 //上一个用户
 function lastUser(){
 function lastUser(){
@@ -938,6 +972,7 @@ function lastUser(){
         sokratesData.value=detailsData.value[transferNum.value].sokrates
         sokratesData.value=detailsData.value[transferNum.value].sokrates
         pointsData.value=detailsData.value[transferNum.value]
         pointsData.value=detailsData.value[transferNum.value]
     }
     }
+    store.commit('getHiteachv','')
 }
 }
 onMounted(() => {
 onMounted(() => {
     initdata()
     initdata()
@@ -1049,11 +1084,11 @@ watch(()=>transferNum.value,(newnum)=>{
     margin:0% 4%;
     margin:0% 4%;
 }
 }
 .listbox-item-total{
 .listbox-item-total{
-    width:10%;
+    width:11%;
     line-height: 30px;
     line-height: 30px;
     padding: 1%;
     padding: 1%;
     border-radius: 5px;
     border-radius: 5px;
-    margin:0.5% 2%;
+    margin:0.5% 1%;
 }
 }
 .item-title{
 .item-title{
     width:100%;
     width:100%;
@@ -1101,6 +1136,9 @@ watch(()=>transferNum.value,(newnum)=>{
 .Account{
 .Account{
     background: linear-gradient(to top right, #FAACA8, #DDD6F3); 
     background: linear-gradient(to top right, #FAACA8, #DDD6F3); 
 }
 }
+.HiTeachCC{
+    background: linear-gradient(to top right, #74EBD5, #9FACE6); 
+}
 
 
 .notenabled{
 .notenabled{
     background-color: #dcdaef;
     background-color: #dcdaef;
@@ -1131,7 +1169,7 @@ watch(()=>transferNum.value,(newnum)=>{
     width:75%;
     width:75%;
     border-radius: 5px;
     border-radius: 5px;
     box-shadow: rgba(0, 0, 0, 0.3) 0px 3px 8px;
     box-shadow: rgba(0, 0, 0, 0.3) 0px 3px 8px;
-    padding: 1%;
+    padding: 1% 0.5%;
 }
 }
 .heartmap-label{
 .heartmap-label{
     display: flex;
     display: flex;

+ 15 - 1
TEAMModelBI/ClientApp/src/view/userInquire/ies.vue

@@ -13,7 +13,7 @@
         </div>
         </div>
         <el-divider />
         <el-divider />
             <div class="joinSchool">
             <div class="joinSchool">
-                <div class="joinSchool-item">
+                <div class="joinSchool-item" v-if="iesShow">
                     <div class="joinSchool-img">
                     <div class="joinSchool-img">
                         <svg class="joinSchool-icon" aria-hidden="true">
                         <svg class="joinSchool-icon" aria-hidden="true">
                             <use xlink:href="#icon-xuexiao8"></use>
                             <use xlink:href="#icon-xuexiao8"></use>
@@ -62,6 +62,9 @@
                         <span>默认学校</span>
                         <span>默认学校</span>
                     </div>
                     </div>
                 </div>
                 </div>
+                <div class="not-datas" v-else>
+                    暂无学校信息
+                </div>
             </div>
             </div>
         <el-divider />
         <el-divider />
             <div class="ies-flex">
             <div class="ies-flex">
@@ -148,6 +151,7 @@
       {name:'南京特殊教育师范学院',code:'ntsjsy',location:'中国',class:15,totalsize:300,occupy:75}
       {name:'南京特殊教育师范学院',code:'ntsjsy',location:'中国',class:15,totalsize:300,occupy:75}
  ])
  ])
  let allschoolList=ref([])
  let allschoolList=ref([])
+ let iesShow=ref(true)
  let echartsBar=ref({
  let echartsBar=ref({
     tooltip: {
     tooltip: {
         trigger: 'axis',
         trigger: 'axis',
@@ -254,6 +258,10 @@
  })
  })
  function initdatas(){
  function initdatas(){
     console.log(props.iesdata,'IESde zhi')
     console.log(props.iesdata,'IESde zhi')
+    if(!props.iesdata){
+        iesShow.value=false 
+        return
+    }
     let {resCount,itemCount,paperCount}=props.iesdata
     let {resCount,itemCount,paperCount}=props.iesdata
     relevancedata.value[0].value=resCount
     relevancedata.value[0].value=resCount
     relevancedata.value[1].value=itemCount
     relevancedata.value[1].value=itemCount
@@ -546,6 +554,12 @@ watch(()=>props,(newvalue)=>{
  .fontsize{
  .fontsize{
     font-size:12px;
     font-size:12px;
  }
  }
+ .not-datas{
+    font-size:16px;
+    font-weight: 700;
+    color: #73767a;
+    line-height: 40px;
+}
  </style>
  </style>
 <style>
 <style>
 .dialog-school .el-dialog__body{
 .dialog-school .el-dialog__body{

+ 46 - 4
TEAMModelBI/ClientApp/src/view/userInquire/index.vue

@@ -28,6 +28,9 @@
                         {{ tag }}
                         {{ tag }}
                     </el-tag>
                     </el-tag>
                 </div>
                 </div>
+                <div class="dele-all" v-show="searchRecordsArr.length >0">
+                    <el-icon size="14" @click="deleAllsearch"><Delete /></el-icon>
+                </div>
             </div>
             </div>
             <div class="recordbox" v-else="selecttypes ==='batch'">
             <div class="recordbox" v-else="selecttypes ==='batch'">
                 <p>搜索结果:</p>
                 <p>搜索结果:</p>
@@ -39,11 +42,18 @@
     </div>
     </div>
 </template>
 </template>
 <script setup>
 <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 { ElMessage, ElLoading } from 'element-plus'
-import { Search } from '@element-plus/icons'
+import { Search,Delete } from '@element-plus/icons'
 import Detailsbox from './details.vue'
 import Detailsbox from './details.vue'
+import {useRoute} from "vue-router"
+import { useStore } from 'vuex'
 let { proxy } = getCurrentInstance()
 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([
 let tags = ref([
   { name: 'Tag 1', type: '' },
   { name: 'Tag 1', type: '' },
   { name: 'Tag 2', type: 'success' },
   { name: 'Tag 2', type: 'success' },
@@ -59,6 +69,9 @@ let searchLoading=ref(false)
 const searchRecordsArr = ref(localStorage.getItem('searchRecords') ?  JSON.parse(localStorage.getItem('searchRecords')):[]);
 const searchRecordsArr = ref(localStorage.getItem('searchRecords') ?  JSON.parse(localStorage.getItem('searchRecords')):[]);
 const backClicks=()=>{pageShow.value='default'}
 const backClicks=()=>{pageShow.value='default'}
 console.log(searchRecordsArr.value,'搜索记录')
 console.log(searchRecordsArr.value,'搜索记录')
+//逻辑判断  是否是从 产品使用分析跳转过来
+transmitModel.value ? transmitinit():''
+provide('transmitShow',transmitModel.value)
 function seachSole(datavalue) {
 function seachSole(datavalue) {
     if(!searchvalue.value){
     if(!searchvalue.value){
         ElMessage.info('请输入手机号码/ 醍魔豆账号 进行搜索!')
         ElMessage.info('请输入手机号码/ 醍魔豆账号 进行搜索!')
@@ -74,8 +87,8 @@ function seachSole(datavalue) {
         searchvalue.value=searchvalue.value.replace(/,/g, ',');
         searchvalue.value=searchvalue.value.replace(/,/g, ',');
         userArr = searchvalue.value.split(',');
         userArr = searchvalue.value.split(',');
     }
     }
-    if(userArr.length >5){
-            ElMessage.info('同时查询人员不能大于5,请调整查询范围')
+    if(userArr.length >10){
+            ElMessage.info('同时查询人员不能大于10,请调整查询范围')
             return
             return
     }
     }
     //let testdata=['1524738018','1595321354']
     //let testdata=['1524738018','1595321354']
@@ -90,6 +103,8 @@ function seachSole(datavalue) {
         time:Date.now()
         time:Date.now()
     }
     }
     proxy.$api.getUserdatas(data).then((res) => { 
     proxy.$api.getUserdatas(data).then((res) => { 
+        //重置vuex内的值,预防下次Menu进入 自动获取vuex值进行查询
+        store.commit('transmitUsers', [])
         console.log(res, 'user back')
         console.log(res, 'user back')
         res.length >0 ? 
         res.length >0 ? 
         (searchResult.value=res,searchLoading.value=false,pageShow.value='details'):
         (searchResult.value=res,searchLoading.value=false,pageShow.value='details'):
@@ -122,6 +137,24 @@ function deleteLog(value){
     resultNum !== -1 ? (searchRecordsArr.value.splice(resultNum,1)):''
     resultNum !== -1 ? (searchRecordsArr.value.splice(resultNum,1)):''
     localStorage.setItem('searchRecords', JSON.stringify(searchRecordsArr.value));
     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()
+}
+function deleAllsearch(){
+    searchRecordsArr.value=[]
+    localStorage.setItem('searchRecords', JSON.stringify(searchRecordsArr.value));
+}
 </script>
 </script>
 <style scoped>
 <style scoped>
 .inquirebox{
 .inquirebox{
@@ -173,6 +206,10 @@ function deleteLog(value){
     padding: 0% 10%;
     padding: 0% 10%;
     line-height: 20px;
     line-height: 20px;
     text-align: left;
     text-align: left;
+    height:15vh;
+    overflow: hidden;
+    overflow-y: auto;
+    position:relative;
 }
 }
 .recordbox p{
 .recordbox p{
     font-size:14px;
     font-size:14px;
@@ -196,4 +233,9 @@ function deleteLog(value){
     font-size:14px;
     font-size:14px;
     display: flex;
     display: flex;
 }
 }
+.dele-all{
+    position: absolute;
+    top:1%;
+    right:5%;
+}
 </style>
 </style>

+ 86 - 58
TEAMModelBI/ClientApp/src/view/userInquire/iot.vue

@@ -40,14 +40,14 @@
                 <div class="item-num">{{item.value}}</div>
                 <div class="item-num">{{item.value}}</div>
                 <span class="item-title">{{item.name}}</span>
                 <span class="item-title">{{item.name}}</span>
               </div>
               </div>
-            </div>
+            </div> -->
             <div class="power-box">
             <div class="power-box">
-              <p class="apparatus-title">课堂与授权</p>
+              <p class="inuse-title">课堂与授权</p>
               <div class="power-item" v-for="(item,index) in powerList.class" :key="index">
               <div class="power-item" v-for="(item,index) in powerList.class" :key="index">
                 <div class="item-num">{{item.value}}</div>
                 <div class="item-num">{{item.value}}</div>
                 <span class="item-title">{{item.name}}</span>
                 <span class="item-title">{{item.name}}</span>
               </div>
               </div>
-            </div> -->
+            </div>
           </div>
           </div>
           <div class="minxinbox">
           <div class="minxinbox">
             <div class="lessons-box">
             <div class="lessons-box">
@@ -123,10 +123,12 @@
   import { ref, getCurrentInstance, defineEmits, computed, onMounted, watch } from 'vue'
   import { ref, getCurrentInstance, defineEmits, computed, onMounted, watch } from 'vue'
   import Xlines from '@/components/echarts/Xline.vue'
   import Xlines from '@/components/echarts/Xline.vue'
   import * as echarts from 'echarts'
   import * as echarts from 'echarts'
+  import { useStore } from 'vuex'
   let props = defineProps({
   let props = defineProps({
     detailsData: Object,
     detailsData: Object,
   })
   })
   console.log(props.detailsData, '子组件')
   console.log(props.detailsData, '子组件')
+  const store = useStore()
   let value1 = ref('')
   let value1 = ref('')
   let value = ref()
   let value = ref()
   let $myemit = defineEmits(['myback'])
   let $myemit = defineEmits(['myback'])
@@ -456,6 +458,7 @@
     { title: '学生参与总时数', icon: '#icon-_shijian_xiaoshuai', value: '8小时', key: 'participationnum' },
     { title: '学生参与总时数', icon: '#icon-_shijian_xiaoshuai', value: '8小时', key: 'participationnum' },
     { title: '课堂总数', icon: '#icon-ketang', value: '45', key: 'classnum' },
     { title: '课堂总数', icon: '#icon-ketang', value: '45', key: 'classnum' },
     { title: '课堂总时数', icon: '#icon--shijian ', value: '648', key: 'classtime' },
     { title: '课堂总时数', icon: '#icon--shijian ', value: '648', key: 'classtime' },
+    { title: 'HiTeach版本', icon: '#icon-banbenhao ', value: '0', key: 'hiteachVersions' },
   ])
   ])
   let powerList = ref({
   let powerList = ref({
     facility: [
     facility: [
@@ -464,9 +467,10 @@
       { name: '授权设备', value: 0, }
       { name: '授权设备', value: 0, }
     ],
     ],
     class: [
     class: [
+      {name:'装置数量',value:0},
       { name: '928授权', value: 0 },
       { name: '928授权', value: 0 },
       { name: 'ID授权', value: 0 },
       { name: 'ID授权', value: 0 },
-      { name: '设备授权', value: 0 },
+      { name: '装置授权', value: 0 },
       { name: '综合授权', value: 0 },
       { name: '综合授权', value: 0 },
     ]
     ]
   })
   })
@@ -488,10 +492,16 @@
     { icon: '#icon--caozuorizhi', title: 'IES课程', content: '使用IES课程', state: true, value: 0 },
     { icon: '#icon--caozuorizhi', title: 'IES课程', content: '使用IES课程', state: true, value: 0 },
     { icon: '#icon--caozuorizhi', title: 'webIrs', content: '使用webIrs', state: true, value: 0 },
     { icon: '#icon--caozuorizhi', title: 'webIrs', content: '使用webIrs', state: true, value: 0 },
     { icon: '#icon--caozuorizhi', title: 'IRS', content: '使用IRS', state: true, value: 0 },
     { icon: '#icon--caozuorizhi', title: 'IRS', content: '使用IRS', state: true, value: 0 },
-    { icon: '#icon--caozuorizhi', title: 'HiTA', content: '使用HiTA', state: false, value: 0 },
-    { icon: '#icon--caozuorizhi', title: 'HaBoard', content: '使用HaBoard', state: false, value: 0 },
-    { icon: '#icon--caozuorizhi', title: 'IES5资源', content: '使用IES5资源', state: true, value: 0 },
-    { icon: '#icon--caozuorizhi', title: 'T指数', content: '课程T绿灯数', state: true, value: 0 },
+    { icon: '#icon--caozuorizhi', title: 'HiTA', content: '使用HiTA', state: true, value: 0 },
+    { icon: '#icon--caozuorizhi', title: 'HaBoard', content: '使用HaBoard', state: true, value: 0 },
+    { icon: '#icon--caozuorizhi', title: 'HaBoard', content: '使用IES5资源', state: true, value: 0 },
+    { icon: '#icon--caozuorizhi', title: 'text', content: '使用文字云', state: false, value: 0 },
+    { icon: '#icon--caozuorizhi', title: 'ClouDAS', content: '使用ClouDAS', state: false, value: 0 },
+    { icon: '#icon--caozuorizhi', title: 'GPT', content: '使用GPT', state: false, value: 0 },
+    { icon: '#icon--caozuorizhi', title: 'IES5测验', content: '使用IES5卷测验', state: true, value: 0 },
+    { icon: '#icon--caozuorizhi', title: 'Excel测验', content: '使用Excel卷测验', state: true, value: 0 },
+    { icon: '#icon--caozuorizhi', title: '纸本测验', content: '使用纸本测验', state: true, value: 0 },
+    { icon: '#icon--caozuorizhi', title: 'T课堂', content: '符合T课堂数', state: true, value: 0 },
   ])
   ])
   let inuseList = ref([
   let inuseList = ref([
     { title: '学习任务数', value: 15, icon: '#icon-renwu', percent: '41.2%', class: 'task', textClass: 'task-text' },
     { title: '学习任务数', value: 15, icon: '#icon-renwu', percent: '41.2%', class: 'task', textClass: 'task-text' },
@@ -504,7 +514,8 @@
     { name: '互动型态课堂', value: 20, percent: '30%', class: 'accomplish', textClass: 'accomplish-text' },
     { name: '互动型态课堂', value: 20, percent: '30%', class: 'accomplish', textClass: 'accomplish-text' },
     { name: '任务型态课堂', value: 20, percent: '10%', class: 'topic', textClass: 'topic-text' },
     { name: '任务型态课堂', value: 20, percent: '10%', class: 'topic', textClass: 'topic-text' },
     { name: '差异化形态课堂', value: 20, percent: '5%', class: 'interaction', textClass: 'interaction-text' },
     { name: '差异化形态课堂', value: 20, percent: '5%', class: 'interaction', textClass: 'interaction-text' },
-    { name: '测验型态课堂', value: 30, percent: '15%', class: 'testclass', textClass: 'testclass-text' },
+    { name: '协作型态课堂', value: 30, percent: '15%', class: 'testclass', textClass: 'testclass-text' },
+    { name: '互评型态课堂', value: 30, percent: '15%', class: 'testclass', textClass: 'testclass-text' },
     { name: '无型态课堂', value: 0, percent: '0%', class: 'noneclass', textClass: 'noneclassclass-text' },
     { name: '无型态课堂', value: 0, percent: '0%', class: 'noneclass', textClass: 'noneclassclass-text' },
     { name: '未上课', value: 0, percent: '0%', class: 'noneclass', textClass: 'noneclassclass-text' },
     { name: '未上课', value: 0, percent: '0%', class: 'noneclass', textClass: 'noneclassclass-text' },
   ])
   ])
@@ -557,7 +568,7 @@
           }
           }
         },
         },
         boundaryGap: true, // 坐标轴两边是否留白
         boundaryGap: true, // 坐标轴两边是否留白
-        data: ['合作', '互动', '任务', '差异化', '测验', '无型态', '未上课']
+        data: ['合作', '互动', '任务', '差异化', '协作','互评', '无型态', '未上课']
       },
       },
       yAxis: [
       yAxis: [
         {
         {
@@ -616,7 +627,7 @@
               }
               }
             }
             }
           },
           },
-          barMaxWidth: '20%',
+          barMaxWidth: '15%',
         }
         }
       ]
       ]
     }
     }
@@ -655,27 +666,39 @@
     basicaList.value[1].value = stuLessonLengMin
     basicaList.value[1].value = stuLessonLengMin
     basicaList.value[2].value = lessonRecord
     basicaList.value[2].value = lessonRecord
     basicaList.value[3].value = lessonLengMin
     basicaList.value[3].value = lessonLengMin
-  
+    let versionvalue=store.state.hiteachVs ? store.state.hiteachVs : '无'
+    basicaList.value[4].value =versionvalue
+   console.log(store,'vuex内容')
     //处理课中使用数据
     //处理课中使用数据
-    let { useIES, useWebIrs, useDeviceIrs, useHita, useHaboard, useIES5Resource, tGreen } = propsbox.detailsData
-    lessonsList.value[0].value = useIES
-    lessonsList.value[1].value = useWebIrs
-    lessonsList.value[2].value = useDeviceIrs
-    lessonsList.value[3].value = useHita
-    lessonsList.value[4].value = useHaboard
-    lessonsList.value[5].value = useIES5Resource
-    lessonsList.value[6].value = tGreen
+    let { useIES, useWebIrs, useDeviceIrs, useHita, useHaboard, useIES5Resource, tGreen,useWordCloud,useClouDAS,useGPT,useIesTest,useExcelTest,usePaperTest,tLesson} = propsbox.detailsData
+    lessonsList.value[0].value = useIES ?useIES:0
+    lessonsList.value[1].value = useWebIrs ? useWebIrs:0
+    lessonsList.value[2].value = useDeviceIrs ? useDeviceIrs:0
+    lessonsList.value[3].value = useHita ? useHita:0
+    lessonsList.value[4].value = useHaboard ?  useHaboard:0
+    lessonsList.value[5].value =useIES5Resource ? useIES5Resource:0
+    //由hita 调整为 文字云
+    lessonsList.value[6].value = useWordCloud ?useWordCloud:0
+    //由HaBoard 调整为 ClouDAS
+    lessonsList.value[7].value = useClouDAS ? useClouDAS:0
+    //增加使用GPT
+    lessonsList.value[8].value = useGPT ?useGPT:0
+    //由IES5资源调整为 使用IES5卷测验
+    lessonsList.value[9].value = useIesTest ? useIesTest:0
+    //新增Excel
+    lessonsList.value[10].value=useExcelTest ? useExcelTest:0
+    //新增纸本
+    lessonsList.value[11].value=usePaperTest ?usePaperTest:0
+    //符合T课堂数
+    lessonsList.value[12].value=tLesson ? tLesson:0
   
   
-    //授权占比
-    // let { deviceCnt, deviceNoAuth, deviceAuth, lessonCnt928, lessonCntId, lessonCntDevice, lessonCntIdDevice } = propsbox.detailsData
-    // powerList.value.facility[0].value = deviceCnt
-    // // basicaList.value[2].value = deviceCnt
-    // powerList.value.facility[1].value = deviceNoAuth
-    // powerList.value.facility[2].value = deviceAuth
-    // powerList.value.class[0].value = lessonCnt928
-    // powerList.value.class[1].value = lessonCntId
-    // powerList.value.class[2].value = lessonCntDevice
-    // powerList.value.class[3].value = lessonCntIdDevice
+    //授权内容
+    let {lessonCnt928,lessonCntId, lessonCntDevice, lessonCntIdDevice,deviceCnt } = propsbox.detailsData
+    powerList.value.class[0].value = deviceCnt
+    powerList.value.class[1].value = lessonCnt928
+    powerList.value.class[2].value = lessonCntId
+    powerList.value.class[3].value = lessonCntDevice
+    powerList.value.class[4].value = lessonCntIdDevice
     //处理任务数、作品完成、题目等。。。。
     //处理任务数、作品完成、题目等。。。。
     let { mission, missionFin, item, interact } = propsbox.detailsData
     let { mission, missionFin, item, interact } = propsbox.detailsData
     inuseList.value[0].value = mission
     inuseList.value[0].value = mission
@@ -684,25 +707,23 @@
     inuseList.value[3].value = interact
     inuseList.value[3].value = interact
   
   
     //处理多形态课堂
     //处理多形态课堂
-    let { lTypeCoop, lTypeIact, lTypeMis, lTypeTst, lTypeDif, lTypeNone,lessonLeng0} = propsbox.detailsData
+    let { lTypeCoop, lTypeIact, lTypeMis, lTypeTst, lTypeDif, lTypeNone,lessonLeng0,learnCoop,learnPeer} = propsbox.detailsData
     let totalNum = [lTypeCoop, lTypeIact, lTypeMis, lTypeTst, lTypeDif].reduce((prev, cur) => { return prev + cur }, 0)
     let totalNum = [lTypeCoop, lTypeIact, lTypeMis, lTypeTst, lTypeDif].reduce((prev, cur) => { return prev + cur }, 0)
     echartData.value.total = totalNum
     echartData.value.total = totalNum
     console.log(totalNum)
     console.log(totalNum)
     classType.value[0].value = lTypeCoop
     classType.value[0].value = lTypeCoop
-    classType.value[0].percent = lTypeCoop === 0 ? 0 : (lTypeCoop / totalNum).toFixed(2) * 100
     classType.value[1].value = lTypeIact
     classType.value[1].value = lTypeIact
-    classType.value[1].percent = lTypeIact === 0 ? 0 : (lTypeIact / totalNum).toFixed(2) * 100
     classType.value[2].value = lTypeMis
     classType.value[2].value = lTypeMis
-    classType.value[2].percent = lTypeMis === 0 ? 0 : (lTypeMis / totalNum).toFixed(2) * 100
-    classType.value[3].value = lTypeTst
-    classType.value[3].percent = lTypeTst === 0 ? 0 : (lTypeTst / totalNum).toFixed(2) * 100
-    classType.value[4].value = lTypeDif
-    classType.value[4].percent = lTypeDif === 0 ? 0 : (lTypeDif / totalNum).toFixed(2) * 100
-    classType.value[4].value = lTypeNone
-    classType.value[5].value = lessonLeng0 ? lessonLeng0:0
-  
+    classType.value[3].value = lTypeDif
+    //由测试改为 协作
+    classType.value[4].value = learnCoop
+    //新增互评
+    classType.value[5].value = learnPeer
+    classType.value[6].value = lTypeNone
+    classType.value[7].value = lessonLeng0 ? lessonLeng0:0
+      
     //echarts占比
     //echarts占比
-    echartData.value.xlines.series[0].data = [lTypeCoop, lTypeIact, lTypeMis, lTypeTst, lTypeDif, lTypeNone, classType.value[5].value]
+    echartData.value.xlines.series[0].data = [lTypeCoop, lTypeIact, lTypeMis, lTypeDif,learnCoop,learnPeer, lTypeNone,lessonLeng0]
     // echartData.value.xlines.series[1].data = [classType.value[1].percent]
     // echartData.value.xlines.series[1].data = [classType.value[1].percent]
     // echartData.value.xlines.series[2].data = [classType.value[2].percent]
     // echartData.value.xlines.series[2].data = [classType.value[2].percent]
     // echartData.value.xlines.series[3].data = [classType.value[3].percent]
     // echartData.value.xlines.series[3].data = [classType.value[3].percent]
@@ -769,7 +790,7 @@ onMounted(() => {
     padding-top: 1%;
     padding-top: 1%;
   }
   }
   .contentbox {
   .contentbox {
-    width: 98%;
+    width: 100%;
     /* padding: 1% 1%; */
     /* padding: 1% 1%; */
     /* background: rgb(250, 250, 250); */
     /* background: rgb(250, 250, 250); */
     /* height: 85vh; */
     /* height: 85vh; */
@@ -796,6 +817,7 @@ onMounted(() => {
     display: flex;
     display: flex;
     flex-wrap: nowrap;
     flex-wrap: nowrap;
     justify-content: space-between;
     justify-content: space-between;
+    line-height: 40px;
   }
   }
   .apparatusAndpower {
   .apparatusAndpower {
     width: 100%;
     width: 100%;
@@ -806,14 +828,14 @@ onMounted(() => {
   }
   }
   .apparatus-box,
   .apparatus-box,
   .power-box {
   .power-box {
-    width: 32%;
+    width: 50%;
     box-shadow: 0 2px 5px #e9e9e9;
     box-shadow: 0 2px 5px #e9e9e9;
     background: #fff;
     background: #fff;
     margin: 0.5%;
     margin: 0.5%;
     border-radius: 5px;
     border-radius: 5px;
     display: flex;
     display: flex;
-    justify-content: space-between;
-    /* align-items: center; */
+    justify-content: space-around;
+    align-items: center;
     flex-wrap: wrap;
     flex-wrap: wrap;
   }
   }
   .apparatus-item {
   .apparatus-item {
@@ -825,22 +847,23 @@ onMounted(() => {
     margin: 1%;
     margin: 1%;
   }
   }
   .power-item {
   .power-item {
-    width: 23%;
-    margin: 0% 1%;
+    width: 18%;
+    height:80px;
     box-shadow: 0 2px 5px #e9e9e9;
     box-shadow: 0 2px 5px #e9e9e9;
     background: #fff;
     background: #fff;
     border-radius: 5px;
     border-radius: 5px;
     margin: 1%;
     margin: 1%;
+    line-height: 40px;
   }
   }
   .apparatus-title {
   .apparatus-title {
-    font-size: 16px;
-    margin-bottom: 5px;
-    border-bottom: 1px dashed #e9e9e9;
-    line-height: 40px;
     width: 100%;
     width: 100%;
     background: #dfe6e9;
     background: #dfe6e9;
-    color: #fff;
+    margin-bottom: 5px;
+    line-height: 25px;
+    border-bottom: 1px dashed #e9e9e9;
+    font-size: 16px;
     font-weight: bold;
     font-weight: bold;
+    color: #fff;
   }
   }
   .inuse-title {
   .inuse-title {
     width: 100%;
     width: 100%;
@@ -858,7 +881,7 @@ onMounted(() => {
   }
   }
   .basicadata-item {
   .basicadata-item {
     display: flex;
     display: flex;
-    width: 20%;
+    width: 18%;
     padding: 5px 5px;
     padding: 5px 5px;
     flex-direction: column;
     flex-direction: column;
     /* height: 60px; */
     /* height: 60px; */
@@ -867,6 +890,7 @@ onMounted(() => {
     box-shadow: 0 2px 5px #e9e9e9;
     box-shadow: 0 2px 5px #e9e9e9;
     background: #fff;
     background: #fff;
     margin: 0.5%;
     margin: 0.5%;
+    align-items: center;
   }
   }
   .item-title-images {
   .item-title-images {
     width: 100%;
     width: 100%;
@@ -907,7 +931,7 @@ onMounted(() => {
     border-radius: 5px;
     border-radius: 5px;
     background: #fff;
     background: #fff;
     box-shadow: 0 2px 5px #e9e9e9;
     box-shadow: 0 2px 5px #e9e9e9;
-    margin: 0.5% 1%;
+    margin: 0.5%;
     overflow: hidden;
     overflow: hidden;
     overflow-y: auto;
     overflow-y: auto;
   }
   }
@@ -976,7 +1000,7 @@ onMounted(() => {
     color: #007fff;
     color: #007fff;
   }
   }
   .inuse-left {
   .inuse-left {
-    width: 100%;
+    width: 50%;
     box-shadow: 0 2px 5px #e9e9e9;
     box-shadow: 0 2px 5px #e9e9e9;
     background: #fff;
     background: #fff;
     margin: 0.5%;
     margin: 0.5%;
@@ -986,13 +1010,14 @@ onMounted(() => {
     align-items: center;
     align-items: center;
     flex-wrap: wrap;
     flex-wrap: wrap;
   }
   }
+
   .inuse-right {
   .inuse-right {
     width: 49.5%;
     width: 49.5%;
     margin-left: 0%;
     margin-left: 0%;
     border-radius: 5px;
     border-radius: 5px;
     background: #fff;
     background: #fff;
     box-shadow: 0 2px 5px #e9e9e9;
     box-shadow: 0 2px 5px #e9e9e9;
-    margin: 0.5% 0%;
+    margin: 0.5%;
     /* margin-left: 1%; */
     /* margin-left: 1%; */
     position: relative;
     position: relative;
   }
   }
@@ -1006,7 +1031,7 @@ onMounted(() => {
     border-radius: 5px;
     border-radius: 5px;
     /* box-shadow: 0 2px 5px #e9e9e9; */
     /* box-shadow: 0 2px 5px #e9e9e9; */
     border: 1px solid #e9e9e9;
     border: 1px solid #e9e9e9;
-    margin: 0.5%;
+    margin: 1%;
   }
   }
   .inuseicon {
   .inuseicon {
     width: 1.6em;
     width: 1.6em;
@@ -1226,6 +1251,9 @@ onMounted(() => {
   .noneclassclass-text {
   .noneclassclass-text {
     color: #95a5a6 !important;
     color: #95a5a6 !important;
   }
   }
+  .lessons-item:last-child{
+    margin-bottom: 1%;
+  }
   @media screen and (max-width: 1400px) {
   @media screen and (max-width: 1400px) {
     .basicadata-item {
     .basicadata-item {
       line-height: 30px !important;
       line-height: 30px !important;

+ 35 - 14
TEAMModelBI/ClientApp/src/view/userInquire/socrates.vue

@@ -30,7 +30,7 @@
         <!-- <div class="socrates-echatrs">
         <!-- <div class="socrates-echatrs">
             <bars :barData="ecahrtsdata"></bars>
             <bars :barData="ecahrtsdata"></bars>
         </div> -->
         </div> -->
-        <div class="tnum-content">
+        <div class="tnum-content"  v-if="sokratesEchart">
                 <div class="selectbox">
                 <div class="selectbox">
                     <div><el-button v-for="item in buttonSelect" :key="item.value" :type="item.click ? 'primary':''" size="small" class="clickbox" @click="selectTime(item.value)">{{item.name}}</el-button></div>
                     <div><el-button v-for="item in buttonSelect" :key="item.value" :type="item.click ? 'primary':''" size="small" class="clickbox" @click="selectTime(item.value)">{{item.name}}</el-button></div>
                     <div class="nowaday-time">时间:<span class="time-values">{{hiteachDatas.appear.start_date}}~{{hiteachDatas.appear.end_date}}</span></div>
                     <div class="nowaday-time">时间:<span class="time-values">{{hiteachDatas.appear.start_date}}~{{hiteachDatas.appear.end_date}}</span></div>
@@ -61,7 +61,10 @@
                         </div>
                         </div>
                     </div>
                     </div>
                 </div>
                 </div>
-            </div>
+        </div>
+        <div class="tnum-content" v-else>
+            <div class="not-coupons">暂无数据</div>
+        </div>
     </div>
     </div>
  </template>
  </template>
  <script setup>
  <script setup>
@@ -361,6 +364,7 @@ let proportiondata = ref({
         },
         },
     ]
     ]
 })
 })
+let sokratesEchart=ref(true)
 let zb = ref()
 let zb = ref()
 onMounted(() => {
 onMounted(() => {
     initdatas()
     initdatas()
@@ -381,20 +385,23 @@ function initdatas(){
         presupposed.value.state=false
         presupposed.value.state=false
     }
     }
     //处理total数据
     //处理total数据
-    primary.value[0].value=hiteach_data.total.t_data ? hiteach_data.total.t_data:0
-    primary.value[1].value=hiteach_data.total.t_green ? hiteach_data.total.t_green:0
-    primary.value[2].value=hiteach_data.total.double_green_light ? hiteach_data.total.double_green_light:0
-    primary.value[3].value=hiteach_data.total.all_total ?  hiteach_data.total.all_total:0
+    primary.value[0].value=hiteach_data && hiteach_data.total.t_data ? hiteach_data.total.t_data:0
+    primary.value[1].value=hiteach_data && hiteach_data.total.t_green ? hiteach_data.total.t_green:0
+    primary.value[2].value=hiteach_data && hiteach_data.total.double_green_light ? hiteach_data.total.double_green_light:0
+    primary.value[3].value=hiteach_data && hiteach_data.total.all_total ?  hiteach_data.total.all_total:0
 
 
-    auxiliary.value[0].value='XXX'
-    auxiliary.value[1].value=hiteach_data.total.personal_comment ? hiteach_data.total.personal_comment:0
-    auxiliary.value[2].value=hiteach_data.total.watchHistory ?  hiteach_data.total.watchHistory:0
-    auxiliary.value[3].value='XXX'
+    auxiliary.value[0].value=hiteach_data ?.total ?.public_count
+    auxiliary.value[1].value=hiteach_data&& hiteach_data.total.personal_comment ? hiteach_data.total.personal_comment:0
+    auxiliary.value[2].value=hiteach_data && hiteach_data.total.watchHistory ?  hiteach_data.total.watchHistory:0
+    auxiliary.value[3].value=hiteach_data ?.total ?.material_count
+    if(!hiteach_data){
+        sokratesEchart.value=false
+    }
     //处理下方图表
     //处理下方图表
-    hiteachDatas.value.weeks=hiteach_data.this_week
-    hiteachDatas.value.months=hiteach_data.this_month
-    hiteachDatas.value.years=hiteach_data.this_year
-    hiteachDatas.value.appear=hiteach_data.this_week
+    hiteachDatas.value.weeks=hiteach_data && hiteach_data.this_week ? hiteach_data.this_week:0
+    hiteachDatas.value.months= hiteach_data && hiteach_data.this_month ?hiteach_data.this_month:0
+    hiteachDatas.value.years= hiteach_data && hiteach_data.this_year ?hiteach_data.this_year:0
+    hiteachDatas.value.appear=hiteach_data && hiteach_data.this_week ?hiteach_data.this_week:0
     tdatas.value[0].values=hiteachDatas.value.appear.duration
     tdatas.value[0].values=hiteachDatas.value.appear.duration
     tdatas.value[1].values=hiteachDatas.value.appear.attendance
     tdatas.value[1].values=hiteachDatas.value.appear.attendance
     tdatas.value[2].values=hiteachDatas.value.appear.interaction
     tdatas.value[2].values=hiteachDatas.value.appear.interaction
@@ -403,6 +410,10 @@ function initdatas(){
 }
 }
 function selectTime(values) {
 function selectTime(values) {
     console.log(values)
     console.log(values)
+    if(!props.sokratesdatas.hiteach_data){
+        sokratesEchart.value=false
+        return
+    }
     let hiteach_data=props.sokratesdatas.hiteach_data
     let hiteach_data=props.sokratesdatas.hiteach_data
     values === 'week' ?  hiteachDatas.value.appear=hiteach_data.this_week:values === 'month' ? hiteachDatas.value.appear=hiteach_data.this_month:
     values === 'week' ?  hiteachDatas.value.appear=hiteach_data.this_week:values === 'month' ? hiteachDatas.value.appear=hiteach_data.this_month:
     values === 'year' ? hiteachDatas.value.appear=hiteach_data.this_year:values ==='total' ? hiteachDatas.value.appear=hiteach_data.total:''
     values === 'year' ? hiteachDatas.value.appear=hiteach_data.this_year:values ==='total' ? hiteachDatas.value.appear=hiteach_data.total:''
@@ -571,4 +582,14 @@ watch(()=>props,(newvalue)=>{
 .time-values,.content-num{
 .time-values,.content-num{
     color:#409EFF !important;
     color:#409EFF !important;
 }
 }
+.not-coupons{
+    display: flex;
+    height:90%;
+    align-items: center;
+    justify-content: center;
+    font-size:22px;
+    font-weight: 700;
+    color: #73767a;
+    /* line-height: 160px; */
+}
 </style>
 </style>

+ 1 - 1
TEAMModelBI/ClientApp/src/view/userInquire/userdetail.vue

@@ -206,7 +206,7 @@ function inidatas(){
     userdata.value.country=lang ==='zh-cn' ? '中文简体':lang ==='zh-tw' ?'中文繁体':'英语'
     userdata.value.country=lang ==='zh-cn' ? '中文简体':lang ==='zh-tw' ?'中文繁体':'英语'
     userdata.value.company=unitName
     userdata.value.company=unitName
     userdata.value.type =unitType == '1'? '基礎教育機構':
     userdata.value.type =unitType == '1'? '基礎教育機構':
-    unitType =='2' ? 中等教育機構:unitType=='3' ? '高等教育機構':unitType=='4' ? '政府單位機構':unitType=='5' ? 'NGO機構':
+    unitType =='2' ? '中等教育機構':unitType=='3' ? '高等教育機構':unitType=='4' ? '政府單位機構':unitType=='5' ? 'NGO機構':
     unitType =='6' ? '企業機構':unitType=='7' ? '其他':unitType=='8' ? '學前教育':unitType=='9' ? '特殊教育':''
     unitType =='6' ? '企業機構':unitType=='7' ? '其他':unitType=='8' ? '學前教育':unitType=='9' ? '特殊教育':''
     userdata.value.professional=jobTitle
     userdata.value.professional=jobTitle
 }
 }

+ 2 - 2
TEAMModelBI/Controllers/BIProductAnalysis/ProductAnalysisController.cs

@@ -64,7 +64,7 @@ namespace TEAMModelBI.Controllers.ProductAnalysis
                 var cosmosClient = _azureCosmos.GetCosmosClient();
                 var cosmosClient = _azureCosmos.GetCosmosClient();
                 var redisClinet8 = _azureRedis.GetRedisClient(8);
                 var redisClinet8 = _azureRedis.GetRedisClient(8);
                 if (!jsonElement.TryGetProperty("dateFrom", out JsonElement dateFromJobj)) return BadRequest();//查詢日期:起始(string)[例]2023-03-05
                 if (!jsonElement.TryGetProperty("dateFrom", out JsonElement dateFromJobj)) return BadRequest();//查詢日期:起始(string)[例]2023-03-05
-                if(!jsonElement.TryGetProperty("dateTo", out JsonElement dateToJobj)) return BadRequest();//查詢日期:結束(string)[例]2023-03-27
+                if (!jsonElement.TryGetProperty("dateTo", out JsonElement dateToJobj)) return BadRequest();//查詢日期:結束(string)[例]2023-03-27
                 if (!jsonElement.TryGetProperty("prod", out JsonElement prodJobj)) return BadRequest();//產品 HiTeach, HiTeachCC, HiTA
                 if (!jsonElement.TryGetProperty("prod", out JsonElement prodJobj)) return BadRequest();//產品 HiTeach, HiTeachCC, HiTA
                 string prod = (prodJobj.ToString().Equals("HiTeach") || prodJobj.ToString().Equals("HiTeachCC") || prodJobj.ToString().Equals("HiTA")) ? prodJobj.ToString() : string.Empty;
                 string prod = (prodJobj.ToString().Equals("HiTeach") || prodJobj.ToString().Equals("HiTeachCC") || prodJobj.ToString().Equals("HiTA")) ? prodJobj.ToString() : string.Empty;
                 if(string.IsNullOrWhiteSpace(prod)) return BadRequest();
                 if(string.IsNullOrWhiteSpace(prod)) return BadRequest();
@@ -116,7 +116,7 @@ namespace TEAMModelBI.Controllers.ProductAnalysis
                     }
                     }
                 }
                 }
 
 
-                ////取得產品分析資訊
+                ////取得IOT產品分析資訊
                 List<ProdAnalysisApiResult> result = new List<ProdAnalysisApiResult>();
                 List<ProdAnalysisApiResult> result = new List<ProdAnalysisApiResult>();
                 string Sql = $"SELECT * FROM c WHERE c.toolType = '{prod}' AND c.dateUnit = '{dateUnit}' AND c.dateTime >= {dateTimeFromSec} AND c.dateTime <= {dateTimeToSec}";
                 string Sql = $"SELECT * FROM c WHERE c.toolType = '{prod}' AND c.dateUnit = '{dateUnit}' AND c.dateTime >= {dateTimeFromSec} AND c.dateTime <= {dateTimeToSec}";
                 if(schoolIds.Count > 0)
                 if(schoolIds.Count > 0)

+ 164 - 0
TEAMModelBI/Controllers/BISchool/SchoolController.cs

@@ -10,6 +10,7 @@ using Newtonsoft.Json;
 using StackExchange.Redis;
 using StackExchange.Redis;
 using System;
 using System;
 using System.Collections.Generic;
 using System.Collections.Generic;
+using System.Dynamic;
 using System.IO;
 using System.IO;
 using System.Linq;
 using System.Linq;
 using System.Net;
 using System.Net;
@@ -2384,6 +2385,154 @@ namespace TEAMModelBI.Controllers.BISchool
             }
             }
         }
         }
 
 
+        /// <summary>
+        /// 取得某學校產品購買紀錄
+        /// </summary>
+        /// <param name="request"></param>
+        /// <returns></returns>
+        [ProducesDefaultResponseType]
+        [HttpPost("get-school-product")]
+        public async Task<IActionResult> GetSchoolProductInfo(JsonElement request)
+        {
+            try
+            {
+                if (!request.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
+                var db = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School");
+                var r8 = _azureRedis.GetRedisClient(8);
+
+                List<SchoolProductSerial> serial = new(); //承接DB資料用:序號
+                List<SerialInfoBaseWithdeviceBoundExt> serialResult = new(); //最後要輸出的序號結果
+                List<SchoolProductService> serviceProduct = new(); //承接DB資料用:服務
+                List<SchoolProductOrder> serviceOrder = new(); //服務各產品購買紀錄
+                List<SchoolProductSumDataService> serviceSum = new(); //服務各產品購買紀錄
+                List<SchoolProductHard> hard = new(); //承接DB資料用:硬體
+                SchoolProductSum productSum = new(); //承接DB資料用:產品目前狀態 
+                List<SchoolProductSumProdInfo> prodinfo = new(); //產品資訊列表(名稱、八碼)
+                long UTCNow = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
+
+                ////取得各產品目前可得數量
+                var response = await db.ReadItemStreamAsync(school_code.ToString(), new PartitionKey($"ProductSum"));
+                if (response.Status == 200)
+                {
+                    using var json = await JsonDocument.ParseAsync(response.ContentStream);
+                    productSum = json.ToObject<SchoolProductSum>();
+                    prodinfo = productSum.prodinfo;
+                    serviceSum = productSum.service;
+                }
+
+                //軟體
+                List<string> serialPermitList = getSerialPermitProdcodeList();
+                string serialPermitJsonStr = JsonConvert.SerializeObject(serialPermitList);
+                string serialQueryText = $"SELECT * FROM c WHERE c.dataType = 'serial' AND ARRAY_CONTAINS({serialPermitJsonStr}, c.prodCode)";
+                await foreach (var itemsr in db.GetItemQueryStreamIterator(queryText: serialQueryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Product-{school_code}") }))
+                {
+                    using var json = await JsonDocument.ParseAsync(itemsr.ContentStream);
+                    if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
+                    {
+                        deviceForCoreService uuidForCore;
+                        foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
+                        {
+                            serial.Add(obj.ToObject<SchoolProductSerial>());
+                        }
+                    }
+                }
+
+                //服務
+                List<SchoolProductSumDataService> service = new List<SchoolProductSumDataService>();
+                SchoolProductSum schoolProductSum;
+                await foreach (var items in db.GetItemQueryStreamIterator(queryText: $"SELECT * FROM c WHERE c.id = '{school_code}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ProductSum") }))
+                {
+                    using var json = await JsonDocument.ParseAsync(items.ContentStream);
+                    if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
+                    {
+                        foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
+                        {
+                            schoolProductSum = obj.ToObject<SchoolProductSum>();
+                            service = schoolProductSum.service;
+                        }
+                    }
+                }
+                if (service.Count > 0)
+                {
+                    SchoolProductOrder spOrderRow;
+                    foreach (SchoolProductSumDataService serviceRow in service)
+                    {
+                        spOrderRow = new SchoolProductOrder();
+                        spOrderRow.prodCode = serviceRow.prodCode;
+                        spOrderRow.avaliable = serviceRow.avaliable;
+                        spOrderRow.avaliableStartDate = serviceRow.startDate;
+                        spOrderRow.avaliableEndDate = serviceRow.endDate;
+                        serviceOrder.Add(spOrderRow);
+                    }
+                }
+
+                //硬體
+                await foreach (var itemhd in db.GetItemQueryStreamIterator(queryText: $"SELECT * FROM c WHERE c.dataType = 'hard'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Product-{school_code}") }))
+                {
+                    using var json = await JsonDocument.ParseAsync(itemhd.ContentStream);
+                    if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
+                    {
+                        foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
+                        {
+                            hard.Add(obj.ToObject<SchoolProductHard>());
+                        }
+                    }
+                }
+
+                //空間計算
+                ////取得教師分配空間
+                long teach = 0;
+                var querysp = $"SELECT SUM(c.size) as size FROM c";
+                await foreach (var item in db.GetItemQueryStreamIterator(queryText: querysp, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school_code}") }))
+                {
+                    var jsonts = await JsonDocument.ParseAsync(item.ContentStream);
+                    foreach (var obj in jsonts.RootElement.GetProperty("Documents").EnumerateArray())
+                    {
+                        teach = obj.GetProperty("size").GetInt64() * 1073741824; //G換算
+                    }
+                }
+                ////學校已使用空間
+                long blobsize = 0;
+                RedisValue value = default;
+                value = r8.HashGet($"Blob:Record", $"{school_code}");
+                if (value != default && !value.IsNullOrEmpty)
+                {
+                    JsonElement record = value.ToString().ToObject<JsonElement>();
+                    if (record.TryGetInt64(out blobsize))
+                    {
+                    }
+                }
+                ////各項空間數值取得
+                Dictionary<string, double> catalog = new();
+                SortedSetEntry[] Scores = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Blob:Catalog:{school_code}");
+                if (Scores != null)
+                {
+                    foreach (var score in Scores)
+                    {
+                        double val = score.Score;
+                        string key = score.Element.ToString();
+                        catalog.Add(key, val);
+                    }
+                }
+                dynamic space = new ExpandoObject();
+                space.size = blobsize;
+                space.teach = teach;
+                space.catalog = catalog;
+
+                //取得購買紀錄
+                List<object> order = await GetOrderHisFromCoreBBAsync(school_code.GetString());
+
+                //取得CC授權使用狀態
+                var hashs = await r8.HashGetAllAsync($"CC:License:{school_code.GetString()}");
+                var ccuser = hashs.Select(x => JsonDocument.Parse(x.Value.ToString())).ToList();
+
+                return Ok(new { serial = serial, service = serviceOrder, hard, space, order, ccuser });
+            }
+            catch (Exception ex)
+            {
+                return BadRequest();
+            }
+        }
         private async Task<string> getCoreAccessToken()
         private async Task<string> getCoreAccessToken()
         {
         {
             string AccessToken = "";
             string AccessToken = "";
@@ -2414,6 +2563,21 @@ namespace TEAMModelBI.Controllers.BISchool
             }
             }
         }
         }
 
 
+        //取得序號產品准許使用產品代碼列表
+        public static List<string> getSerialPermitProdcodeList()
+        {
+            List<string> allowProdCode = new List<string>(); //軟體許可產品列:HiTeach STD、TBL、PRO、HiTeach5;
+            allowProdCode.Add("J223IZ6M"); //HiTeach STD
+            allowProdCode.Add("3222C6D2"); //HiTeach TBL
+            allowProdCode.Add("J223IZAM"); //HiTeach PRO
+            allowProdCode.Add("J2236ZCX"); //HiTeach Lite
+            allowProdCode.Add("3222DNG2"); //HiTeach Mobile
+            allowProdCode.Add("3222IAVN"); //HiTeach Premium
+            allowProdCode.Add("BYJ6LZ6Z"); //HiTeach5
+            allowProdCode.Add("LZLL6ZEI"); //HiTeachCC
+            return allowProdCode;
+        }
+
         #endregion
         #endregion
 
 
         #region  顾问学校统计返回值
         #region  顾问学校统计返回值

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

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

File diff suppressed because it is too large
+ 697 - 191
TEAMModelBI/Controllers/BITmid/TmidController.cs


+ 34 - 6
TEAMModelBI/Controllers/Census/SchoolController.cs

@@ -1413,9 +1413,31 @@ namespace TEAMModelBI.Controllers.Census
             jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
             jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
             jsonElement.TryGetProperty("areaId", out JsonElement areaId);
             jsonElement.TryGetProperty("areaId", out JsonElement areaId);
 
 
+            ////IES5實體學校學區名稱
+            List<string> AreaIdList = new List<string>();
+            StringBuilder sqlBiArea = new($"SELECT DISTINCT VALUE c.areaId FROM c WHERE IS_DEFINED(c.areaId) AND NOT IS_NULL(c.areaId) AND c.areaId != ''");
+            await foreach (string item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<string>(queryText: sqlBiArea.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BIRel") }))
+            {
+                AreaIdList.Add(item);
+            }
+            Dictionary<string, string> areaDic = new Dictionary<string, string>();
+            string AreaListStr = JsonSerializer.Serialize(AreaIdList);
+            StringBuilder sqlArea = new($"SELECT c.id, c.name FROM c WHERE ARRAY_CONTAINS({AreaListStr}, c.id, true)");
+            await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryStreamIterator(queryText: sqlArea.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base-Area") }))
+            {
+                var json = await JsonDocument.ParseAsync(item.ContentStream);
+                foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
+                {
+                    string arId = obj.GetProperty("id").GetString();
+                    string arName = obj.GetProperty("name").GetString();
+                    if(!areaDic.ContainsKey(arId))
+                    {
+                        areaDic.Add(arId, arName);
+                    }
+                }
+            }
             //IES5實體學校
             //IES5實體學校
             StringBuilder sql = new($"select value(c) from c");
             StringBuilder sql = new($"select value(c) from c");
-
             if (!string.IsNullOrEmpty($"{role}") && !string.IsNullOrEmpty($"{tmdId}") && string.IsNullOrEmpty($"{areaId}"))
             if (!string.IsNullOrEmpty($"{role}") && !string.IsNullOrEmpty($"{tmdId}") && string.IsNullOrEmpty($"{areaId}"))
             {
             {
                 switch ($"{role}")
                 switch ($"{role}")
@@ -1434,12 +1456,15 @@ namespace TEAMModelBI.Controllers.Census
                 sql.Append($" where c.areaId ='{areaId}'");
                 sql.Append($" where c.areaId ='{areaId}'");
             }
             }
 
 
-            //List<string> scId = await CommonFind.FindScIds(cosmosClient, "select value(c.id) from c ", "Base");
             //取得學校BI統計中間件
             //取得學校BI統計中間件
             List<BIRelation> scInfos = new();
             List<BIRelation> scInfos = new();
             List<string> schIds = new();
             List<string> schIds = new();
             await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<BIRelation>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BIRel") }))
             await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<BIRelation>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BIRel") }))
             {
             {
+                if (!string.IsNullOrWhiteSpace(item.areaId) && areaDic.ContainsKey(item.areaId))
+                {
+                    item.areaName = areaDic[item.areaId];
+                }
                 scInfos.Add(item);
                 scInfos.Add(item);
                 schIds.Add(item.id);
                 schIds.Add(item.id);
             }
             }
@@ -1471,17 +1496,20 @@ namespace TEAMModelBI.Controllers.Census
             {
             {
                 vrAreaIdList.Add(item);
                 vrAreaIdList.Add(item);
             }
             }
-            Dictionary<string, string> areaDic = new Dictionary<string, string>();
+            //Dictionary<string, string> areaDic = new Dictionary<string, string>();
             string vrAreaListStr = JsonSerializer.Serialize(vrAreaIdList);
             string vrAreaListStr = JsonSerializer.Serialize(vrAreaIdList);
-            StringBuilder sqlArea = new($"SELECT c.id, c.name FROM c WHERE ARRAY_CONTAINS({vrAreaListStr}, c.id, true)");
-            await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryStreamIterator(queryText: sqlArea.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base-Area") }))
+            StringBuilder vrSqlArea = new($"SELECT c.id, c.name FROM c WHERE ARRAY_CONTAINS({vrAreaListStr}, c.id, true)");
+            await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryStreamIterator(queryText: vrSqlArea.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base-Area") }))
             {
             {
                 var json = await JsonDocument.ParseAsync(item.ContentStream);
                 var json = await JsonDocument.ParseAsync(item.ContentStream);
                 foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
                 foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
                 {
                 {
                     string arId = obj.GetProperty("id").GetString();
                     string arId = obj.GetProperty("id").GetString();
                     string arName = obj.GetProperty("name").GetString();
                     string arName = obj.GetProperty("name").GetString();
-                    areaDic.Add(arId, arName);
+                    if (!areaDic.ContainsKey(arId))
+                    {
+                        areaDic.Add(arId, arName);
+                    }  
                 }
                 }
             }
             }
             //取得虛擬學校資料
             //取得虛擬學校資料

+ 2 - 1
TEAMModelBI/Controllers/RepairApi/SchoolRepController.cs

@@ -581,6 +581,7 @@ namespace TEAMModelBI.Controllers.RepairApi
         public async Task<IActionResult> SetAllProdAnalysis()
         public async Task<IActionResult> SetAllProdAnalysis()
         {
         {
             var _azureCosmosClient = _azureCosmos.GetCosmosClient();
             var _azureCosmosClient = _azureCosmos.GetCosmosClient();
+            var _azureCosmosClientCsv2 = _azureCosmos.GetCosmosClient(name: "CoreServiceV2");
             var _azureCosmosClientCsv2Read = _azureCosmos.GetCosmosClient(name: "CoreServiceV2CnRead");
             var _azureCosmosClientCsv2Read = _azureCosmos.GetCosmosClient(name: "CoreServiceV2CnRead");
             var datetime = DateTimeOffset.UtcNow;
             var datetime = DateTimeOffset.UtcNow;
             var y = $"{datetime.Year}";
             var y = $"{datetime.Year}";
@@ -608,7 +609,7 @@ namespace TEAMModelBI.Controllers.RepairApi
                     {
                     {
                         string m = date.Substring(0, 2);
                         string m = date.Substring(0, 2);
                         string d = date.Substring(2, 2);
                         string d = date.Substring(2, 2);
-                        await BIProdAnalysis.BICreatDailyAnalData(_azureRedis, _azureCosmosClient, _azureCosmosClientCsv2Read, _dingDing, y, m, d);
+                        await BIProdAnalysis.BICreatDailyAnalData(_azureRedis, _azureCosmosClient, _azureCosmosClientCsv2, _azureCosmosClientCsv2Read, _dingDing, y, m, d);
                         resultKeys.Add($"{key}");
                         resultKeys.Add($"{key}");
                     }
                     }
                 }
                 }

+ 3 - 3
TEAMModelBI/TEAMModelBI.csproj

@@ -65,9 +65,9 @@
 		<SpaRoot>ClientApp\</SpaRoot>
 		<SpaRoot>ClientApp\</SpaRoot>
 		<DefaultItemExcludes>$(DefaultItemExcludes);$(SpaRoot)node_modules\**</DefaultItemExcludes>
 		<DefaultItemExcludes>$(DefaultItemExcludes);$(SpaRoot)node_modules\**</DefaultItemExcludes>
 		<UserSecretsId>078b5d89-7d90-4f6a-88fc-7d96025990a8</UserSecretsId>
 		<UserSecretsId>078b5d89-7d90-4f6a-88fc-7d96025990a8</UserSecretsId>
-		<Version>5.2311.15</Version>
-		<AssemblyVersion>5.2311.15.1</AssemblyVersion>
-		<FileVersion>5.2311.15.1</FileVersion>
+		<Version>5.2312.6</Version>
+		<AssemblyVersion>5.2312.6.1</AssemblyVersion>
+		<FileVersion>5.2312.6.1</FileVersion>
 		<Description>TEAMModelBI(BI)</Description>
 		<Description>TEAMModelBI(BI)</Description>
 		<PackageReleaseNotes>BI版本说明版本切换标记2022000908</PackageReleaseNotes>
 		<PackageReleaseNotes>BI版本说明版本切换标记2022000908</PackageReleaseNotes>
 		<PackageId>TEAMModelBI</PackageId>
 		<PackageId>TEAMModelBI</PackageId>

+ 131 - 0
TEAMModelBI/Tool/Extension/GeoRegion.cs

@@ -0,0 +1,131 @@
+using Microsoft.IdentityModel.Tokens;
+using System;
+using System.Collections.Generic;
+using System.Drawing.Drawing2D;
+using System.IdentityModel.Tokens.Jwt;
+using System.IO;
+using System.Text;
+using System.Text.Json;
+using TEAMModelOS.SDK.Extension;
+using TEAMModelOS.SDK.Models.Cosmos.BI;
+
+namespace TEAMModelBI.Models.Extension
+{
+    public static class GeoRegion
+    {
+        //取得國省市區地理資料架構
+        public static regiondata GetRegionData()
+        {
+            regiondata region = new regiondata();
+            //國際
+            var regionTw = new List<regionrow>();
+            using (StreamReader r = new StreamReader("JsonFile/Region/region_gl.json"))
+            {
+                string json = r.ReadToEnd();
+                regionTw = JsonSerializer.Deserialize<List<regionrow>>(json);
+                foreach (regionrow itemcy in regionTw)
+                {
+                    //country
+                    string countryCode = itemcy.code;
+                    if (!region.country.ContainsKey(countryCode))
+                    {
+                        region.country.Add(countryCode, new regionbase() { code = countryCode, name = itemcy.name });
+                    }
+                    //province 無
+                    //city
+                    if (itemcy.children != null)
+                    {
+                        foreach (JsonElement itemcyChild in itemcy.children)
+                        {
+                            regionrow itemct = itemcyChild.ToObject<regionrow>();
+                            string provinceCode = "tw"; //台灣的省代碼用"tw"
+                            string cityCode = itemct.code;
+                            if (!region.city.ContainsKey(countryCode)) region.city.Add(countryCode, new Dictionary<string, Dictionary<string, regionbase>>());
+                            if (!region.city[countryCode].ContainsKey(provinceCode)) region.city[countryCode].Add(provinceCode, new Dictionary<string, regionbase>());
+                            if (!region.city[countryCode][provinceCode].ContainsKey(cityCode)) region.city[countryCode][provinceCode].Add(cityCode, new regionbase() { code = cityCode, name = itemct.name });
+                            //dist
+                            if (itemct.children != null)
+                            {
+                                foreach (JsonElement itemctChild in itemct.children)
+                                {
+                                    regionrow itemds = itemctChild.ToObject<regionrow>();
+                                    string distCode = itemds.code;
+                                    if (!region.dist.ContainsKey(countryCode)) region.dist.Add(countryCode, new Dictionary<string, Dictionary<string, Dictionary<string, regionbase>>>());
+                                    if (!region.dist[countryCode].ContainsKey(provinceCode)) region.dist[countryCode].Add(provinceCode, new Dictionary<string, Dictionary<string, regionbase>>());
+                                    if (!region.dist[countryCode][provinceCode].ContainsKey(cityCode)) region.dist[countryCode][provinceCode].Add(cityCode, new Dictionary<string, regionbase>());
+                                    if (!region.dist[countryCode][provinceCode][cityCode].ContainsKey(distCode)) region.dist[countryCode][provinceCode][cityCode].Add(distCode, new regionbase() { code = distCode, name = itemds.name });
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+            //大陸
+            var regionCn = new List<regionrow>();
+            using (StreamReader r = new StreamReader("JsonFile/Region/region_cn.json"))
+            {
+                string json = r.ReadToEnd();
+                regionCn = JsonSerializer.Deserialize<List<regionrow>>(json);
+                //country
+                string countryCode = "CN";
+                string countryName = "中国";
+                if (!region.country.ContainsKey(countryCode))
+                {
+                    region.country.Add(countryCode, new regionbase() { code = countryCode, name = countryName });
+                }
+                //province
+                foreach (regionrow itempv in regionCn)
+                {
+                    string provinceCode = itempv.code.Replace("0000", "");
+                    if (!region.province.ContainsKey(countryCode)) region.province.Add(countryCode, new Dictionary<string, regionbase>());
+                    if (!region.province[countryCode].ContainsKey(provinceCode)) region.province[countryCode].Add(provinceCode, new regionbase() { code = provinceCode, name = itempv.name });
+                    //city
+                    if (itempv.children != null)
+                    {
+                        foreach (JsonElement itempvChild in itempv.children)
+                        {
+                            regionrow itemct = itempvChild.ToObject<regionrow>();
+                            string cityCode = itemct.code;
+                            if (!region.city.ContainsKey(countryCode)) region.city.Add(countryCode, new Dictionary<string, Dictionary<string, regionbase>>());
+                            if (!region.city[countryCode].ContainsKey(provinceCode)) region.city[countryCode].Add(provinceCode, new Dictionary<string, regionbase>());
+                            if (!region.city[countryCode][provinceCode].ContainsKey(cityCode)) region.city[countryCode][provinceCode].Add(cityCode, new regionbase() { code = cityCode, name = itemct.name });
+                            //dist
+                            if (itemct.children != null)
+                            {
+                                foreach (JsonElement itemctChild in itemct.children)
+                                {
+                                    regionrow itemds = itemctChild.ToObject<regionrow>();
+                                    string distCode = itemds.code;
+                                    if (!region.dist.ContainsKey(countryCode)) region.dist.Add(countryCode, new Dictionary<string, Dictionary<string, Dictionary<string, regionbase>>>());
+                                    if (!region.dist[countryCode].ContainsKey(provinceCode)) region.dist[countryCode].Add(provinceCode, new Dictionary<string, Dictionary<string, regionbase>>());
+                                    if (!region.dist[countryCode][provinceCode].ContainsKey(cityCode)) region.dist[countryCode][provinceCode].Add(cityCode, new Dictionary<string, regionbase>());
+                                    if (!region.dist[countryCode][provinceCode][cityCode].ContainsKey(distCode)) region.dist[countryCode][provinceCode][cityCode].Add(distCode, new regionbase() { code = distCode, name = itemds.name });
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+
+            return region;
+        }
+
+        public class regiondata
+        {
+            public Dictionary<string, regionbase> country { get; set; } = new();
+            public Dictionary<string, Dictionary<string, regionbase>> province { get; set; } = new();
+            public Dictionary<string, Dictionary<string, Dictionary<string, regionbase>>> city { get; set; } = new();
+            public Dictionary<string, Dictionary<string, Dictionary<string, Dictionary<string, regionbase>>>> dist { get; set; } = new();
+        }
+        public class regionbase
+        {
+            public string code { get; set; } //代碼
+            public string name { get; set; } //名稱
+        }
+        public class regionrow : regionbase
+        {
+            public List<object> children { get; set; }
+        }
+
+    }
+}

+ 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; }
-    }
-}

File diff suppressed because it is too large
+ 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>

File diff suppressed because it is too large
+ 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
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>
-
-

+ 105 - 95
TEAMModelOS.FunctionV4/CosmosDB/TriggerExam.cs

@@ -34,6 +34,7 @@ using Microsoft.Extensions.Configuration;
 using DocumentFormat.OpenXml.EMMA;
 using DocumentFormat.OpenXml.EMMA;
 using Microsoft.Extensions.Options;
 using Microsoft.Extensions.Options;
 using TEAMModelOS.Models;
 using TEAMModelOS.Models;
+using Microsoft.AspNetCore.Razor.TagHelpers;
 using HtmlAgilityPack;
 using HtmlAgilityPack;
 using Azure.Storage.Blobs;
 using Azure.Storage.Blobs;
 
 
@@ -326,6 +327,10 @@ namespace TEAMModelOS.FunctionV4
                                                 ids.Add((member.id, member.code));
                                                 ids.Add((member.id, member.code));
                                             }
                                             }
                                             //ids = members.Where(c => c.id.Equals(cla)).SelectMany(m => m.members).Select(g => g.id).ToList();
                                             //ids = members.Where(c => c.id.Equals(cla)).SelectMany(m => m.members).Select(g => g.id).ToList();
+                                            List<string> blobs = new();
+                                            if (info.qamode == 2) {
+                                                blobs =  info.papers.Where(c => c.subjectId.Equals(subject.id)).Select(c => c.blob).ToList();
+                                            }
                                             foreach (var (sId, scode) in ids)
                                             foreach (var (sId, scode) in ids)
                                             {
                                             {
                                                 result.mark.Add(marks);
                                                 result.mark.Add(marks);
@@ -336,6 +341,9 @@ namespace TEAMModelOS.FunctionV4
                                                 result.ans.Add(anses);
                                                 result.ans.Add(anses);
                                                 result.sum.Add(0);
                                                 result.sum.Add(0);
                                                 result.status.Add(1);
                                                 result.status.Add(1);
+                                                if (info.qamode == 2) {
+                                                    result.paper.Add(blobs[new Random().Next(blobs.Count)]);
+                                                }                                              
                                             }
                                             }
 
 
                                             //result.progress = info.progress;
                                             //result.progress = info.progress;
@@ -421,7 +429,7 @@ namespace TEAMModelOS.FunctionV4
                             int fno = 0;
                             int fno = 0;
                             try
                             try
                             {
                             {
-                                SetLearnRecordContent(info, data, _azureStorage, _azureCosmos);
+                                //await SetLearnRecordContent(info, data, _azureStorage, _azureCosmos);
                                 //用来判定是否完成评分
                                 //用来判定是否完成评分
                                 //bool isScore = true;
                                 //bool isScore = true;
                                 await resultStatus(client, examClassResults);
                                 await resultStatus(client, examClassResults);
@@ -532,7 +540,7 @@ namespace TEAMModelOS.FunctionV4
 
 
                                     await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ExamInfo>(info, info.id, new Azure.Cosmos.PartitionKey(info.code));
                                     await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ExamInfo>(info, info.id, new Azure.Cosmos.PartitionKey(info.code));
                                 }
                                 }
-                                //SetLearnRecordContent(info, data, _azureStorage);
+                                await SetLearnRecordContent(info, data, _azureStorage, _azureCosmos);
                             }
                             }
                             catch (Exception e)
                             catch (Exception e)
                             {
                             {
@@ -559,12 +567,7 @@ namespace TEAMModelOS.FunctionV4
             try
             try
             {
             {
                 if (info.papers.Count > 0)
                 if (info.papers.Count > 0)
-                {
-                    // debug用
-                    //if (info.id == "d1dc1417-eeb0-4b4c-b1b3-7e9f99c95087")
-                    //{
-                    //}
-                    
+                {                    
                     for (int i = 0; i < info.papers.Count; i++)
                     for (int i = 0; i < info.papers.Count; i++)
                     {// 每一個科目的試卷
                     {// 每一個科目的試卷
                         string rootName = "";
                         string rootName = "";
@@ -591,40 +594,43 @@ namespace TEAMModelOS.FunctionV4
                                 // 組合SQL
                                 // 組合SQL
                                 if (info.classes.Count > 0)
                                 if (info.classes.Count > 0)
                                 {// 按照classes取ans.json
                                 {// 按照classes取ans.json
-                                    sbsql.Append($" and c.info.id in (");
-                                    foreach (var classes in info.classes)
-                                    {// 組合所有classesid                                                                         
-                                        if (classes == info.classes[info.classes.Count - 1])
-                                        {
-                                            sbsql.Append($"'{classes}' )");
-                                        }
-                                        else
-                                        {
-                                            sbsql.Append($"'{classes}',");
-                                        }
-                                    }
+                                    sbsql.Append($" and ARRAY_CONTAINS({System.Text.Json.JsonSerializer.Serialize(info.classes)}, c.info.id)");
                                 }
                                 }
                                 else if (info.stuLists.Count > 0)
                                 else if (info.stuLists.Count > 0)
                                 {
                                 {
-                                    sbsql.Append($" and c.info.id in (");
-                                    foreach (var stuLists in info.stuLists)
-                                    {// 組合所有stuListsid                                                                         
-                                        if (stuLists == info.stuLists[info.stuLists.Count - 1])
-                                        {
-                                            sbsql.Append($"'{stuLists}' )");
-                                        }
-                                        else
-                                        {
-                                            sbsql.Append($"'{stuLists}',");
-                                        }
-                                    }
+                                    sbsql.Append($" and ARRAY_CONTAINS({System.Text.Json.JsonSerializer.Serialize(info.stuLists)}, c.info.id)");
                                 }
                                 }
-                                // 取學生答案
+                                // 取學生答案及學生名單
                                 var client = _azureCosmos.GetCosmosClient();
                                 var client = _azureCosmos.GetCosmosClient();
+                                Dictionary<string, List<string>> stuDic = new Dictionary<string, List<string>>();
+                                if (!string.IsNullOrWhiteSpace(info.school) && !stuDic.ContainsKey(info.school))
+                                {
+                                    stuDic.Add(info.school, new List<string>());
+                                }
                                 List<StudentAnswers> studentAnswersList = new List<StudentAnswers>();
                                 List<StudentAnswers> studentAnswersList = new List<StudentAnswers>();
-                                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Common).GetItemQueryIterator<StudentAnswers>(queryText: sbsql.ToString()))
+                                List<string> stuListForSql = new List<string>();
+                                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Common).GetItemQueryIterator<StudentAnswers>(queryText: sbsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{rootName}") }))
                                 {
                                 {
                                     studentAnswersList.Add(item);
                                     studentAnswersList.Add(item);
+                                    stuListForSql = stuListForSql.Union(item.studentIds).ToList();
+                                }
+                                //取得學校的學生名單
+                                List<string> stuOpenIdList = new List<string>();
+                                if(!string.IsNullOrWhiteSpace(info.school))
+                                {
+                                    StringBuilder stusql = new StringBuilder($"SELECT * FROM c WHERE c.pk = 'Base' AND ARRAY_CONTAINS({System.Text.Json.JsonSerializer.Serialize(stuListForSql)}, c.id)");
+                                    await foreach (Student item in client.GetContainer(Constant.TEAMModelOS, Constant.Student).GetItemQueryIterator<Student>(queryText: stusql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{info.school}") }))
+                                    {
+                                        stuDic[info.school].Add(item.id);
+                                        if(!string.IsNullOrWhiteSpace(item.openId) && !stuOpenIdList.Contains(item.openId))
+                                        {
+                                            stuOpenIdList.Add(item.openId);
+                                        }
+                                    }
+                                }
+                                if(stuOpenIdList.Count.Equals(0)) //無任何有OpenID的學生 => 中止生成此試卷的學生歷程
+                                {
+                                    continue;
                                 }
                                 }
                                 // 按照取出的學生答案blob 對答案 組合資料
                                 // 按照取出的學生答案blob 對答案 組合資料
                                 foreach (var studentAnswers in studentAnswersList)
                                 foreach (var studentAnswers in studentAnswersList)
@@ -643,7 +649,7 @@ namespace TEAMModelOS.FunctionV4
                                                 #region ===StartExam 開始課堂===                  
                                                 #region ===StartExam 開始課堂===                  
                                                 LearnRecordItem LRItem_StartExam = new();
                                                 LearnRecordItem LRItem_StartExam = new();
                                                 LRItem_StartExam.verb = "StartExam";
                                                 LRItem_StartExam.verb = "StartExam";
-                                                LRItem_StartExam.actor = getStuId(info.school, stuid);
+                                                LRItem_StartExam.actor = getStuId(info.school, stuid, stuDic);
                                                 LRItem_StartExam.time = info.createTime;
                                                 LRItem_StartExam.time = info.createTime;
                                                 LRItem_StartExam.ID = info.id;
                                                 LRItem_StartExam.ID = info.id;
                                                 LRItem_StartExam.Desc = info.name;
                                                 LRItem_StartExam.Desc = info.name;
@@ -681,7 +687,7 @@ namespace TEAMModelOS.FunctionV4
                                                         if (paperIndex.slides[j].type == "complete") { learnRecordItem.verb = "AnsComplete"; }
                                                         if (paperIndex.slides[j].type == "complete") { learnRecordItem.verb = "AnsComplete"; }
                                                         // 問答
                                                         // 問答
                                                         if (paperIndex.slides[j].type == "subjective") { learnRecordItem.verb = "AnsSubjective"; }
                                                         if (paperIndex.slides[j].type == "subjective") { learnRecordItem.verb = "AnsSubjective"; }
-                                                        learnRecordItem.actor = getStuId(info.school, stuid);
+                                                        learnRecordItem.actor = getStuId(info.school, stuid, stuDic);
                                                         learnRecordItem.time = data.endTime;
                                                         learnRecordItem.time = data.endTime;
                                                         string[] arrurlsingle = paperIndex.slides[j].url.Split('.');
                                                         string[] arrurlsingle = paperIndex.slides[j].url.Split('.');
                                                         learnRecordItem.ID = arrurlsingle[0];
                                                         learnRecordItem.ID = arrurlsingle[0];
@@ -718,7 +724,7 @@ namespace TEAMModelOS.FunctionV4
                                                 #region ===EndExam 結束課堂===
                                                 #region ===EndExam 結束課堂===
                                                 LearnRecordItem LRItem_EndExam = new();
                                                 LearnRecordItem LRItem_EndExam = new();
                                                 LRItem_EndExam.verb = "EndExam";
                                                 LRItem_EndExam.verb = "EndExam";
-                                                LRItem_EndExam.actor = getStuId(info.school, stuid);
+                                                LRItem_EndExam.actor = getStuId(info.school, stuid, stuDic);
                                                 LRItem_EndExam.time = info.endTime;
                                                 LRItem_EndExam.time = info.endTime;
                                                 LRItem_EndExam.ID = info.id;
                                                 LRItem_EndExam.ID = info.id;
                                                 LRItem_EndExam.Desc = info.name;
                                                 LRItem_EndExam.Desc = info.name;
@@ -788,15 +794,15 @@ namespace TEAMModelOS.FunctionV4
         /// <param name="school"></param>
         /// <param name="school"></param>
         /// <param name="stuid"></param>
         /// <param name="stuid"></param>
         /// <returns></returns>
         /// <returns></returns>
-        private static string getStuId(string school, string stuid)
+        private static string getStuId(string school, string stuid, Dictionary<string, List<string>> stuDic)
         {
         {
-            if (school == "SYSTEM_NO_SCHOOL")
-            {// 未入校老師的評量  //                                                
-                return stuid;
+            if (!string.IsNullOrWhiteSpace(school) && stuDic.ContainsKey(school) && stuDic[school].Contains(stuid))
+            {// 校內帳號用組合的 "Base-hbgl,473891247381"
+                return $"Base-{school.Trim()},{stuid}";
             }
             }
             else
             else
-            {// 如果有學校代碼  校內帳號用組合的 "Base-hbgl,473891247381"
-                return $"Base-{school.Trim()},{stuid}";
+            {// 未入校老師的評量 
+                return stuid;
             }
             }
         }
         }
         /// <summary>
         /// <summary>
@@ -1199,6 +1205,7 @@ namespace TEAMModelOS.FunctionV4
                 subject = x.Key,
                 subject = x.Key,
                 blob = x.ToList().Select(z => z.blob).ToList()
                 blob = x.ToList().Select(z => z.blob).ToList()
             });
             });
+            bool flag = info.papers.Exists(c => c.subjectId != null);
             if (addTmdidsCls.IsNotEmpty())
             if (addTmdidsCls.IsNotEmpty())
             {
             {
                 addTmdidsCls.ForEach(x =>
                 addTmdidsCls.ForEach(x =>
@@ -1265,7 +1272,7 @@ namespace TEAMModelOS.FunctionV4
                         creatorId = info.creatorId,
                         creatorId = info.creatorId,
                         subjects = sub,
                         subjects = sub,
                         blob = null,
                         blob = null,
-                        paper = info.pk.Equals("Art") ? papers.Select(c => new
+                        paper = flag ? papers.Select(c => new
                         {
                         {
                             c.subject,
                             c.subject,
                             blob = c.blob[new Random().Next(c.blob.Count)]
                             blob = c.blob[new Random().Next(c.blob.Count)]
@@ -1349,7 +1356,7 @@ namespace TEAMModelOS.FunctionV4
                         creatorId = info.creatorId,
                         creatorId = info.creatorId,
                         subjects = sub,
                         subjects = sub,
                         blob = null,
                         blob = null,
-                        paper = info.pk.Equals("Art") ? papers.Select(c => new
+                        paper = flag ? papers.Select(c => new
                         {
                         {
                             c.subject,
                             c.subject,
                             blob = c.blob[new Random().Next(c.blob.Count)]
                             blob = c.blob[new Random().Next(c.blob.Count)]
@@ -1884,18 +1891,31 @@ namespace TEAMModelOS.FunctionV4
             await examRecordCount(info, subject, _dingDing, no, result, examClassResults, _azureCosmos);
             await examRecordCount(info, subject, _dingDing, no, result, examClassResults, _azureCosmos);
             await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").UpsertItemAsync(result, new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}"));
             await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").UpsertItemAsync(result, new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}"));
             List<ErrorItems> errorItems = new();
             List<ErrorItems> errorItems = new();
+            string code = string.Empty;
+            string pk = string.Empty;
+            string table = "School";
+            if (info.scope.Equals("school"))
+            {
+                code = $"ErrorItems-{info.school}";
+                pk = $"Item-{info.school}";
+            }
+            else
+            {
+                code = "ErrorItems";
+                pk = $"Item-{info.creatorId}";
+                table = "Teacher";
+            }
             string sqlqueryText = $"select value(c) from c where c.activityId = '{info.id}'and c.subjectId = '{info.subjects[no].id}' and c.stuId in ({string.Join(",", result.studentIds.Select(x => $"'{x}'"))})";
             string sqlqueryText = $"select value(c) from c where c.activityId = '{info.id}'and c.subjectId = '{info.subjects[no].id}' and c.stuId in ({string.Join(",", result.studentIds.Select(x => $"'{x}'"))})";
-            await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Student").GetItemQueryIterator<ErrorItems>(queryText: sqlqueryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("ErrorItems") }))
+            await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Student").GetItemQueryIterator<ErrorItems>(queryText: sqlqueryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{code}") }))
             {
             {
                 errorItems.Add(item);
                 errorItems.Add(item);
             }
             }
-            try
-            {
-                /* bool isError =  examClassResults.SelectMany(c => c.status).ToList().Exists(z => z == 1);
-                 if () { 
-
-                 }*/
-                if (errorItems.Count == 0)
+            try {
+               /* bool isError =  examClassResults.SelectMany(c => c.status).ToList().Exists(z => z == 1);
+                if () { 
+                
+                }*/
+                if (errorItems.Count == 0 && info.qamode != 2)
                 {
                 {
                     // 新增逻辑 收集错题内容
                     // 新增逻辑 收集错题内容
                     BlobDownloadResult index_json;
                     BlobDownloadResult index_json;
@@ -1908,29 +1928,26 @@ namespace TEAMModelOS.FunctionV4
                         index_json = await _azureStorage.GetBlobContainerClient($"{info.creatorId}").GetBlobClient($"{info.papers[no].blob}/index.json").DownloadContentAsync();
                         index_json = await _azureStorage.GetBlobContainerClient($"{info.creatorId}").GetBlobClient($"{info.papers[no].blob}/index.json").DownloadContentAsync();
                     }
                     }
                     //BlobDownloadResult index_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{info.papers[no].blob}/index.json").DownloadContentAsync();
                     //BlobDownloadResult index_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{info.papers[no].blob}/index.json").DownloadContentAsync();
-                    JObject jo = JObject.Parse(index_json.Content.ToString());
-                    JArray array = jo.Value<JArray>("slides");
-                    List<string> urls = new();
-                    foreach (var ne in array)
+                    JsonElement RecordingJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(index_json.Content.ToString()))).RootElement;
+                    RecordingJson.TryGetProperty("slides", out JsonElement slides);
+                    var sdes = slides.ToObject<List<Slides>>();
+                    List<string> attachments = new List<string>();
+                    if (info.qamode == 1)
                     {
                     {
-                        if (!ne["type"].ToString().Equals("compose"))
+                        attachments = RecordingJson.GetProperty("attachments").ToObject<List<string>>();
+                        if (attachments.Count == 0)
                         {
                         {
-                            urls.Add(ne["url"].ToString());
+                            return;
                         }
                         }
                     }
                     }
-                    string code = string.Empty;
-                    string pk = string.Empty;
-                    string table = "School";
-                    if (info.scope.Equals("school"))
-                    {
-                        code = $"ErrorItems-{info.school}";
-                        pk = $"Item-{info.school}";
-                    }
-                    else
+                    List<string> urls = new();
+
+                    foreach (var ne in sdes)
                     {
                     {
-                        code = "ErrorItems";
-                        pk = $"Item-{info.creatorId}";
-                        table = "Teacher";
+                        if (!ne.type.Equals("compose"))
+                        {
+                            urls.Add(ne.url);
+                        }
                     }
                     }
                     // 获取整体的题目ID集合
                     // 获取整体的题目ID集合
                     List<string> ids = new();
                     List<string> ids = new();
@@ -1955,26 +1972,6 @@ namespace TEAMModelOS.FunctionV4
                         itemInfos.Add((id, pid, level, type, knowledge));
                         itemInfos.Add((id, pid, level, type, knowledge));
                     }
                     }
 
 
-
-                    /*await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, table).GetItemQueryStreamIterator(
-                                        queryText: $"select c.id,c.pid,c.level,c.type from c where c.id in ({string.Join(",", ids.Select(o => $"'{o}'"))})", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{pk}") }))
-                    {
-                        using var json = await JsonDocument.ParseAsync(item.ContentStream);
-                        if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
-                        {
-                            var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
-                            while (accounts.MoveNext())
-                            {
-                                JsonElement account = accounts.Current;
-                                string pid = "";
-                                if (account.TryGetProperty("pid",out JsonElement element)) {
-                                    pid = element.GetString();
-                                }
-                                itemInfos.Add((account.GetProperty("id").GetString(), pid, account.GetProperty("level").GetInt32(), account.GetProperty("type").GetString()));
-                            }
-                        }
-                    }*/
-
                     /* double[] point = StringHelper.ListTodouble(result.paper.point);
                     /* double[] point = StringHelper.ListTodouble(result.paper.point);
                      double[,] res = StringHelper.ListToDouble(result.studentScores);
                      double[,] res = StringHelper.ListToDouble(result.studentScores);
                      var cdm = new ClouDASMatrix(res, point);*/
                      var cdm = new ClouDASMatrix(res, point);*/
@@ -2026,6 +2023,7 @@ namespace TEAMModelOS.FunctionV4
                             items.type = itemInfos.Where(c => c.id.Equals(items.id)).FirstOrDefault().type;
                             items.type = itemInfos.Where(c => c.id.Equals(items.id)).FirstOrDefault().type;
                             items.pId = itemInfos.Where(c => c.id.Equals(items.id)).FirstOrDefault().pid;
                             items.pId = itemInfos.Where(c => c.id.Equals(items.id)).FirstOrDefault().pid;
                             items.knowledge = itemInfos.Where(c => c.id.Equals(items.id)).FirstOrDefault().knows;
                             items.knowledge = itemInfos.Where(c => c.id.Equals(items.id)).FirstOrDefault().knows;
+                            items.qamode = info.qamode;
                             error.its.Add(items);
                             error.its.Add(items);
                         }
                         }
                         errors.Add(error);
                         errors.Add(error);
@@ -2041,12 +2039,12 @@ namespace TEAMModelOS.FunctionV4
                         if (location.Equals("China")) //大陸正式站
                         if (location.Equals("China")) //大陸正式站
                         {
                         {
                             urlAction = "https://malearn.teammodel.cn";
                             urlAction = "https://malearn.teammodel.cn";
-                            accessKey = "QUzQqbqbnLsTDTeaJy4Br6wUuqPoAlKpzRK2S6PGImRHAzFuySGAeA==";
+                            accessKey = "2BcXFR_hvzG1pZjqIkaM7Dx74Hcu6m0PwwOacFpDpq44AzFuHJBRXA==";
                         }
                         }
                         else if (location.Equals("China-Dep") || location.Equals("China-Test")) //大陸測試站
                         else if (location.Equals("China-Dep") || location.Equals("China-Test")) //大陸測試站
                         {
                         {
                             urlAction = "https://malearn-rc.teammodel.cn";
                             urlAction = "https://malearn-rc.teammodel.cn";
-                            accessKey = "hESc0g7Q60FTEss4ZnVXPB61S1a8WlAXIq5ULl3T3oTxAzFunpLDwA==";
+                            accessKey = "lghWhJduNiAlo-e8isqEoROjdR7DAC-50XNtanIwHKYlAzFu1aog_A==";
                         }
                         }
                     }
                     }
                     else if (location.Contains("Global"))
                     else if (location.Contains("Global"))
@@ -2069,10 +2067,18 @@ namespace TEAMModelOS.FunctionV4
                         htc.DefaultRequestHeaders.Remove("x-functions-key");
                         htc.DefaultRequestHeaders.Remove("x-functions-key");
                     }
                     }
                     htc.DefaultRequestHeaders.Add("x-functions-key", accessKey);
                     htc.DefaultRequestHeaders.Add("x-functions-key", accessKey);
+                    ///智慧題庫school欄位修正
+                    foreach (ErrorItems error in errors)
+                    {
+                        error.school = (info.scope.Equals("school")) ? info.school : string.Empty;
+                    }
                     string paramJson = JsonConvert.SerializeObject(errors);
                     string paramJson = JsonConvert.SerializeObject(errors);
                     var content = new StringContent(paramJson, Encoding.UTF8, "application/json");
                     var content = new StringContent(paramJson, Encoding.UTF8, "application/json");
-                    await htc.PostAsync(connect, content);
-                    await task_error.TaskPage(10);
+                    var response = await htc.PostAsync(connect, content);
+                    if ((int)response.StatusCode == 200)
+                    {
+                        await task_error.TaskPage(10);
+                    }
                 }
                 }
             }
             }
             catch (Exception e)
             catch (Exception e)
@@ -2133,6 +2139,10 @@ namespace TEAMModelOS.FunctionV4
             /// 學生作答 blob 路徑
             /// 學生作答 blob 路徑
             /// </summary>
             /// </summary>
             public List<List<string>> studentAnswers { get; set; }
             public List<List<string>> studentAnswers { get; set; }
+            /// <summary>
+            /// 學生ID
+            /// </summary>
+            public List<string> studentIds { get; set; } = new();
 
 
         }
         }
         private class QuestionData
         private class QuestionData

+ 10 - 10
TEAMModelOS.FunctionV4/HttpTrigger/IESHttpTrigger.cs

@@ -722,21 +722,21 @@ namespace TEAMModelOS.FunctionV4
                     case "teacher":
                     case "teacher":
                         try
                         try
                         {
                         {
-                            Teacher teacher = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<Teacher>(id, new PartitionKey("Base"));
-                            teacher.loginInfos = new List<LoginInfo>() { new LoginInfo { expire = Expire, ip = ip, time = now } };
-                            await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
+                            //Teacher teacher = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<Teacher>(id, new PartitionKey("Base"));
+                            //teacher.loginInfos = new List<LoginInfo>() { new LoginInfo { expire = Expire, ip = ip, time = now } };
+                            //await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
                         }
                         }
                         catch { }
                         catch { }
                         break;
                         break;
                     case "student":
                     case "student":
                         try
                         try
                         {
                         {
-                            Student student = await cosmosClient.GetContainer("TEAMModelOS", Constant.Student).ReadItemAsync<Student>(id, new PartitionKey($"Base-{school}"));
-                            student.loginInfos = new List<LoginInfo>() { new LoginInfo { expire = Expire, ip = ip, time = now } };
-                            await cosmosClient.GetContainer("TEAMModelOS", Constant.Student).ReplaceItemAsync<Student>(student, student.id, new PartitionKey($"Base-{school}"));
+                           // Student student = await cosmosClient.GetContainer("TEAMModelOS", Constant.Student).ReadItemAsync<Student>(id, new PartitionKey($"Base-{school}"));
+                            //student.loginInfos = new List<LoginInfo>() { new LoginInfo { expire = Expire, ip = ip, time = now } };
+                            //await cosmosClient.GetContainer("TEAMModelOS", Constant.Student).ReplaceItemAsync<Student>(student, student.id, new PartitionKey($"Base-{school}"));
                             string key = $"Login:School:{school}:student-day:{dateDay}";
                             string key = $"Login:School:{school}:student-day:{dateDay}";
                             //记录一个学校每天每个学生登录的次数
                             //记录一个学校每天每个学生登录的次数
-                            await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync(key, student.id, 1);
+                            await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync(key, id, 1);
                             //获取key到期的时间
                             //获取key到期的时间
                             await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, hour);  //设置到期时间25小时
                             await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, hour);  //设置到期时间25小时
                         }
                         }
@@ -745,9 +745,9 @@ namespace TEAMModelOS.FunctionV4
                     case "tmduser":
                     case "tmduser":
                         try
                         try
                         {
                         {
-                            TmdUser tmdUser = await cosmosClient.GetContainer("TEAMModelOS", Constant.Student).ReadItemAsync<TmdUser>(id, new PartitionKey("Base"));
-                            tmdUser.loginInfos = new List<LoginInfo>() { new LoginInfo { expire = Expire, ip = ip, time = now } };
-                            await cosmosClient.GetContainer("TEAMModelOS", Constant.Student).ReplaceItemAsync<TmdUser>(tmdUser, tmdUser.id, new PartitionKey("Base"));
+                            //TmdUser tmdUser = await cosmosClient.GetContainer("TEAMModelOS", Constant.Student).ReadItemAsync<TmdUser>(id, new PartitionKey("Base"));
+                            //tmdUser.loginInfos = new List<LoginInfo>() { new LoginInfo { expire = Expire, ip = ip, time = now } };
+                            //await cosmosClient.GetContainer("TEAMModelOS", Constant.Student).ReplaceItemAsync<TmdUser>(tmdUser, tmdUser.id, new PartitionKey("Base"));
                         }
                         }
                         catch { }
                         catch { }
                         break;
                         break;

+ 1 - 0
TEAMModelOS.FunctionV4/Program.cs

@@ -64,6 +64,7 @@ namespace TEAMModelOS.FunctionV4
                List<(string name, string connectionString)> cosmosDBConnects = new();
                List<(string name, string connectionString)> cosmosDBConnects = new();
                cosmosDBConnects.Add(("Default", context.Configuration.GetSection("Azure:Cosmos:ConnectionString").Get<string>()));
                cosmosDBConnects.Add(("Default", context.Configuration.GetSection("Azure:Cosmos:ConnectionString").Get<string>()));
                cosmosDBConnects.Add(("CoreServiceV1", context.Configuration.GetSection("CoreServiceV1:Cosmos:ConnectionString").Get<string>())); //CoreService V1 read only
                cosmosDBConnects.Add(("CoreServiceV1", context.Configuration.GetSection("CoreServiceV1:Cosmos:ConnectionString").Get<string>())); //CoreService V1 read only
+               cosmosDBConnects.Add(("CoreServiceV2", context.Configuration.GetSection("CoreServiceV2:Cosmos:ConnectionString").Get<string>())); //CoreService V2
                cosmosDBConnects.Add(("CoreServiceV2CnRead", context.Configuration.GetSection("CoreServiceV2:CosmosCnRead:ConnectionString").Get<string>())); //CoreService V2 CN read only
                cosmosDBConnects.Add(("CoreServiceV2CnRead", context.Configuration.GetSection("CoreServiceV2:CosmosCnRead:ConnectionString").Get<string>())); //CoreService V2 CN read only
                services.AddMultipleAzureCosmos(cosmosDBConnects);
                services.AddMultipleAzureCosmos(cosmosDBConnects);
                //services.AddAzureCosmos(context.Configuration.GetSection("Azure:Cosmos:ConnectionString").Get<string>());
                //services.AddAzureCosmos(context.Configuration.GetSection("Azure:Cosmos:ConnectionString").Get<string>());

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

@@ -21,7 +21,7 @@
     },
     },
     "resourceName": {
     "resourceName": {
       "type": "string",
       "type": "string",
-      "defaultValue": "teammodelos-func-v4",
+      "defaultValue": "test",
       "metadata": {
       "metadata": {
         "description": "Name of the main resource to be created by this template."
         "description": "Name of the main resource to be created by this template."
       }
       }
@@ -128,7 +128,6 @@
                     "[variables('function_ResourceId')]"
                     "[variables('function_ResourceId')]"
                   ],
                   ],
                   "properties": {
                   "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')]",
                     "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_EXTENSION_VERSION": "~3",
                     "FUNCTIONS_WORKER_RUNTIME": "dotnet"
                     "FUNCTIONS_WORKER_RUNTIME": "dotnet"

+ 5 - 5
TEAMModelOS.FunctionV4/ServiceBus/ActiveTaskTopic.cs

@@ -517,7 +517,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                 if (groupChange.type == null || !groupChange.type.Equals("research") || !groupChange.type.Equals("yxtrain") || !groupChange.type.Equals("activity"))
                 if (groupChange.type == null || !groupChange.type.Equals("research") || !groupChange.type.Equals("yxtrain") || !groupChange.type.Equals("activity"))
                 {
                 {
                     //课程名单变动修改学生课程关联信息
                     //课程名单变动修改学生课程关联信息
-                    await IESActivityService.FixStuCourse(client, _dingDing, groupChange);
+                   // await IESActivityService.FixStuCourse(client, _dingDing, groupChange);
                     //名单变动修改课例关联信息
                     //名单变动修改课例关联信息
                     //await ActivityService.FixLessonRecord(client, _dingDing, groupChange);
                     //await ActivityService.FixLessonRecord(client, _dingDing, groupChange);
                 }
                 }
@@ -1150,7 +1150,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
         /// </summary>
         /// </summary>
         /// <param name="msg"></param>
         /// <param name="msg"></param>
         /// <returns></returns>
         /// <returns></returns>
-        [Function("CopyStandardFile")]
+        ///[Function("CopyStandardFile")]  弃用
         public async Task BatchCopyBlobFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "copy-standard-file", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
         public async Task BatchCopyBlobFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "copy-standard-file", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
         {
         {
             try
             try
@@ -2146,7 +2146,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
             }
             }
 
 
         }
         }
-
+        /*
         /// <summary>
         /// <summary>
         /// 完善课程变更
         /// 完善课程变更
         /// </summary>
         /// </summary>
@@ -2155,7 +2155,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
         ///// </data>
         ///// </data>
         /// <param name="msg"></param>
         /// <param name="msg"></param>
         /// <returns></returns>
         /// <returns></returns>
-        [Function("Course")]
+        ///[Function("Course")]   弃用 
         public async Task CourseFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "course", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
         public async Task CourseFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "course", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
         {
         {
             var client = _azureCosmos.GetCosmosClient();
             var client = _azureCosmos.GetCosmosClient();
@@ -2457,7 +2457,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
             {
             {
                 await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -Course\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
                 await _dingDing.SendBotMsg($"OS,{Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -Course\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
             }
             }
-        }
+        }*/
 
 
         [Function("Imei")]
         [Function("Imei")]
         public async Task ImeiFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "imei", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
         public async Task ImeiFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "imei", Connection = "Azure:ServiceBus:ConnectionString")] string msg)

+ 4 - 4
TEAMModelOS.FunctionV4/TEAMModelOS.FunctionV4.csproj

@@ -5,9 +5,9 @@
 		<OutputType>Exe</OutputType>
 		<OutputType>Exe</OutputType>
 		<_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput>
 		<_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput>
 		<SignAssembly>true</SignAssembly>
 		<SignAssembly>true</SignAssembly>
-		<Version>5.2311.15</Version>
-		<AssemblyVersion>5.2311.15.1</AssemblyVersion>
-		<FileVersion>5.2311.15.1</FileVersion>
+		<Version>5.2312.6</Version>
+		<AssemblyVersion>5.2312.6.1</AssemblyVersion>
+		<FileVersion>5.2312.6.1</FileVersion>
 		<PackageId>TEAMModelOS.FunctionV4</PackageId>
 		<PackageId>TEAMModelOS.FunctionV4</PackageId>
 		<Authors>teammodel</Authors>
 		<Authors>teammodel</Authors>
 		<Company>醍摩豆(成都)信息技术有限公司</Company>
 		<Company>醍摩豆(成都)信息技术有限公司</Company>
@@ -51,7 +51,7 @@
 		<PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.15.0" />
 		<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.Extensions.Timer" Version="4.1.0" />
 		<PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.7.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.Http" Version="3.0.13" />
 		<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Storage" Version="5.0.1" />
 		<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Storage" Version="5.0.1" />
 		<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.ServiceBus" Version="5.7.0" />
 		<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.ServiceBus" Version="5.7.0" />

+ 2 - 1
TEAMModelOS.FunctionV4/TimeTrigger/IESTimerTrigger.cs

@@ -426,13 +426,14 @@ namespace TEAMModelOS.FunctionV4.TimeTrigger
         public async Task BICreatDailyAnalData([TimerTrigger("0 1 1 * * *")] TimerInfo myTimer, ILogger log)
         public async Task BICreatDailyAnalData([TimerTrigger("0 1 1 * * *")] TimerInfo myTimer, ILogger log)
         {
         {
             var _azureCosmosClient = _azureCosmos.GetCosmosClient();
             var _azureCosmosClient = _azureCosmos.GetCosmosClient();
+            var _azureCosmosClientCsv2 = _azureCosmos.GetCosmosClient(name: "CoreServiceV2");
             var _azureCosmosClientCsv2CnRead = _azureCosmos.GetCosmosClient(name: "CoreServiceV2CnRead");
             var _azureCosmosClientCsv2CnRead = _azureCosmos.GetCosmosClient(name: "CoreServiceV2CnRead");
             var datetime = DateTimeOffset.UtcNow.AddHours(-12); //統計昨天的數據
             var datetime = DateTimeOffset.UtcNow.AddHours(-12); //統計昨天的數據
             var y = $"{datetime.Year}";
             var y = $"{datetime.Year}";
             var m = datetime.Month >= 10 ? $"{datetime.Month}" : $"0{datetime.Month}";
             var m = datetime.Month >= 10 ? $"{datetime.Month}" : $"0{datetime.Month}";
             var d = datetime.Day >= 10 ? $"{datetime.Day}" : $"0{datetime.Day}";
             var d = datetime.Day >= 10 ? $"{datetime.Day}" : $"0{datetime.Day}";
             //生成學校IOT數據
             //生成學校IOT數據
-            await BIProdAnalysis.BICreatDailyAnalData(_azureRedis, _azureCosmosClient, _azureCosmosClientCsv2CnRead, _dingDing, y, m, d);
+            await BIProdAnalysis.BICreatDailyAnalData(_azureRedis, _azureCosmosClient, _azureCosmosClientCsv2, _azureCosmosClientCsv2CnRead, _dingDing, y, m, d);
             //刪除三個月以前的Redis數據 [待做]
             //刪除三個月以前的Redis數據 [待做]
         }
         }
 
 

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

@@ -5,7 +5,7 @@
     "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
     "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
     "Azure:Storage:ConnectionString": "DefaultEndpointsProtocol=https;AccountName=teammodeltest;AccountKey=O2W2vadCqexDxWO+px+QK7y1sHwsYj8f/WwKLdOdG5RwHgW/Dupz9dDUb4c1gi6ojzQaRpFUeAAmOu4N9E+37A==;EndpointSuffix=core.chinacloudapi.cn",
     "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: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: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:Redis:ConnectionString": "52.130.252.100:6379,password=habook,ssl=false,abortConnect=False,writeBuffer=10240",
     "Azure:ServiceBus:ActiveTask": "dep-active-task",
     "Azure:ServiceBus:ActiveTask": "dep-active-task",
@@ -17,6 +17,7 @@
     "HaBookAuth:CoreService:clientID": "c7317f88-7cea-4e48-ac57-a16071f7b884",
     "HaBookAuth:CoreService:clientID": "c7317f88-7cea-4e48-ac57-a16071f7b884",
     "HaBookAuth:CoreService:clientSecret": "kguxh:V.PLmxBdaI@jnrTrDSth]A3346",
     "HaBookAuth:CoreService:clientSecret": "kguxh:V.PLmxBdaI@jnrTrDSth]A3346",
     "CoreServiceV1:Cosmos:ConnectionString": "AccountEndpoint=https://corecosmosdbcn.documents.azure.cn:443/;AccountKey=WIFUWgnC6HiPb4yYba5iLR4ZghcA2fqrEvnX00YTA5B4sd7o89sxtbvgFDDUqT2VRkeWrWVTWZ8VbApQtwkJKQ==;", //CSV1大陸正式站(唯讀)
     "CoreServiceV1:Cosmos:ConnectionString": "AccountEndpoint=https://corecosmosdbcn.documents.azure.cn:443/;AccountKey=WIFUWgnC6HiPb4yYba5iLR4ZghcA2fqrEvnX00YTA5B4sd7o89sxtbvgFDDUqT2VRkeWrWVTWZ8VbApQtwkJKQ==;", //CSV1大陸正式站(唯讀)
+	"CoreServiceV2:Cosmos:ConnectionString": "AccountEndpoint=https://teammodelostest.documents.azure.cn:443/;AccountKey=S5aG4XbGulK3T1LKzNAraeSuNMvXWf5y6j7ptQHlzVL2jHB07FRNUnmKCChkQ5IeLrJzGfSKIXGnAk3gW30UtQ==;", //CSV2大陸測試站(唯讀)
     "CoreServiceV2:CosmosCnRead:ConnectionString": "AccountEndpoint=https://corecosmosdb.documents.azure.cn:443/;AccountKey=12C5n8IvXFqsPARUb2YBOUWiU9PksohESlLHgH6cAVajxWBBJIJ6chJusgfrYhxCKgQgSHHxVgHsFPRakhvlPw==;", //CSV2大陸正式站(唯讀)
     "CoreServiceV2:CosmosCnRead:ConnectionString": "AccountEndpoint=https://corecosmosdb.documents.azure.cn:443/;AccountKey=12C5n8IvXFqsPARUb2YBOUWiU9PksohESlLHgH6cAVajxWBBJIJ6chJusgfrYhxCKgQgSHHxVgHsFPRakhvlPw==;", //CSV2大陸正式站(唯讀)
     "Option:LocationNum": 1
     "Option:LocationNum": 1
   }
   }

+ 14 - 1
TEAMModelOS.SDK/DI/AzureRedis/AzureRedisFactory.cs

@@ -43,12 +43,25 @@ namespace TEAMModelOS.SDK.DI
                 return null;
                 return null;
             }
             }
         }
         }
+        public ConnectionMultiplexer GetConnectionMultiplexer( string name = "Default")
+        {
+            try
+            {
+                var cm = ConnectionMultiplexers.GetOrAdd(name, x => ConnectionMultiplexer.Connect(_optionsMonitor.Get(name).RedisConnectionString));
+                return cm;
+            }
+            catch (OptionsValidationException e)
+            {
+                _logger?.LogWarning(e, e.Message);
+                return null;
+            }
+        }
         //public (IDatabase db , IServer server ) GetRedisDbCmClient(int dbnum = -1, string name = "Default")
         //public (IDatabase db , IServer server ) GetRedisDbCmClient(int dbnum = -1, string name = "Default")
         //{
         //{
         //    try
         //    try
         //    {
         //    {
         //        var cm = ConnectionMultiplexers.GetOrAdd(name, x => ConnectionMultiplexer.Connect(_optionsMonitor.Get(name).RedisConnectionString));
         //        var cm = ConnectionMultiplexers.GetOrAdd(name, x => ConnectionMultiplexer.Connect(_optionsMonitor.Get(name).RedisConnectionString));
-                
+
         //        return (cm.GetDatabase(dbnum),cm.GetServer(cm.GetEndPoints()[0]));
         //        return (cm.GetDatabase(dbnum),cm.GetServer(cm.GetEndPoints()[0]));
         //    }
         //    }
         //    catch (OptionsValidationException e)
         //    catch (OptionsValidationException e)

+ 275 - 41
TEAMModelOS.SDK/Models/Cosmos/Common/Activity.cs

@@ -29,7 +29,10 @@ namespace TEAMModelOS.SDK.Models
         public List<Attachment> attachment { get; set; } = new List<Attachment>();
         public List<Attachment> attachment { get; set; } = new List<Attachment>();
         public List<string> zb { get; set; } = new List<string>();
         public List<string> zb { get; set; } = new List<string>();
         public List<string> cb { get; set; } = new List<string>();
         public List<string> cb { get; set; } = new List<string>();
-        public string mzsm { get; set; } 
+        /// <summary>
+        /// 免责声明
+        /// </summary>
+        public string mzsm { get; set; }
         /// <summary>
         /// <summary>
         /// "hbcn/区级id,areaId",
         /// "hbcn/区级id,areaId",
         /// </summary>
         /// </summary>
@@ -68,7 +71,7 @@ namespace TEAMModelOS.SDK.Models
         [Required(ErrorMessage = "模块不能为空")]
         [Required(ErrorMessage = "模块不能为空")]
         [MinLength(1, ErrorMessage = "模块不能为空")]
         [MinLength(1, ErrorMessage = "模块不能为空")]
         public List<string> modules { get; set; } = new List<string>();
         public List<string> modules { get; set; } = new List<string>();
-      
+
         /// <summary>
         /// <summary>
         /// 所属年份
         /// 所属年份
         /// </summary>
         /// </summary>
@@ -76,7 +79,7 @@ namespace TEAMModelOS.SDK.Models
         /// <summary>
         /// <summary>
         /// 创建时间
         /// 创建时间
         /// </summary>
         /// </summary>
-        public long createTime {  get; set; }
+        public long createTime { get; set; }
         /// <summary>
         /// <summary>
         /// 创建者
         /// 创建者
         /// </summary>
         /// </summary>
@@ -85,10 +88,13 @@ namespace TEAMModelOS.SDK.Models
         /// 0未发布,1已发布,2.已结束
         /// 0未发布,1已发布,2.已结束
         /// </summary>
         /// </summary>
         public int publish { get; set; }
         public int publish { get; set; }
+
+    }
+    public class ActivityDto : Activity
+    {
         public string sas { get; set; }
         public string sas { get; set; }
     }
     }
 
 
-
     public class ActivityWebsite : CosmosEntity {
     public class ActivityWebsite : CosmosEntity {
         // id(区级id,校级id)
         // id(区级id,校级id)
         //code:ActivityWebsite
         //code:ActivityWebsite
@@ -115,17 +121,36 @@ namespace TEAMModelOS.SDK.Models
         /// </summary>
         /// </summary>
         public int allowPublic { get; set; } = 0;
         public int allowPublic { get; set; } = 0;
 
 
+
+
     }
     }
-    public class ActivityBanner { 
+    public class ActivityWebsiteDto : ActivityWebsite
+    {
+        public string sas { get; set; }
+        public ActivityWebsiteDto() { }
+        public ActivityWebsiteDto(ActivityWebsite website) {
+            this.allowPublic = website.allowPublic;
+            this.route = website.route;
+            this.scope = website.scope;
+            this.name = website.name;
+            this.logo = website.logo;
+            this.pk = website.pk;
+            this.code = website.code;
+            this.banners = website.banners;
+            this.id = website.id;
+        }
+    }
+
+    public class ActivityBanner {
         public string title { get; set; }
         public string title { get; set; }
         public string subtitle { get; set; }
         public string subtitle { get; set; }
         /// <summary>
         /// <summary>
         /// 指向链接
         /// 指向链接
         /// </summary>
         /// </summary>
         public string url { get; set; }
         public string url { get; set; }
-       /// <summary>
-       /// 图片链接
-       /// </summary>
+        /// <summary>
+        /// 图片链接
+        /// </summary>
         public string blob { get; set; }
         public string blob { get; set; }
         /// <summary>
         /// <summary>
         /// 文件类型  video  image
         /// 文件类型  video  image
@@ -139,6 +164,10 @@ namespace TEAMModelOS.SDK.Models
         /// 展示到期时间,-1永不过期
         /// 展示到期时间,-1永不过期
         /// </summary>
         /// </summary>
         public long expire { get; set; }
         public long expire { get; set; }
+        /// <summary>
+        /// 来源 activity ,upload, link 
+        /// </summary>
+        public string source { get; set; }
     }
     }
 
 
     public class InviteTeachers {
     public class InviteTeachers {
@@ -148,7 +177,7 @@ namespace TEAMModelOS.SDK.Models
         public string school { get; set; }
         public string school { get; set; }
         public string schoolName { get; set; }
         public string schoolName { get; set; }
         /// <summary>
         /// <summary>
-        /// 0 未确认,1已确认,用于区级发布, publish=1,joinMode=invite,学校可以去进行邀请某一些教师。
+        /// 0 未报名,1已报名,用于区级发布, publish=1,joinMode=invite,学校可以去进行邀请某一些教师。
         /// </summary>
         /// </summary>
         public int status { get; set; }
         public int status { get; set; }
     }
     }
@@ -158,14 +187,20 @@ namespace TEAMModelOS.SDK.Models
     public class ActivityTeacher : CosmosEntity
     public class ActivityTeacher : CosmosEntity
     {
     {
         /// <summary>
         /// <summary>
-        /// id  如果活动是邀请制,则id是活动的id 。
-        /// code = ActivityTeacher 
+        /// id  学校id
+        /// code = ActivityTeacher-{activityId}
         /// </summary>
         /// </summary>
         public ActivityTeacher()
         public ActivityTeacher()
         {
         {
             pk="ActivityTeacher";
             pk="ActivityTeacher";
         }
         }
-       public List<InviteTeachers> inviteTeachers { get; set; } = new List<InviteTeachers>();
+
+        /// <summary>
+        /// 活动id
+        /// </summary>
+        public string activityId { get; set; }
+        public string schoolNmae { get; set; }
+        public List<InviteTeachers> inviteTeachers { get; set; } = new List<InviteTeachers>();
     }
     }
 
 
     public class ActivityInvitedSchool
     public class ActivityInvitedSchool
@@ -174,9 +209,9 @@ namespace TEAMModelOS.SDK.Models
         public string name { get; set; }
         public string name { get; set; }
         public string picture { get; set; }
         public string picture { get; set; }
     }
     }
-    public class ActivityConfirmedSchool: ActivityInvitedSchool
+    public class ActivityConfirmedSchool : ActivityInvitedSchool
     {
     {
-       
+
         /// <summary>
         /// <summary>
         /// 0 未确认,1已确认,用于区级发布, publish=1,joinMode=invite,学校可以去进行邀请某一些教师。
         /// 0 未确认,1已确认,用于区级发布, publish=1,joinMode=invite,学校可以去进行邀请某一些教师。
         /// </summary>
         /// </summary>
@@ -227,17 +262,20 @@ namespace TEAMModelOS.SDK.Models
         public string ruleId { get; set; }
         public string ruleId { get; set; }
         public string ruleName { get; set; }
         public string ruleName { get; set; }
     }
     }
-    public class ReviewRule :CosmosEntity{
+    /// <summary>
+    /// 存在Normal表
+    /// </summary>
+    public class ReviewRule : CosmosEntity {
         public ReviewRule() {
         public ReviewRule() {
             pk="ReviewRule";
             pk="ReviewRule";
-           
+
         }
         }
         /// <summary>
         /// <summary>
         ///  code="ReviewRule-disposable"; 存为活动   code="ReviewRule-template"; 存为模板
         ///  code="ReviewRule-disposable"; 存为活动   code="ReviewRule-template"; 存为模板
         /// </summary>
         /// </summary>
         //id 为活动的id ,以此用于来推断 模板评审规则或者活动评审规则的来源
         //id 为活动的id ,以此用于来推断 模板评审规则或者活动评审规则的来源
         [Required(ErrorMessage = "Required")]
         [Required(ErrorMessage = "Required")]
-        public string name  { get; set; }
+        public string name { get; set; }
         /// <summary>
         /// <summary>
         /// "hbcn/区级id,areaId",
         /// "hbcn/区级id,areaId",
         /// </summary>
         /// </summary>
@@ -253,7 +291,7 @@ namespace TEAMModelOS.SDK.Models
         /// </summary>
         /// </summary>
         [Required(ErrorMessage = "Required")]
         [Required(ErrorMessage = "Required")]
         public string type { get; set; }
         public string type { get; set; }
-        public List<RuleConfig> configs { get; set; } = new List<RuleConfig>(); 
+        public List<RuleConfig> configs { get; set; } = new List<RuleConfig>();
         /// <summary>
         /// <summary>
         /// 模板来源 name 
         /// 模板来源 name 
         /// </summary>
         /// </summary>
@@ -263,9 +301,9 @@ namespace TEAMModelOS.SDK.Models
     public class RuleConfig {
     public class RuleConfig {
         public string id { get; set; }
         public string id { get; set; }
         public string pid { get; set; }
         public string pid { get; set; }
-        public string label {  get; set; }
+        public string label { get; set; }
         public string desc { get; set; }
         public string desc { get; set; }
-        public double score {  get; set; }
+        public double score { get; set; }
         public int order { get; set; }
         public int order { get; set; }
         public List<string> cids { get; set; } = new List<string>();
         public List<string> cids { get; set; } = new List<string>();
     }
     }
@@ -286,12 +324,12 @@ namespace TEAMModelOS.SDK.Models
         /// </summary>
         /// </summary>
         public int upsertAsTemplate { get; set; } = 0;
         public int upsertAsTemplate { get; set; } = 0;
         public string sourceName { get; set; }
         public string sourceName { get; set; }
-        public List<RuleConfigTree> trees{ get; set; }
+        public List<RuleConfigTree> trees { get; set; }
 
 
     }
     }
-    public class RuleConfigTree: RuleConfig
+    public class RuleConfigTree : RuleConfig
     {
     {
-        
+
         public List<RuleConfigTree> children { get; set; } = new List<RuleConfigTree>();
         public List<RuleConfigTree> children { get; set; } = new List<RuleConfigTree>();
     }
     }
     public class ContestUpload
     public class ContestUpload
@@ -310,11 +348,11 @@ namespace TEAMModelOS.SDK.Models
         /// 是否由队长上传 0个人上传,1 队长上传
         /// 是否由队长上传 0个人上传,1 队长上传
         /// </summary>
         /// </summary>
         public int captainUpload { get; set; }
         public int captainUpload { get; set; }
-        public string desc { get; set;}
+        public string desc { get; set; }
     }
     }
     public class ContestSign
     public class ContestSign
     {
     {
-       
+
         public List<string> field { get; set; } = new List<string>();
         public List<string> field { get; set; } = new List<string>();
         /// <summary>
         /// <summary>
         /// 报名类型,0个人,1团队
         /// 报名类型,0个人,1团队
@@ -327,7 +365,7 @@ namespace TEAMModelOS.SDK.Models
         /// </summary>
         /// </summary>
         public int limit { get; set; }
         public int limit { get; set; }
 
 
-        public List<ContestSignField> fields { get; set; }= new List<ContestSignField>();
+        public List<ContestSignField> fields { get; set; } = new List<ContestSignField>();
     }
     }
     public class ContestSignField {
     public class ContestSignField {
         /// <summary>
         /// <summary>
@@ -343,7 +381,7 @@ namespace TEAMModelOS.SDK.Models
         /// <summary>
         /// <summary>
         /// 单选,复选,下拉列表
         /// 单选,复选,下拉列表
         /// </summary>
         /// </summary>
-        public List<string> item { get; set; }= new List<string> ();
+        public List<string> item { get; set; } = new List<string>();
     }
     }
     /// <summary>
     /// <summary>
     /// 在线培训模块的数据结构
     /// 在线培训模块的数据结构
@@ -364,7 +402,7 @@ namespace TEAMModelOS.SDK.Models
         /// "online", "submit", "exam"模块
         /// "online", "submit", "exam"模块
         /// </summary>
         /// </summary>
         public List<string> modules { get; set; } = new List<string>();
         public List<string> modules { get; set; } = new List<string>();
-        public List<TrainingAbility> abilities { get; set; }= new List<TrainingAbility>();
+        public List<TrainingAbility> abilities { get; set; } = new List<TrainingAbility>();
         public TrainingOnline online { get; set; }
         public TrainingOnline online { get; set; }
         public TrainingSubmit submit { get; set; }
         public TrainingSubmit submit { get; set; }
         public TrainingExam exam { get; set; }
         public TrainingExam exam { get; set; }
@@ -372,7 +410,7 @@ namespace TEAMModelOS.SDK.Models
         public long etime { get; set; }
         public long etime { get; set; }
     }
     }
 
 
-    public class TrainingOnline 
+    public class TrainingOnline
     {
     {
         /// <summary>
         /// <summary>
         /// //最少学习多少积分 
         /// //最少学习多少积分 
@@ -399,7 +437,7 @@ namespace TEAMModelOS.SDK.Models
         /// <summary>
         /// <summary>
         /// //学习完成获得积分,0-10
         /// //学习完成获得积分,0-10
         /// </summary>
         /// </summary>
-        public int balance { get; set; } 
+        public int balance { get; set; }
         public string id { get; set; }
         public string id { get; set; }
         /// <summary>
         /// <summary>
         ///新建字段 维度 对应 原来的 subjectId 学科
         ///新建字段 维度 对应 原来的 subjectId 学科
@@ -409,14 +447,14 @@ namespace TEAMModelOS.SDK.Models
         /// 标号 A1  A2 A3....
         /// 标号 A1  A2 A3....
         /// </summary>
         /// </summary>
         public string no { get; set; }
         public string no { get; set; }
-       
+
         /// <summary>
         /// <summary>
         /// 册别name
         /// 册别name
         /// </summary>
         /// </summary>
         [Required(ErrorMessage = "{0} 必须填写")]
         [Required(ErrorMessage = "{0} 必须填写")]
         public string name { get; set; }
         public string name { get; set; }
         public List<AbilityTask> abilityTasks { get; set; } = new List<AbilityTask>();
         public List<AbilityTask> abilityTasks { get; set; } = new List<AbilityTask>();
-       
+
         public string desc { get; set; }
         public string desc { get; set; }
         public string sug { get; set; }
         public string sug { get; set; }
         public List<AbilityStds> stds { get; set; } = new List<AbilityStds>();
         public List<AbilityStds> stds { get; set; } = new List<AbilityStds>();
@@ -447,7 +485,7 @@ namespace TEAMModelOS.SDK.Models
         public ResearchSign sign { get; set; }
         public ResearchSign sign { get; set; }
         public ResearchExamLite examLite { get; set; }
         public ResearchExamLite examLite { get; set; }
         public ResearchHomework homework { get; set; }
         public ResearchHomework homework { get; set; }
-        public ResearchSurvey survey { get; set; }  
+        public ResearchSurvey survey { get; set; }
         public ResearchVote vote { get; set; }
         public ResearchVote vote { get; set; }
     }
     }
     public class ResearchSign
     public class ResearchSign
@@ -491,7 +529,7 @@ namespace TEAMModelOS.SDK.Models
     /// <summary>
     /// <summary>
     /// 本次活动的评审专家
     /// 本次活动的评审专家
     /// </summary>
     /// </summary>
-    
+
     public class ActivityExpert : CosmosEntity
     public class ActivityExpert : CosmosEntity
     {
     {
         /// <summary>
         /// <summary>
@@ -503,7 +541,9 @@ namespace TEAMModelOS.SDK.Models
         }
         }
         public List<Expert> experts { get; set; } = new List<Expert>();
         public List<Expert> experts { get; set; } = new List<Expert>();
     }
     }
-    public class Expert { 
+
+
+    public class Expert {
         public string id { get; set; }
         public string id { get; set; }
         public string iname { get; set; }
         public string iname { get; set; }
         public string name { get; set; }
         public string name { get; set; }
@@ -525,10 +565,12 @@ namespace TEAMModelOS.SDK.Models
         /// </summary>
         /// </summary>
         public List<ExpertSubject> subjects { get; set; } = new List<ExpertSubject>();
         public List<ExpertSubject> subjects { get; set; } = new List<ExpertSubject>();
         /// <summary>
         /// <summary>
-        /// 评审专家可以对哪些模块进行评审
+        /// 评审专家可以对哪些模块进行评审,["Contest"]
         /// </summary>
         /// </summary>
         public List<string> modules { get; set; } = new List<string>();
         public List<string> modules { get; set; } = new List<string>();
     }
     }
+
+
     public class ExpertSubject {
     public class ExpertSubject {
         /// <summary>
         /// <summary>
         /// 科目
         /// 科目
@@ -539,14 +581,44 @@ namespace TEAMModelOS.SDK.Models
         /// </summary>
         /// </summary>
         public string period { get; set; }
         public string period { get; set; }
     }
     }
+    public class TeacherActivityDto : ActivityDto
+    {
+        /// <summary>
+        /// 0未报名,1已报名
+        /// </summary>
+        public int contestSign { get; set; } = 0;
+        /// <summary>
+        /// 参赛模式 0 个人,1 团队(是否允许跨校)
+        /// </summary>
+        public int contestType { get; set; }
+        /// <summary>
+        /// 报名时间
+        /// </summary>
+        public long signTime { get; set; } = -1;
+        /// <summary>
+        /// 0未提交,1 已提交
+        /// </summary>
+        public int contestUpload { get; set; }
+        public string uploadType { get; set; }
+        public long uploadTime { get; set; } = -1;
+    }
 
 
-    public class ActivityEnroll  :CosmosEntity {
+    /// <summary>
+    /// 教师报名数据,存放在Teacher
+    /// </summary>
+    public class ActivityEnroll : CosmosEntity {
         //id  教师id,
         //id  教师id,
         //code ActivityEnroll-ActivityId
         //code ActivityEnroll-ActivityId
         //pk ActivityEnroll
         //pk ActivityEnroll
-        //Contest/赛课活动",  "Training/线上培训", "Research/教研活动
-        public string school { get; set; }
+        public string schoolId { get; set; }
+        public string schoolName { get; set; }
+        public string tmdName { get; set; }
+        public string tmdPicture { get; set; }
+        public string schoolPicture { get; set; }
         public EnrollContest contest { get; set; }
         public EnrollContest contest { get; set; }
+        public EnrollUpload upload { get; set; }
+
+        public string activityId { get; set; }
     }
     }
 
 
     public class EnrollContest
     public class EnrollContest
@@ -554,11 +626,11 @@ namespace TEAMModelOS.SDK.Models
         /// <summary>
         /// <summary>
         /// 报名时间
         /// 报名时间
         /// </summary>
         /// </summary>
-        public string enrollTime { get; set; }
+        public long enrollTime { get; set; }
         /// <summary>
         /// <summary>
         /// 参赛模式 0 个人,1 团队(是否允许跨校)
         /// 参赛模式 0 个人,1 团队(是否允许跨校)
         /// </summary>
         /// </summary>
-        public string type { get; set; }
+        public int type { get; set; }
         /// <summary>
         /// <summary>
         /// 组队口令
         /// 组队口令
         /// </summary>
         /// </summary>
@@ -573,8 +645,170 @@ namespace TEAMModelOS.SDK.Models
         /// 表单填报信息
         /// 表单填报信息
         /// </summary>
         /// </summary>
         public List<EnrollInfo> enrollInfos { get; set; } = new List<EnrollInfo>();
         public List<EnrollInfo> enrollInfos { get; set; } = new List<EnrollInfo>();
+
+
+    }
+
+    public class TeacherEnrollContestDto
+    {
+        //[Required(ErrorMessage = "Required")]
+        //public string activityId { get; set; }
+        [Required(ErrorMessage = "Required")]
+        public string tmdid { get; set; }
+        public string tmdName { get; set; }
+        [Required(ErrorMessage = "Required")]
+        public string schoolId { get; set; }
+        public string schoolName { get; set; }
+        public string tmdPicture { get; set; }
+        public string schoolPicture { get; set; }
+        public long enrollTime { get; set; }
+        /// <summary>
+        ///  参赛模式 0 个人,1 团队(是否允许跨校)
+        /// </summary>
+        [Required(ErrorMessage = "Required")]
+        public int type { get; set; }
+        public string cipher { get; set; }
+        public int leader { get; set; }
+        public string teamName { get; set; }
+        /// <summary>
+        /// 表单填报信息
+        /// </summary>
+        public List<EnrollInfo> enrollInfos { get; set; } = new List<EnrollInfo>();
+    }
+    public class TeacherUploadContestDto {
+        public List<ContestAttachment> files { get; set; } = new List<ContestAttachment>();
+        public List<ContestSokrates> sokrates { get; set; } = new List<ContestSokrates>();
+        /// <summary>
+        /// file  sokrates
+        /// </summary>
+        public string type { get; set; }
+        public string schoolId { get; set; }
+        public string schoolName { get; set; }
+        public string schoolPicture { get; set; }
     }
     }
 
 
+    public class EnrollUpload
+    {
+        public long uploadTime { get; set; }
+        public List<ContestAttachment> files { get; set; } = new List<ContestAttachment>();
+        public List<ContestSokrates> sokrates { get; set; } = new List<ContestSokrates>();
+        /// <summary>
+        /// file  sokrates
+        /// </summary>
+        public string type { get; set; }
+        /// <summary>
+        ///作品id
+        /// </summary>
+        public string uploadId { get; set; }
+        /// <summary>
+        /// 真实分数 -1未评分
+        /// </summary>
+        public double score { get; set; } = -1;
+        /// <summary>
+        /// 掩饰分数 -1未评分
+        /// </summary>
+        public double maskScore { get; set; } = -1;
+    }
+    /// <summary>
+    /// 专家分配的任务
+    /// </summary>
+    public class ActivityExpertTask:CosmosEntity
+    {
+        //id  教师id,
+        //code  ActivityExpertTask-活动id
+
+      
+    }
+    /// <summary>
+    /// 专家在优课评选模块的任务分配
+    /// </summary>
+    public class ExpertContestTask { 
+        public List<ContestExpert> experts { get; set; }
+
+    
+    }
+    public class ContestExpert {
+        public string tmdid { get; set; }
+        public string name { get; set; }
+        public string picture { get; set; }
+        public int status { get; set; } = -1;
+        public double score { get; set; } = -1;
+    }
+
+    public class ExpertDto : Expert
+    {
+
+    }
+
+    public class ContestAttachment
+    {
+        /// <summary>
+        /// 文件名字
+        /// </summary>
+        public string name { get; set; }
+        /// <summary>
+        /// 完整路径
+        /// </summary>
+        public string url { get; set; }
+        /// <summary>
+        /// 文件大小
+        /// </summary>
+        public long size { get; set; }
+        /// <summary>
+        /// 创建时间
+        /// </summary>
+        public long createTime { get; set; }
+        /// <summary>
+        /// 文件后缀
+        /// </summary>
+        public string extension { get; set; }
+        /// <summary>
+        /// 文件类型
+        /// </summary>
+        public string type { get; set; }
+        public string blob { get; set; }
+        public string hash { get; set; }
+        /// <summary>
+        /// 视频播放时长
+        /// </summary>
+        public double duration { get; set; }
+        /// <summary>
+        /// blob的容器名称
+        /// </summary>
+        public string cnt { get; set; }
+        /// <summary>
+        /// 创建者
+        /// </summary>
+        public long creator { get; set; }
+        public List<string> tag { get; set; } = new List<string>();
+    }
+
+    public class ContestSokrates
+    { 
+        public string name { get; set; }
+        public  string url {  get; set; }
+        /// <summary>
+        /// 视频播放时长
+        /// </summary>
+        public double duration { get; set; }
+        /// <summary>
+        /// 苏格拉底报告
+        /// </summary>
+        public string report { get; set; }
+        /// <summary>
+        /// 课例ID
+        /// </summary>
+        public string recordId {  get; set; }
+        /// <summary>
+        /// 封面
+        /// </summary>
+        public string poster { get; set; }
+        /// <summary>
+        /// 教师id 
+        /// </summary>
+        public string tmdid {  get; set; }
+
+    }
     /// <summary>
     /// <summary>
     /// 表单填报信息
     /// 表单填报信息
     /// </summary>
     /// </summary>

+ 2 - 1
TEAMModelOS.SDK/Models/Cosmos/Common/ExamClassResult.cs

@@ -36,7 +36,7 @@ namespace TEAMModelOS.SDK.Models
         //记录学生原始学校ID
         //记录学生原始学校ID
         //public List<string> scIds { get; set; } = new List<string>();
         //public List<string> scIds { get; set; } = new List<string>();
         //记录学生作答状态
         //记录学生作答状态
-        //0 未完成 1缺考 2补考 3补考完成
+        //0 已作答 1缺考 2补考 3补考完成
         public List<int> status { get; set; } = new List<int>();
         public List<int> status { get; set; } = new List<int>();
         //批注
         //批注
         public List<List<List<Details>>> mark { get; set; }
         public List<List<List<Details>>> mark { get; set; }
@@ -57,6 +57,7 @@ namespace TEAMModelOS.SDK.Models
         public List<int> fphc { get; set; } = new List<int>();
         public List<int> fphc { get; set; } = new List<int>();
         public List<int> fplc { get; set; } = new List<int>();
         public List<int> fplc { get; set; } = new List<int>();
         public List<int> fpc { get; set; } = new List<int>();
         public List<int> fpc { get; set; } = new List<int>();
+        public List<string> paper { get; set; }= new List<string>();
     }
     }
 /*    public class PaperSimple {
 /*    public class PaperSimple {
         public string id { get; set; }
         public string id { get; set; }

+ 1 - 0
TEAMModelOS.SDK/Models/Cosmos/School/CourseBase.cs

@@ -280,6 +280,7 @@ namespace TEAMModelOS.SDK.Models
     {
     {
         public string id { get; set; }
         public string id { get; set; }
         public string name { get; set; }
         public string name { get; set; }
+        public string bindId { get; set; }
     }
     }
 
 
    
    

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


Some files were not shown because too many files changed in this diff