123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635 |
- 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
- });
- }
-
- }
- }
|