CourseController.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. using Microsoft.AspNetCore.Mvc;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using TEAMModelOS.Models;
  7. using TEAMModelOS.SDK;
  8. using TEAMModelOS.SDK.DI;
  9. using System.Text.Json;
  10. using TEAMModelOS.SDK.Models;
  11. using TEAMModelOS.SDK.Extension;
  12. using Azure.Cosmos;
  13. using Microsoft.AspNetCore.Http;
  14. using Microsoft.Extensions.Options;
  15. using System.IO;
  16. using System.Dynamic;
  17. using System.Net.Http;
  18. using System.Net;
  19. using Newtonsoft.Json;
  20. using System.Linq;
  21. using StackExchange.Redis;
  22. using static TEAMModelOS.SDK.Models.Teacher;
  23. using Microsoft.Extensions.Configuration;
  24. using TEAMModelOS.Filter;
  25. using Microsoft.AspNetCore.Authorization;
  26. using HTEXLib.COMM.Helpers;
  27. using TEAMModelOS.SDK.Models.Service;
  28. using System.ComponentModel.DataAnnotations;
  29. namespace TEAMModelAPI.Controllers
  30. {
  31. [ProducesResponseType(StatusCodes.Status200OK)]
  32. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  33. [ApiController]
  34. [Route("school")]
  35. public class CourseController : ControllerBase
  36. {
  37. public AzureCosmosFactory _azureCosmos;
  38. private readonly AzureStorageFactory _azureStorage;
  39. private readonly AzureRedisFactory _azureRedis;
  40. private readonly DingDing _dingDing;
  41. private readonly Option _option;
  42. private readonly IConfiguration _configuration;
  43. private readonly CoreAPIHttpService _coreAPIHttpService;
  44. private readonly AzureServiceBusFactory _serviceBus;
  45. //1 2 3 4 5 6 7
  46. private List<string> weekDays = new List<string> { "MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN" };
  47. public CourseController(CoreAPIHttpService coreAPIHttpService, AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, DingDing dingDing, IOptionsSnapshot<Option> option, IConfiguration configuration, AzureServiceBusFactory serviceBus)
  48. {
  49. _azureCosmos = azureCosmos;
  50. _azureStorage = azureStorage;
  51. _azureRedis = azureRedis;
  52. _dingDing = dingDing;
  53. _option = option?.Value;
  54. _configuration = configuration;
  55. _coreAPIHttpService = coreAPIHttpService;
  56. _serviceBus = serviceBus;
  57. }
  58. [ProducesDefaultResponseType]
  59. [HttpPost("get-course-list")]
  60. [ApiToken(Auth = "1301", Name = "获取课程列表信息", RW = "R", Limit = false)]
  61. public async Task<IActionResult> GetCourseList(JsonElement json)
  62. {
  63. var client = _azureCosmos.GetCosmosClient();
  64. var (id, school) = HttpContext.GetApiTokenInfo();
  65. json.TryGetProperty("periodId", out JsonElement periodId);
  66. json.TryGetProperty("subjectId", out JsonElement subjectId);
  67. StringBuilder sql = new StringBuilder($"SELECT c.id,c.name,c.subject,c.period,c.scope,c.no,c.school FROM c where 1=1 ");
  68. if (!string.IsNullOrWhiteSpace($"{periodId}"))
  69. {
  70. sql.Append($" and c.period.id='{periodId}'");
  71. }
  72. if (!string.IsNullOrWhiteSpace($"{subjectId}"))
  73. {
  74. sql.Append($" and c.subject.id='{subjectId}'");
  75. }
  76. List<dynamic> courses = new List<dynamic>();
  77. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
  78. GetItemQueryIterator<dynamic>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{school}") }))
  79. {
  80. courses.Add(item);
  81. }
  82. return Ok(new { courses });
  83. }
  84. [ProducesDefaultResponseType]
  85. [HttpPost("get-course-info")]
  86. [ApiToken(Auth = "1302", Name = "课程详细信息", RW = "R", Limit = false)]
  87. public async Task<IActionResult> GetCourseInfo(JsonElement json)
  88. {
  89. var (id, school) = HttpContext.GetApiTokenInfo();
  90. json.TryGetProperty("courseId", out JsonElement courseId);
  91. Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
  92. .ReadItemStreamAsync($"{courseId}", new PartitionKey($"Course-{school}"));
  93. if (response.Status == 200)
  94. {
  95. JsonDocument document = JsonDocument.Parse(response.Content);
  96. Course course = document.RootElement.Deserialize<Course>();
  97. return Ok(new { course.name, course.id, course.subject, course.period, course.scope, course.school, course.no, course.desc, course.schedule });
  98. }
  99. else
  100. {
  101. return Ok(new { error = 1, msg = "课程不存在!" });
  102. }
  103. }
  104. /// <summary>
  105. /// 获取指定学段作息
  106. /// </summary>
  107. /// <param name="request"></param>
  108. /// <returns></returns>
  109. [ProducesDefaultResponseType]
  110. [HttpPost("get-period-timetable")]
  111. [ApiToken(Auth = "1303", Name = "试卷和评测的条件信息", RW = "R", Limit = false)]
  112. public async Task<IActionResult> GetPaperExamCondition(JsonElement json)
  113. {
  114. json.TryGetProperty("periodId", out JsonElement _periodId);
  115. var (id, school) = HttpContext.GetApiTokenInfo();
  116. School data = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(school, new PartitionKey("Base"));
  117. var period = data.period.Find(x => x.id.Equals($"{_periodId}"));
  118. if (period != null)
  119. {
  120. return Ok(new { period.subjects, period.timetable, period.grades, period.majors , weekDays });
  121. }
  122. else
  123. {
  124. return Ok(new { error = 1, msg = "学段不存在!" });
  125. }
  126. }
  127. [ProducesDefaultResponseType]
  128. [HttpPost("upsert-course-infos")]
  129. [ApiToken(Auth = "1304", Name = "课程详细信息", RW = "W", Limit = false)]
  130. public async Task<IActionResult> UpsertCourseInfo(CourseDtoImpt json)
  131. {
  132. var (id, school) = HttpContext.GetApiTokenInfo();
  133. List<CourseDto> courseDtos = json.courses;
  134. List<Dictionary<string, string>> errorData = new List<Dictionary<string, string>>();
  135. List<Course> courses = new List<Course>() ;
  136. School data = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(school, new PartitionKey("Base"));
  137. foreach (var courseDto in courseDtos) {
  138. var period = data.period.Find(x => x.id.Equals($"{courseDto.periodId}"));
  139. if (period != null)
  140. {
  141. //同名学科
  142. var subject = period.subjects.Find(x => x.id.Equals($"{courseDto.subjectId}"));
  143. if (subject == null) {
  144. subject = period.subjects.Find(x => x.name.Equals($"{courseDto.subjectName}"));
  145. }
  146. if (subject == null) {
  147. subject = new Subject { id = courseDto.subjectId, name = subject.name, type = 1 };
  148. period.subjects.Add(subject);
  149. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(data, data.id, new PartitionKey("Base"));
  150. }
  151. Course course = null;
  152. if (string.IsNullOrWhiteSpace(courseDto?.id))
  153. {
  154. course = new Course
  155. {
  156. pk = "Course",
  157. id = Guid.NewGuid().ToString(),
  158. code = $"Course-{school}",
  159. name = courseDto.name,
  160. subject = new SubjectSimple { id = subject.id, name = subject.name },
  161. period = new PeriodSimple { id = period.id, name = period.name },
  162. school = school,
  163. desc = courseDto.desc,
  164. scope = "school",
  165. no = courseDto.no,
  166. };
  167. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).CreateItemAsync(course, new PartitionKey(course.code));
  168. }
  169. else
  170. {
  171. Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{course.id}", new PartitionKey($"Course-{school}"));
  172. if (response.Status == 200)
  173. {
  174. JsonDocument jsonDocument = JsonDocument.Parse(response.Content);
  175. course = jsonDocument.RootElement.ToObject<Course>();
  176. course.pk = "Course";
  177. course.name = string.IsNullOrWhiteSpace(courseDto.name) ? course.name : courseDto.name;
  178. course.subject = new SubjectSimple { id = subject.id, name = subject.name };
  179. course.period = new PeriodSimple { id = period.id, name = period.name };
  180. course.school = school;
  181. course.desc = string.IsNullOrWhiteSpace(courseDto.desc) ? course.desc : courseDto.desc;
  182. course.scope = "school";
  183. course.no = string.IsNullOrWhiteSpace(courseDto.no) ? course.no : courseDto.no;
  184. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(course, course.id, new PartitionKey(course.code));
  185. }
  186. else
  187. {
  188. course = new Course
  189. {
  190. pk = "Course",
  191. id = Guid.NewGuid().ToString(),
  192. code = $"Course-{school}",
  193. name = courseDto.name,
  194. subject = new SubjectSimple { id = subject.id, name = subject.name },
  195. period = new PeriodSimple { id = period.id, name = period.name },
  196. school = school,
  197. desc = courseDto.desc,
  198. scope = "school",
  199. no = courseDto.no,
  200. };
  201. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).CreateItemAsync(course, new PartitionKey(course.code));
  202. }
  203. }
  204. if (course != null) { courses.Add(course); }
  205. }
  206. else
  207. {
  208. errorData.Add(new Dictionary<string, string> { { "course", courseDto.name }, { "periodId", courseDto.periodId } });
  209. //return Ok(new { error = 2, msg = "学段不存在!" });
  210. }
  211. }
  212. return Ok(new { courses = courses ,errorData});
  213. }
  214. //[Required(ErrorMessage = "{0} 课程的科目id必须填写"), RegularExpression(@"[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}",ErrorMessage ="科目的uuid格式错误!")]
  215. public class ImportCourseDto {
  216. public List<ImportCourse> courses { get; set; } = new List<ImportCourse>();
  217. }
  218. public class ImportCourse {
  219. [Required(ErrorMessage = "课程id 必须设置"), RegularExpression(@"[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}", ErrorMessage = "科目的uuid格式错误!")]
  220. public string courseId { get; set; }
  221. [Required(ErrorMessage = "课程名称 必须设置")]
  222. public string courseName { get; set; }
  223. [Required(ErrorMessage = "课程科目id 必须设置"), RegularExpression(@"[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}", ErrorMessage = "科目的uuid格式错误!")]
  224. public string subjectId { get; set; }
  225. [Required(ErrorMessage = "课程科目名称 必须设置")]
  226. public string subjectName { get; set; }
  227. [Required(ErrorMessage = "课程学段id 必须设置"), RegularExpression(@"[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}", ErrorMessage = "学段的uuid格式错误!")]
  228. public string periodId { get; set; }
  229. public List<Schedule> schedules { get; set; }
  230. }
  231. [ProducesDefaultResponseType]
  232. [HttpPost("upsert-course-schedule")]
  233. [ApiToken(Auth = "1305", Name = "更新课程的排课信息", RW = "W", Limit = false)]
  234. public async Task<IActionResult> UpsertCourseSchedule(ImportCourseDto json)
  235. {
  236. var (id, school) = HttpContext.GetApiTokenInfo();
  237. List<ImportCourse> importCourses = json.courses;
  238. HashSet<string> courseIds= importCourses .Select(x => x.courseId).ToHashSet();
  239. if (courseIds.Count < 1) { return Ok(new { error = 1, msg = "课程参数错误!" }); }
  240. //string sql = $"select value(c) from c where c.id in({string.Join(",",courseIds.Select(x=>$"'{x}'"))})";
  241. string sql = $"select value(c) from c ";//直接获取全校的课程
  242. List<Course> courses = new List<Course>();
  243. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
  244. .GetItemQueryIterator<Course>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Course-{school}") })) {
  245. courses.Add(item);
  246. }
  247. List<Subject> addSubjects = new List<Subject>();
  248. School data = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(school, new PartitionKey("Base"));
  249. //不存在的课程,可以被直接创建
  250. var unexistCourseIds = courseIds.Except(courses.Select(x => x.id));
  251. foreach (var item in unexistCourseIds) {
  252. ImportCourse importCourse= importCourses.Find(x => x.courseId.Equals(item));
  253. if (importCourse != null) {
  254. Period period= data.period.Find(x => x.id.Equals(importCourse.periodId));
  255. if (period != null) {
  256. //同名学科
  257. var subject = period.subjects.Find(x => x.id.Equals($"{importCourse.subjectId}"));
  258. if (subject == null)
  259. {
  260. subject = period.subjects.Find(x => x.name.Equals($"{importCourse.subjectName}"));
  261. }
  262. if (subject == null) {
  263. subject = new Subject { id = importCourse.subjectId, name = importCourse.subjectName, type = 1 };
  264. period.subjects.Add(subject);
  265. addSubjects.Add(subject);
  266. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(data, data.id, new PartitionKey("Base"));
  267. }
  268. Course course = new Course
  269. {
  270. id = importCourse.courseId,
  271. code = $"Course-{school}",
  272. pk = "Course",
  273. name = importCourse.courseName,
  274. period = new PeriodSimple { id = period.id, name = period.name },
  275. subject = new SubjectSimple { id = subject.id, name = subject.name },
  276. school = school,
  277. scope = "school",
  278. year = DateTimeOffset.Now.Year,
  279. schedule = new List<Schedule>(),
  280. };
  281. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).CreateItemAsync(course, new PartitionKey(course.code));
  282. courses.Add(course);
  283. }
  284. }
  285. }
  286. //importCourses =importCourses .Where(x => !unexistCourseIds .Contains(x.courseId));
  287. //排查 课程学段,课程排课作息,课程排课的星期几是否准确
  288. List<ScheduleTimeDto> import_schedules_hastime = new List<ScheduleTimeDto>() ;
  289. List<ScheduleNoTimeDto> import_schedules_nottime = new List<ScheduleNoTimeDto>();
  290. //保存没有选用名单的排课。
  291. List<Schedule> schedules_noList= new List<Schedule>() ;
  292. List<ScheduleTimeDto> weeksError = new List<ScheduleTimeDto>();
  293. importCourses .ToList().ForEach(x => {
  294. x.schedules.ForEach(z => {
  295. if (!string.IsNullOrWhiteSpace(z.classId) || !string.IsNullOrWhiteSpace(z.stulist))
  296. {
  297. string classId = null;
  298. //行政班不为空,教学班为空,则名单取行政班
  299. classId = !string.IsNullOrWhiteSpace(z.classId) && string.IsNullOrWhiteSpace(z.stulist) ? z.classId : classId;
  300. //行政班为空,教学班不为空,则名单取教学班
  301. classId = string.IsNullOrWhiteSpace(z.classId) && !string.IsNullOrWhiteSpace(z.stulist) ? z.stulist : classId;
  302. //行政班,教学班都不为空,且相同,则任取一个,取的是行政班
  303. classId = !string.IsNullOrWhiteSpace(z.classId) && !string.IsNullOrWhiteSpace(z.stulist) && z.classId.Equals(z.stulist) ? z.classId : classId;
  304. //行政班,教学班都不为空,且不同,则取null
  305. classId = !string.IsNullOrWhiteSpace(z.classId) && !string.IsNullOrWhiteSpace(z.stulist) && !z.classId.Equals(z.stulist) ? null : classId;
  306. if (!string.IsNullOrWhiteSpace(classId))
  307. {
  308. if (z.time.IsNotEmpty())
  309. {
  310. z.time.ForEach(t =>
  311. {
  312. ScheduleTimeDto scheduleDto = new ScheduleTimeDto
  313. {
  314. courseId = x.courseId,
  315. roomId = z.room,
  316. classId = z.classId,
  317. stulist = z.stulist,
  318. teacherId = z.teacherId,
  319. timeId = t.id,
  320. week = t.week,
  321. keyTeacher = $"{z.teacherId}_{t.week}_{t.id}",
  322. keyGroupId = $"{classId}_{t.week}_{t.id}",
  323. keyRoomIds = string.IsNullOrWhiteSpace(z.room) ? null : $"{z.room}_{t.week}_{t.id}"
  324. };
  325. //星期几自检 1 2 3 4 5 6 7
  326. if (weekDays.Contains(t.week))
  327. {
  328. import_schedules_hastime.Add(scheduleDto);
  329. }
  330. else
  331. {
  332. weeksError.Add(scheduleDto);
  333. }
  334. });
  335. }
  336. else {
  337. //允许导入没有排课时间表的课程。
  338. import_schedules_nottime.Add(new ScheduleNoTimeDto
  339. {
  340. courseId = x.courseId,
  341. roomId = z.room,
  342. classId = z.classId,
  343. stulist = z.stulist,
  344. teacherId = z.teacherId,
  345. });
  346. }
  347. }
  348. else { schedules_noList.Add(z); }
  349. }
  350. else {
  351. schedules_noList.Add(z);
  352. }
  353. });
  354. });
  355. //导入的排课自检。
  356. //教师自检
  357. var check_teacher = import_schedules_hastime.GroupBy(x => x.keyTeacher).Select(g => new { key = g.Key, list = g.ToList() });
  358. IEnumerable<ScheduleTimeDto> teacherWarning = new List<ScheduleTimeDto>();
  359. teacherWarning = check_teacher.Where(x => x.list.Count > 1).SelectMany(x => x.list);
  360. //import_schedules.RemoveAll(x => import_teacherConfuse.Contains(x));
  361. //名单自检
  362. var check_groupId = import_schedules_hastime.GroupBy(x => x.keyGroupId).Select(g => new { key = g.Key, list = g.ToList() });
  363. IEnumerable<ScheduleTimeDto> groupIdWarning = new List<ScheduleTimeDto>();
  364. groupIdWarning = check_groupId.Where(x => x.list.Count > 1).SelectMany(x => x.list);
  365. //import_schedules.RemoveAll(x => import_groupIdConfuse.Contains(x));
  366. //物理教室自检
  367. 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() });
  368. IEnumerable<ScheduleTimeDto> roomIdsWarning = new List<ScheduleTimeDto>();
  369. roomIdsWarning = check_roomIds.Where(x => x.list.Count > 1).SelectMany(x => x.list);
  370. //import_schedules.RemoveAll(x => import_roomIdsConfuse.Contains(x));
  371. //打散数据库已经有的排课信息
  372. List<ScheduleTimeDto> database_schedules = new List<ScheduleTimeDto>();
  373. courses.ForEach(x => {
  374. x.schedule.ForEach(z => {
  375. if (!string.IsNullOrWhiteSpace(z.teacherId) &&(!string.IsNullOrWhiteSpace(z.classId) || !string.IsNullOrWhiteSpace(z.stulist)))
  376. {
  377. string classId = null;
  378. //行政班不为空,教学班为空,则名单取行政班
  379. classId = !string.IsNullOrWhiteSpace(z.classId) && string.IsNullOrWhiteSpace(z.stulist) ? z.classId : classId;
  380. //行政班为空,教学班不为空,则名单取教学班
  381. classId = string.IsNullOrWhiteSpace(z.classId) && !string.IsNullOrWhiteSpace(z.stulist) ? z.stulist : classId;
  382. //行政班,教学班都不为空,且相同,则任取一个,取的是行政班
  383. classId = !string.IsNullOrWhiteSpace(z.classId) && !string.IsNullOrWhiteSpace(z.stulist) && z.classId.Equals(z.stulist) ? z.classId : classId;
  384. //行政班,教学班都不为空,且不同,则取null
  385. classId = !string.IsNullOrWhiteSpace(z.classId) && !string.IsNullOrWhiteSpace(z.stulist) && !z.classId.Equals(z.stulist) ? null : classId;
  386. if (!string.IsNullOrWhiteSpace(classId))
  387. {
  388. z.time.ForEach(t =>
  389. {
  390. ScheduleTimeDto scheduleDto = new ScheduleTimeDto
  391. {
  392. courseId = x.id,
  393. roomId = z.room,
  394. classId = z.classId,
  395. stulist = z.stulist,
  396. teacherId = z.teacherId,
  397. timeId = t.id,
  398. week = t.week,
  399. keyTeacher = $"{z.teacherId}_{t.week}_{t.id}",
  400. keyGroupId = $"{classId}_{t.week}_{t.id}",
  401. keyRoomIds = string.IsNullOrWhiteSpace(z.room) ? null : $"{z.room}_{t.week}_{t.id}"
  402. };
  403. database_schedules.Add(scheduleDto);
  404. });
  405. }
  406. }
  407. });
  408. });
  409. List<ScheduleTimeDto> teacherError = new List<ScheduleTimeDto>();
  410. List<ScheduleTimeDto> groupIdError = new List<ScheduleTimeDto>();
  411. List<ScheduleTimeDto> roomIdsError = new List<ScheduleTimeDto>();
  412. //数据库排查
  413. import_schedules_hastime.ForEach(x => {
  414. //检查教师的排课是否冲突,不同的课程不能出现 教师冲突的情况, 相同课程可能是需要更新的。
  415. if (database_schedules.FindAll(s => s.keyTeacher.Equals(x.keyTeacher) && !x.courseId.Equals(s.courseId)).IsNotEmpty())
  416. {
  417. teacherError.Add(x);
  418. }
  419. //检查名单的排课是否冲突
  420. if (database_schedules.FindAll(s => s.keyGroupId.Equals(x.keyGroupId) && !x.courseId.Equals(s.courseId)).IsNotEmpty())
  421. {
  422. groupIdError.Add(x);
  423. }
  424. //检查教室的排课是否冲突
  425. if (database_schedules.FindAll(s => s.keyRoomIds.Equals(x.keyRoomIds) && !x.courseId.Equals(s.courseId)).IsNotEmpty())
  426. {
  427. roomIdsError.Add(x);
  428. }
  429. });
  430. //移除 教师,名单,教室冲突的排课
  431. import_schedules_hastime.RemoveAll(x => teacherError.Contains(x));
  432. import_schedules_hastime.RemoveAll(x => groupIdError.Contains(x));
  433. import_schedules_hastime.RemoveAll(x => roomIdsError.Contains(x));
  434. //最终导入之前,必须检查,课程是否存在(notInCourseIds),教师是否存在,名单是否存在,并重新排列行政班,教学班,
  435. //排课时间段id是否正确,星期几是否正确(import_weeksConfuse),教室是否正确
  436. //检查教师存在的
  437. HashSet<string> teachers = import_schedules_hastime.Select(x => x.teacherId).ToHashSet();
  438. teachers.Union(import_schedules_nottime.Select(x => x.teacherId));
  439. IEnumerable<string> unexistTeacherIds= null;
  440. if (teachers.Count > 0) {
  441. List<string> teacherIds = new List<string>();
  442. string sqlTeacher = $"select value(c.id) from c where c.id in ({string.Join(",",teachers.Select(x=>$"'{x}'"))})";
  443. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
  444. .GetItemQueryIterator<string>(queryText: sqlTeacher, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Teacher-{school}") }))
  445. {
  446. teacherIds.Add(item);
  447. }
  448. unexistTeacherIds= teachers.Except(teacherIds);
  449. //移除不存在的教师
  450. import_schedules_hastime.RemoveAll(x => unexistTeacherIds.Contains(x.teacherId));
  451. import_schedules_nottime.RemoveAll(x => unexistTeacherIds.Contains(x.teacherId));
  452. }
  453. //检查教室存在的
  454. HashSet<string> roomIds = import_schedules_hastime.Select(x => x.roomId).ToHashSet();
  455. roomIds.Union(import_schedules_nottime.Select(x => x.roomId));
  456. IEnumerable<string> unexistRoomIds = null;
  457. if (roomIds.Count > 0)
  458. {
  459. List<string> rooms = new List<string>();
  460. string sqlRoom = $"select value(c.id) from c where c.id in ({string.Join(",", roomIds.Select(x => $"'{x}'"))})";
  461. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
  462. .GetItemQueryIterator<string>(queryText: sqlRoom, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Room-{school}") }))
  463. {
  464. rooms.Add(item);
  465. }
  466. unexistRoomIds= roomIds.Except(rooms);
  467. //移除不存在的教室
  468. import_schedules_hastime.RemoveAll(x => unexistRoomIds.Contains(x.roomId));
  469. import_schedules_nottime.RemoveAll(x => unexistRoomIds.Contains(x.roomId));
  470. }
  471. //检查名单存在的
  472. List<string> groupIds = new List<string>();
  473. var classIdsHasTime = import_schedules_hastime.Where(x => !string.IsNullOrWhiteSpace(x.classId)).Select(x => x.classId).ToHashSet();
  474. if (classIdsHasTime.Any()) {
  475. groupIds.AddRange(classIdsHasTime);
  476. }
  477. var stulistsHasTime = import_schedules_hastime.Where(x => !string.IsNullOrWhiteSpace(x.stulist)).Select(x => x.stulist).ToHashSet();
  478. if (stulistsHasTime.Any())
  479. {
  480. groupIds.AddRange(stulistsHasTime);
  481. }
  482. var classIdsNotTime = import_schedules_nottime.Where(x => !string.IsNullOrWhiteSpace(x.classId)).Select(x => x.classId).ToHashSet();
  483. if (classIdsNotTime.Any())
  484. {
  485. groupIds.AddRange(classIdsNotTime);
  486. }
  487. var stulistsNotTime = import_schedules_nottime.Where(x => !string.IsNullOrWhiteSpace(x.stulist)).Select(x => x.stulist).ToHashSet();
  488. if (stulistsNotTime.Any())
  489. {
  490. groupIds.AddRange(stulistsNotTime);
  491. }
  492. List<GroupListDto> groupListDtos= await GroupListService.GetGroupListListids(_azureCosmos.GetCosmosClient(), _dingDing, groupIds, school);
  493. IEnumerable<string> unexistGroupIds = groupIds.Except(groupListDtos.Select(x=>x.id));
  494. //移除不存在的名单id
  495. import_schedules_hastime.RemoveAll(x => unexistGroupIds.Contains(x.classId));
  496. import_schedules_hastime.RemoveAll(x => unexistGroupIds.Contains(x.stulist));
  497. import_schedules_nottime.RemoveAll(x => unexistGroupIds.Contains(x.classId));
  498. import_schedules_nottime.RemoveAll(x => unexistGroupIds.Contains(x.stulist));
  499. HashSet<Course> update_course = new HashSet<Course>();
  500. HashSet<string> unexistTimeIds = new HashSet<string>();
  501. //处理包含时间排课的课程
  502. import_schedules_hastime.ForEach(schedule => {
  503. Course course = courses.Find(x => x.id.Equals(schedule.courseId));
  504. if (string.IsNullOrWhiteSpace(course?.period?.id))
  505. {
  506. Period period = data.period.Find(p => p.id.Equals(course.period.id));
  507. TimeTable timeTable = period?.timetable.Find(x => x.id.Equals(schedule.timeId));
  508. if (timeTable != null)
  509. {
  510. string groupId= string.IsNullOrWhiteSpace(schedule.classId)?schedule.stulist:schedule.classId;
  511. GroupListDto groupList= groupListDtos.Find(g => g.id.Equals(groupId));
  512. string classId = null;
  513. string stulist = null;
  514. if (groupList.type.Equals("class")) {
  515. classId = groupList.id;
  516. }
  517. else {
  518. stulist = groupList.id;
  519. }
  520. var course_schedule =course.schedule.Find(x => x.teacherId.Equals(schedule.teacherId));
  521. if (course_schedule != null)
  522. {
  523. course_schedule.classId = classId;
  524. course_schedule.stulist = stulist ;
  525. course_schedule.room = schedule.roomId;
  526. var time= course_schedule.time.Find(t => t.id.Equals(schedule.timeId) && t.week.Equals(schedule.week));
  527. if (time != null)
  528. {
  529. time.id=schedule.timeId;
  530. time.week=schedule.week;
  531. }
  532. else {
  533. course_schedule.time.Add(new TimeInfo { id = schedule.timeId, week = schedule.week });
  534. }
  535. }
  536. else {
  537. 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} } });
  538. }
  539. update_course.Add(course);
  540. }
  541. else {
  542. //课程,所在学段对应的作息时间不正确
  543. unexistTimeIds.Add(schedule.timeId);
  544. }
  545. }
  546. });
  547. //处理没有时间排课的课程
  548. import_schedules_nottime.ForEach(schedule => {
  549. Course course = courses.Find(x => x.id.Equals(schedule.courseId));
  550. if (string.IsNullOrWhiteSpace(course?.period?.id))
  551. {
  552. Period period = data.period.Find(p => p.id.Equals(course.period.id));
  553. string groupId = string.IsNullOrWhiteSpace(schedule.classId) ? schedule.stulist : schedule.classId;
  554. GroupListDto groupList = groupListDtos.Find(g => g.id.Equals(groupId));
  555. string classId = null;
  556. string stulist = null;
  557. if (groupList.type.Equals("class"))
  558. {
  559. classId = groupList.id;
  560. }
  561. else
  562. {
  563. stulist = groupList.id;
  564. }
  565. var course_schedule = course.schedule.Find(x => x.teacherId.Equals(schedule.teacherId));
  566. if (course_schedule != null)
  567. {
  568. course_schedule.classId = classId;
  569. course_schedule.stulist = stulist;
  570. course_schedule.room = schedule.roomId;
  571. }
  572. else
  573. {
  574. course.schedule.Add(new Schedule { teacherId=schedule.teacherId, classId = classId, stulist = stulist, room = schedule.roomId});
  575. }
  576. update_course.Add(course);
  577. }
  578. });
  579. foreach (var item in update_course) {
  580. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
  581. }
  582. return Ok(new {
  583. import= new //导入数据自检信息
  584. {
  585. teacherWarning,//自检-教师冲突的排课
  586. groupIdWarning,//自检-名单冲突的排课
  587. roomIdsWarning,//自检-物理教室冲突的排课
  588. weeksError //自检-错误的星期几编码
  589. },
  590. database= new //数据库比对信息
  591. {
  592. teacherError,//数据比对-教师冲突的排课
  593. groupIdError,//数据比对-名单冲突的排课
  594. roomIdsError,//数据比对-物理教室冲突的排课
  595. unexistCourseIds ,//不存在的课程
  596. unexistTeacherIds,//不存在的教师
  597. unexistGroupIds,//不存在的名单
  598. unexistRoomIds,//不存在的教室
  599. unexistTimeIds //不存在的作息
  600. },
  601. updateCourse= update_course,
  602. addSubjects= addSubjects
  603. });
  604. }
  605. }
  606. }