34 Commits
121 changed files with 116569 additions and 1729 deletions
+1
View File
@@ -18,6 +18,7 @@ BackgroundJobs__AutomaticScheduleConcurrency=1
BackgroundJobs__SchedulePublishConcurrency=1
BackgroundJobs__MakeupExamAutoConcurrency=1
BackgroundJobs__ExamArrangementConcurrency=1
BackgroundJobs__CourseGradeStatisticsRefreshConcurrency=1
# RabbitMq__HostName=rabbitmq.example.edu.cn
# RabbitMq__Port=5671
# RabbitMq__UserName=jiaowu
@@ -1,6 +1,7 @@
using System.ComponentModel.DataAnnotations;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Domain.System;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Grades;
using Jiaowu.Api.Infrastructure.Persistence;
@@ -491,6 +491,7 @@ public sealed class BaseDataController(AppDbContext db, IAppCache cache) : Contr
x.Building.Campus!.Name,
x.Capacity,
x.RoomType,
x.TeachingVenueNature,
x.Equipment,
x.IsEnabled,
x.SortOrder))
@@ -557,6 +558,9 @@ public sealed class BaseDataController(AppDbContext db, IAppCache cache) : Contr
BuildingId = request.BuildingId,
Capacity = request.Capacity,
RoomType = request.RoomType.Trim(),
TeachingVenueNature = request.TeachingVenueNature == 0
? TeachingVenueNature.GeneralClassroom
: request.TeachingVenueNature,
Equipment = request.Equipment?.Trim(),
SortOrder = request.SortOrder,
IsEnabled = request.IsEnabled
@@ -577,6 +581,9 @@ public sealed class BaseDataController(AppDbContext db, IAppCache cache) : Contr
entity.BuildingId = request.BuildingId;
entity.Capacity = request.Capacity;
entity.RoomType = request.RoomType.Trim();
entity.TeachingVenueNature = request.TeachingVenueNature == 0
? TeachingVenueNature.GeneralClassroom
: request.TeachingVenueNature;
entity.Equipment = request.Equipment?.Trim();
await SaveAndInvalidateAsync(cancellationToken);
return entity;
@@ -728,6 +735,7 @@ public sealed record ClassroomRequest(
Guid BuildingId,
[Range(1, 1000)] int Capacity,
[Required, MaxLength(40)] string RoomType,
TeachingVenueNature TeachingVenueNature,
[MaxLength(300)] string? Equipment)
: CatalogRequest(Code, Name, SortOrder, IsEnabled);
@@ -784,6 +792,7 @@ public sealed record ClassroomListItem(
string CampusName,
int Capacity,
string RoomType,
TeachingVenueNature TeachingVenueNature,
string? Equipment,
bool IsEnabled,
int SortOrder);
@@ -27,7 +27,7 @@ public sealed class BaseDataExcelController(AppDbContext db, IAppCache cache) :
["classes"] = ["编码", "名称", "所属专业编码", "年级", "辅导员工号", "排序", "状态"],
["terms"] = ["编码", "名称", "学年", "学期季", "开始日期", "结束日期", "当前学期", "状态"],
["buildings"] = ["编码", "名称", "所属校区编码", "排序", "状态"],
["classrooms"] = ["编码", "名称", "所属教学楼编码", "容量", "教室类型", "设备", "排序", "状态"],
["classrooms"] = ["编码", "名称", "所属教学楼编码", "容量", "教室类型", "教学场地性质", "设备", "排序", "状态"],
["course-categories"] = ["编码", "名称", "排序", "状态"]
};
@@ -70,7 +70,10 @@ public sealed class BaseDataExcelController(AppDbContext db, IAppCache cache) :
IReadOnlyList<ExcelRow> rows;
try
{
rows = await ExcelWorkbookHelper.ReadAsync(file, headers, cancellationToken);
var requiredHeaders = kind.Equals("classrooms", StringComparison.OrdinalIgnoreCase)
? headers.Where(x => x != "教学场地性质").ToArray()
: headers;
rows = await ExcelWorkbookHelper.ReadAsync(file, requiredHeaders, cancellationToken);
}
catch (InvalidDataException exception)
{
@@ -165,6 +168,7 @@ public sealed class BaseDataExcelController(AppDbContext db, IAppCache cache) :
"classrooms" => (await db.Classrooms.AsNoTracking().Include(x => x.Building)
.OrderBy(x => x.Code).ToListAsync(cancellationToken))
.Select(x => Row(x.Code, x.Name, x.Building!.Code, x.Capacity, x.RoomType,
VenueNatureName(x.TeachingVenueNature),
x.Equipment, x.SortOrder, Status(x.IsEnabled))).ToList(),
"course-categories" => (await db.CourseCategories.AsNoTracking()
.OrderBy(x => x.SortOrder).ThenBy(x => x.Code)
@@ -473,8 +477,9 @@ public sealed class BaseDataExcelController(AppDbContext db, IAppCache cache) :
var buildingCode = Required(row, "所属教学楼编码", errors);
var capacity = ParseInt(row, "容量", 1, 1000, errors);
var roomType = Required(row, "教室类型", errors);
var venueNature = ParseVenueNature(row, roomType, errors);
if (code is null || name is null || buildingCode is null ||
capacity is null || roomType is null) continue;
capacity is null || roomType is null || venueNature is null) continue;
if (!buildings.TryGetValue(buildingCode, out var building))
{
errors.Add($"第 {row.RowNumber} 行:所属教学楼编码“{buildingCode}”不存在。");
@@ -488,7 +493,8 @@ public sealed class BaseDataExcelController(AppDbContext db, IAppCache cache) :
Code = code,
Name = name,
BuildingId = building.Id,
RoomType = roomType
RoomType = roomType,
TeachingVenueNature = venueNature.Value
};
db.Classrooms.Add(entity);
existing[code] = entity;
@@ -499,6 +505,7 @@ public sealed class BaseDataExcelController(AppDbContext db, IAppCache cache) :
entity.BuildingId = building.Id;
entity.Capacity = capacity.Value;
entity.RoomType = roomType;
entity.TeachingVenueNature = venueNature.Value;
entity.Equipment = Optional(row, "设备");
}
return new(created, updated, rows.Count);
@@ -597,6 +604,57 @@ public sealed class BaseDataExcelController(AppDbContext db, IAppCache cache) :
return true;
}
private static TeachingVenueNature? ParseVenueNature(
ExcelRow row,
string? roomType,
List<string> errors)
{
var value = Optional(row, "教学场地性质");
if (value is null) return InferVenueNature(roomType ?? string.Empty);
var result = (TeachingVenueNature)0;
foreach (var part in value.Split(['、', '', ',', ';', ''],
StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))
{
result |= part switch
{
"普通教室" => TeachingVenueNature.GeneralClassroom,
"实验室" => TeachingVenueNature.Laboratory,
"实训室" => TeachingVenueNature.TrainingRoom,
"计算机机房" or "机房" => TeachingVenueNature.ComputerLab,
"语音室" => TeachingVenueNature.LanguageLab,
"体育场地" => TeachingVenueNature.SportsVenue,
"艺术场地" => TeachingVenueNature.ArtsVenue,
_ => (TeachingVenueNature)0
};
if (part is not ("普通教室" or "实验室" or "实训室" or "计算机机房" or "机房" or "语音室" or "体育场地" or "艺术场地"))
errors.Add($"第 {row.RowNumber} 行:“教学场地性质”包含不支持的值“{part}”。");
}
return result == 0 ? null : result;
}
private static TeachingVenueNature InferVenueNature(string roomType) =>
roomType.Contains("机房", StringComparison.OrdinalIgnoreCase)
? TeachingVenueNature.Laboratory | TeachingVenueNature.ComputerLab
: roomType.Contains("语音", StringComparison.OrdinalIgnoreCase)
? TeachingVenueNature.Laboratory | TeachingVenueNature.LanguageLab
: roomType.Contains("实训", StringComparison.OrdinalIgnoreCase)
? TeachingVenueNature.TrainingRoom
: roomType.Contains("实验", StringComparison.OrdinalIgnoreCase)
? TeachingVenueNature.Laboratory
: TeachingVenueNature.GeneralClassroom;
private static string VenueNatureName(TeachingVenueNature value) => string.Join("、",
new[]
{
(TeachingVenueNature.GeneralClassroom, "普通教室"),
(TeachingVenueNature.Laboratory, "实验室"),
(TeachingVenueNature.TrainingRoom, "实训室"),
(TeachingVenueNature.ComputerLab, "计算机机房"),
(TeachingVenueNature.LanguageLab, "语音室"),
(TeachingVenueNature.SportsVenue, "体育场地"),
(TeachingVenueNature.ArtsVenue, "艺术场地")
}.Where(x => (value & x.Item1) != 0).Select(x => x.Item2));
private static bool ParseBoolean(
ExcelRow row, string header, bool defaultValue, List<string> errors)
{
@@ -3,6 +3,7 @@ using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Persistence;
using Jiaowu.Api.Infrastructure.Timetables;
using Jiaowu.Api.Infrastructure.Scheduling;
using Jiaowu.Api.Infrastructure.Teaching;
using Microsoft.AspNetCore.Authorization;
@@ -286,6 +287,8 @@ public sealed class CourseAdjustmentsController(
db.CourseAdjustments.Add(adj);
await db.SaveChangesAsync(cancellationToken);
await new PublishedTimetableProjectionService(db)
.RebuildPublishedPlansForTaskAsync(adj.TeachingTaskId, cancellationToken);
if (request.Submit)
{
@@ -0,0 +1,161 @@
using System.ComponentModel.DataAnnotations;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Jiaowu.Api.Controllers;
[ApiController]
[Authorize(Roles = ReadRoles)]
[Route("api/course-groups")]
public sealed class CourseGroupsController(AppDbContext db) : ControllerBase
{
private const string ReadRoles =
SystemRoles.SuperAdmin + "," +
SystemRoles.AcademicAdmin + "," +
SystemRoles.CollegeAdmin;
private const string ManageRoles =
SystemRoles.SuperAdmin + "," +
SystemRoles.AcademicAdmin;
[HttpGet]
public async Task<ActionResult> GetAll(CancellationToken cancellationToken)
{
var groups = await db.CourseGroups.AsNoTracking()
.OrderBy(x => x.Code)
.Select(x => new
{
x.Id,
x.Code,
x.Name,
x.Description,
CourseCount = x.Courses.Count,
Courses = x.Courses.OrderBy(item => item.Course!.Code).Select(item => new
{
item.Id,
item.CourseId,
CourseCode = item.Course!.Code,
CourseName = item.Course.Name,
item.Course.Credits,
item.Course.TotalHours,
item.Course.Nature
})
})
.ToListAsync(cancellationToken);
return Ok(groups);
}
[HttpPost]
[Authorize(Roles = ManageRoles)]
public async Task<ActionResult> Create(
CourseGroupRequest request,
CancellationToken cancellationToken)
{
var group = new CourseGroup
{
Code = request.Code.Trim(),
Name = request.Name.Trim(),
Description = Normalize(request.Description)
};
db.CourseGroups.Add(group);
return await SaveCreatedAsync(group.Id, cancellationToken);
}
[HttpPut("{id:guid}")]
[Authorize(Roles = ManageRoles)]
public async Task<ActionResult> Update(
Guid id,
CourseGroupRequest request,
CancellationToken cancellationToken)
{
var group = await db.CourseGroups.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
if (group is null) return NotFound();
group.Code = request.Code.Trim();
group.Name = request.Name.Trim();
group.Description = Normalize(request.Description);
return await SaveNoContentAsync(cancellationToken);
}
[HttpDelete("{id:guid}")]
[Authorize(Roles = ManageRoles)]
public async Task<ActionResult> Delete(Guid id, CancellationToken cancellationToken)
{
var group = await db.CourseGroups.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
if (group is null) return NotFound();
db.CourseGroups.Remove(group);
return await SaveNoContentAsync(cancellationToken);
}
[HttpPost("{id:guid}/courses")]
[Authorize(Roles = ManageRoles)]
public async Task<ActionResult> AddCourse(
Guid id,
CourseGroupCourseRequest request,
CancellationToken cancellationToken)
{
if (!await db.CourseGroups.AnyAsync(x => x.Id == id, cancellationToken)) return NotFound();
if (!await db.Courses.AnyAsync(x => x.Id == request.CourseId && x.IsEnabled, cancellationToken))
return ValidationProblem("所选课程不存在或已停用。");
db.CourseGroupCourses.Add(new CourseGroupCourse { CourseGroupId = id, CourseId = request.CourseId });
return await SaveCreatedAsync(id, cancellationToken);
}
[HttpDelete("{id:guid}/courses/{courseId:guid}")]
[Authorize(Roles = ManageRoles)]
public async Task<ActionResult> RemoveCourse(
Guid id,
Guid courseId,
CancellationToken cancellationToken)
{
var item = await db.CourseGroupCourses.FirstOrDefaultAsync(
x => x.CourseGroupId == id && x.CourseId == courseId,
cancellationToken);
if (item is null) return NotFound();
db.CourseGroupCourses.Remove(item);
return await SaveNoContentAsync(cancellationToken);
}
private async Task<ActionResult> SaveCreatedAsync(Guid id, CancellationToken cancellationToken)
{
try
{
await db.SaveChangesAsync(cancellationToken);
return Created(string.Empty, new { id });
}
catch (DbUpdateException)
{
return ConflictProblem("课程组编码或组内课程重复。");
}
}
private async Task<ActionResult> SaveNoContentAsync(CancellationToken cancellationToken)
{
try
{
await db.SaveChangesAsync(cancellationToken);
return NoContent();
}
catch (DbUpdateException)
{
return ConflictProblem("课程组编码或组内课程重复。");
}
}
private ActionResult ConflictProblem(string detail) => Conflict(new ProblemDetails
{
Title = "无法完成操作", Detail = detail, Status = StatusCodes.Status409Conflict
});
private static string? Normalize(string? value) =>
string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
public sealed record CourseGroupRequest(
[Required, MaxLength(30)] string Code,
[Required, MaxLength(100)] string Name,
[MaxLength(500)] string? Description);
public sealed record CourseGroupCourseRequest(Guid CourseId);
@@ -1011,7 +1011,11 @@ public sealed class CourseSelectionsController(
x.TeachingTask!.Status == TeachingTaskStatus.Published &&
(x.IsOpenToAll ||
x.TeachingTask.Classes.Any(item =>
item.AdministrativeClassId == student.AdministrativeClassId)))
item.AdministrativeClassId == student.AdministrativeClassId) ||
x.Enrollments.Any(item =>
item.StudentId == student.Id &&
(item.Status == CourseEnrollmentStatus.Enrolled ||
item.Status == CourseEnrollmentStatus.Waitlisted))))
.OrderBy(x => x.TeachingTask!.Course!.Code)
.Select(x => new StudentOfferingDto(
x.Id,
@@ -432,6 +432,48 @@ public sealed class CurriculumPlansController(
return await SaveCreatedAsync(item.Id, cancellationToken);
}
[HttpPost("{planId:guid}/modules/{moduleId:guid}/course-groups/{groupId:guid}")]
public async Task<ActionResult> AddCourseGroup(
Guid planId,
Guid moduleId,
Guid groupId,
CurriculumCourseGroupImportRequest request,
CancellationToken cancellationToken)
{
var plan = await ModifiablePlanAsync(planId, cancellationToken);
if (plan is null) return NotFound();
if (request.RecommendedSemester > plan.Major!.SchoolingYears * 2)
return ValidationProblem("建议学期超出了该专业学制。");
if (!await db.CurriculumModules.AnyAsync(
x => x.Id == moduleId && x.CurriculumPlanId == planId,
cancellationToken))
return NotFound();
var courseIds = await db.CourseGroupCourses.AsNoTracking()
.Where(x => x.CourseGroupId == groupId && x.Course!.IsEnabled)
.Select(x => x.CourseId)
.ToListAsync(cancellationToken);
if (courseIds.Count == 0)
return ValidationProblem("课程组不存在,或其中没有可用课程。");
var existingCourseIds = await db.CurriculumCourses.AsNoTracking()
.Where(x => x.CurriculumModule!.CurriculumPlanId == planId &&
courseIds.Contains(x.CourseId))
.Select(x => x.CourseId)
.ToListAsync(cancellationToken);
if (existingCourseIds.Count > 0)
return ConflictProblem("课程组中有课程已存在于该培养方案,请先移除重复课程后再导入。");
db.CurriculumCourses.AddRange(courseIds.Select(courseId => new CurriculumCourse
{
CurriculumModuleId = moduleId,
CourseId = courseId,
RecommendedSemester = request.RecommendedSemester,
Type = request.Type,
Notes = Normalize(request.Notes)
}));
return await SaveNoContentAsync(cancellationToken);
}
[HttpPut("{planId:guid}/modules/{moduleId:guid}/courses/{itemId:guid}")]
public async Task<ActionResult> UpdateCourse(
Guid planId,
@@ -586,3 +628,8 @@ public sealed record CurriculumCourseRequest(
[Range(1, 20)] int RecommendedSemester,
CurriculumCourseType Type,
[MaxLength(500)] string? Notes);
public sealed record CurriculumCourseGroupImportRequest(
[Range(1, 20)] int RecommendedSemester,
CurriculumCourseType Type,
[MaxLength(500)] string? Notes);
@@ -1,4 +1,5 @@
using System.ComponentModel.DataAnnotations;
using System.Data;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Auth;
@@ -38,8 +39,15 @@ public sealed class ExperimentGradesController(
public async Task<ActionResult> GetManagement(
Guid? academicTermId,
ExperimentGradeSheetStatus? status,
CancellationToken cancellationToken)
Guid? collegeId = null,
string? keyword = null,
int page = 1,
int pageSize = 20,
CancellationToken cancellationToken = default)
{
page = Math.Max(1, page);
pageSize = Math.Clamp(pageSize, 10, 50);
keyword = Normalize(keyword);
var source = ScopedProjects().AsNoTracking()
.Where(x =>
x.Status == ExperimentProjectStatus.Published ||
@@ -51,11 +59,28 @@ public sealed class ExperimentGradesController(
source = source.Where(x =>
x.GradeSheet != null &&
x.GradeSheet.Status == status.Value);
if (collegeId.HasValue)
source = source.Where(x =>
x.TeachingTask!.Course!.CollegeId == collegeId.Value);
if (keyword is not null)
source = source.Where(x =>
x.Code.Contains(keyword) ||
x.Name.Contains(keyword) ||
x.TeachingTask!.TaskNumber.Contains(keyword) ||
x.TeachingTask.Name.Contains(keyword) ||
x.TeachingTask.Course!.Code.Contains(keyword) ||
x.TeachingTask.Course.Name.Contains(keyword) ||
x.TeachingTask.Teachers.Any(item =>
item.Teacher!.TeacherNumber.Contains(keyword) ||
item.Teacher.Name.Contains(keyword)));
return Ok(await source
var total = await source.CountAsync(cancellationToken);
var items = await source
.OrderByDescending(x => x.TeachingTask!.AcademicTerm!.StartDate)
.ThenBy(x => x.TeachingTask!.TaskNumber)
.ThenBy(x => x.Code)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.Select(x => new
{
x.Id,
@@ -96,7 +121,14 @@ public sealed class ExperimentGradesController(
x.GradeSheet.PublishedAt
}
})
.ToListAsync(cancellationToken));
.ToListAsync(cancellationToken);
return Ok(new
{
Items = items,
Total = total,
Page = page,
PageSize = pageSize
});
}
[HttpGet("mine")]
@@ -107,7 +139,7 @@ public sealed class ExperimentGradesController(
if (student is null)
return ConflictProblem("当前账号未关联有效学生档案。");
return Ok(await db.ExperimentGradeRecords.AsNoTracking()
var results = await db.ExperimentGradeRecords.AsNoTracking()
.Where(x =>
x.StudentId == student.Id &&
x.ExperimentGradeSheet!.Status ==
@@ -126,12 +158,19 @@ public sealed class ExperimentGradesController(
ProjectName =
x.ExperimentGradeSheet.ExperimentProject.Name,
x.ExperimentGradeSheet.ExperimentProject.ArrangementMode,
TeachingTaskId = x.ExperimentGradeSheet.ExperimentProject
.TeachingTaskId,
AcademicTermId = x.ExperimentGradeSheet.ExperimentProject
.TeachingTask!.AcademicTermId,
TaskNumber = x.ExperimentGradeSheet.ExperimentProject
.TeachingTask.TaskNumber,
CourseCode = x.ExperimentGradeSheet.ExperimentProject
.TeachingTask!.Course!.Code,
CourseName = x.ExperimentGradeSheet.ExperimentProject
.TeachingTask.Course.Name,
TermName = x.ExperimentGradeSheet.ExperimentProject
.TeachingTask.AcademicTerm!.Name,
x.ExperimentGradeSheet.ContributionWeight,
x.ExperimentGradeSheet.PassScore,
x.ParticipationStatus,
x.TotalScore,
@@ -156,7 +195,40 @@ public sealed class ExperimentGradesController(
}),
x.ExperimentGradeSheet.PublishedAt
})
.ToListAsync(cancellationToken));
.ToListAsync(cancellationToken);
var taskIds = results.Select(x => x.TeachingTaskId).Distinct().ToArray();
var aggregates = await db.ExperimentCourseGrades.AsNoTracking()
.Where(x =>
x.StudentId == student.Id &&
taskIds.Contains(x.TeachingTaskId))
.ToDictionaryAsync(x => x.TeachingTaskId, cancellationToken);
var courses = results
.GroupBy(x => x.TeachingTaskId)
.Select(group =>
{
var first = group.First();
aggregates.TryGetValue(group.Key, out var aggregate);
return new
{
TeachingTaskId = group.Key,
first.AcademicTermId,
first.TermName,
first.TaskNumber,
first.CourseCode,
first.CourseName,
ExperimentCourseScore = aggregate?.WeightedAverageScore,
PublishedProjectCount =
aggregate?.PublishedProjectCount ?? group.Count(),
TotalWeight = aggregate?.TotalWeight ??
group.Sum(x => x.ContributionWeight),
RefreshedAt = aggregate?.RefreshedAt,
Projects = group.OrderBy(x => x.ProjectCode).ToList()
};
})
.OrderByDescending(x => x.Projects.Max(project => project.PublishedAt))
.ThenBy(x => x.CourseCode)
.ToList();
return Ok(courses);
}
[HttpPost("sheets")]
@@ -713,7 +785,15 @@ public sealed class ExperimentGradesController(
sheet.Status = ExperimentGradeSheetStatus.Published;
sheet.PublishedAt = DateTime.UtcNow;
await db.ExecuteInRetriableTransactionAsync(async transaction =>
{
await db.SaveChangesAsync(cancellationToken);
await ExperimentGradeAggregationService.RefreshTeachingTaskAsync(
db,
sheet.ExperimentProject!.TeachingTaskId,
cancellationToken);
await transaction.CommitAsync(cancellationToken);
}, cancellationToken, IsolationLevel.Serializable);
var userIds = await db.ExperimentGradeRecords
.Where(x => x.ExperimentGradeSheetId == sheet.Id)
.Select(x => x.Student!.UserId)
@@ -747,6 +827,10 @@ public sealed class ExperimentGradesController(
.Include(x => x.ExperimentProject)
.ThenInclude(x => x!.TeachingTask)
.ThenInclude(x => x!.Course)
.Include(x => x.ExperimentProject)
.ThenInclude(x => x!.TeachingTask)
.ThenInclude(x => x!.Teachers)
.ThenInclude(x => x.Teacher)
.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
}
@@ -1,7 +1,9 @@
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Text.Json;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Domain.System;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Experiments;
using Jiaowu.Api.Infrastructure.Persistence;
@@ -31,12 +33,21 @@ public sealed class ExperimentsController(
[Authorize(Roles = Managers)]
public async Task<ActionResult> GetOptions(
Guid? academicTermId,
Guid? offeringCollegeId,
string? courseKeyword,
CancellationToken cancellationToken)
{
var tasks = AccessibleTeachingTasks().AsNoTracking()
.Where(x => x.Status == TeachingTaskStatus.Published);
if (academicTermId.HasValue)
tasks = tasks.Where(x => x.AcademicTermId == academicTermId);
if (offeringCollegeId.HasValue)
tasks = tasks.Where(x => x.Course!.CollegeId == offeringCollegeId);
var normalizedCourseKeyword = Normalize(courseKeyword);
if (normalizedCourseKeyword is not null)
tasks = tasks.Where(x =>
x.Course!.Code.Contains(normalizedCourseKeyword) ||
x.Course.Name.Contains(normalizedCourseKeyword));
var periods = db.ScheduleTimeSlots.AsNoTracking()
.Where(x => x.IsEnabled);
@@ -90,6 +101,52 @@ public sealed class ExperimentsController(
.OrderBy(item => item.AdministrativeClass!.Code)
.Select(item => item.AdministrativeClass!.Name)
})
.Take(200)
.ToListAsync(cancellationToken),
Colleges = await AccessibleTeachingTasks().AsNoTracking()
.Where(x => !academicTermId.HasValue || x.AcademicTermId == academicTermId.Value)
.Select(x => new { x.Course!.CollegeId, CollegeName = x.Course.College!.Name })
.Distinct()
.OrderBy(x => x.CollegeName)
.ToListAsync(cancellationToken),
ScheduleEntries = await db.ScheduleEntries.AsNoTracking()
.Where(x => x.SchedulePlan!.Status == SchedulePlanStatus.Published &&
x.Kind == ScheduleEntryKind.Experiment &&
x.ClassroomId.HasValue &&
AccessibleTeachingTasks().Select(task => task.Id)
.Contains(x.TeachingTaskId))
.Where(x => !academicTermId.HasValue ||
x.SchedulePlan!.AcademicTermId == academicTermId.Value)
.Where(x => !offeringCollegeId.HasValue ||
x.TeachingTask!.Course!.CollegeId == offeringCollegeId.Value)
.Where(x => normalizedCourseKeyword == null ||
x.TeachingTask!.Course!.Code.Contains(normalizedCourseKeyword) ||
x.TeachingTask.Course.Name.Contains(normalizedCourseKeyword))
.OrderBy(x => x.TeachingTask!.Course!.Code)
.ThenBy(x => x.TeachingTask!.TaskNumber)
.ThenBy(x => x.DayOfWeek)
.ThenBy(x => x.StartPeriod)
.Select(x => new
{
x.Id,
x.TeachingTaskId,
TaskNumber = x.TeachingTask!.TaskNumber,
CourseCode = x.TeachingTask.Course!.Code,
CourseName = x.TeachingTask.Course.Name,
x.DayOfWeek,
x.StartPeriod,
x.PeriodCount,
x.StartWeek,
x.EndWeek,
x.WeekPattern,
ClassNames = x.TeachingTask!.Classes
.OrderBy(item => item.AdministrativeClass!.Code)
.Select(item => item.AdministrativeClass!.Name),
ClassroomName = x.Classroom!.Name,
BuildingName = x.Classroom.Building!.Name,
CampusName = x.Classroom.Building.Campus!.Name
})
.Take(500)
.ToListAsync(cancellationToken),
Classrooms = await db.Classrooms.AsNoTracking()
.Where(x => x.IsEnabled)
@@ -103,6 +160,7 @@ public sealed class ExperimentsController(
BuildingName = x.Building!.Name,
CampusName = x.Building.Campus!.Name,
x.Capacity
,x.TeachingVenueNature
})
.ToListAsync(cancellationToken),
Periods = periodItems
@@ -115,7 +173,14 @@ public sealed class ExperimentsController(
Guid? academicTermId,
ExperimentArrangementMode? arrangementMode,
ExperimentProjectStatus? status,
CancellationToken cancellationToken)
Guid? offeringCollegeId,
string? courseKeyword,
string? classKeyword,
string? teacherKeyword,
string? taskKeyword,
CancellationToken cancellationToken,
int page = 1,
int pageSize = 20)
{
var source = ScopedProjects().AsNoTracking();
if (academicTermId.HasValue)
@@ -127,7 +192,47 @@ public sealed class ExperimentsController(
if (status.HasValue)
source = source.Where(x => x.Status == status);
return Ok(await source
var normalizedCourseKeyword = Normalize(courseKeyword);
var normalizedClassKeyword = Normalize(classKeyword);
var normalizedTeacherKeyword = Normalize(teacherKeyword);
var normalizedTaskKeyword = Normalize(taskKeyword);
var taskSource = AccessibleTeachingTasks().AsNoTracking()
.Where(task => source.Select(project => project.TeachingTaskId).Contains(task.Id));
if (academicTermId.HasValue)
taskSource = taskSource.Where(x => x.AcademicTermId == academicTermId);
if (offeringCollegeId.HasValue)
taskSource = taskSource.Where(x => x.Course!.CollegeId == offeringCollegeId);
if (normalizedCourseKeyword is not null)
taskSource = taskSource.Where(x =>
x.Course!.Code.Contains(normalizedCourseKeyword) ||
x.Course.Name.Contains(normalizedCourseKeyword));
if (normalizedClassKeyword is not null)
taskSource = taskSource.Where(x => x.Classes.Any(item =>
item.AdministrativeClass!.Code.Contains(normalizedClassKeyword) ||
item.AdministrativeClass.Name.Contains(normalizedClassKeyword)));
if (normalizedTeacherKeyword is not null)
taskSource = taskSource.Where(x => x.Teachers.Any(item =>
item.Teacher!.TeacherNumber.Contains(normalizedTeacherKeyword) ||
item.Teacher.Name.Contains(normalizedTeacherKeyword)));
if (normalizedTaskKeyword is not null)
taskSource = taskSource.Where(x =>
x.TaskNumber.Contains(normalizedTaskKeyword) ||
x.Name.Contains(normalizedTaskKeyword));
page = Math.Max(1, page);
pageSize = Math.Clamp(pageSize, 10, 100);
var total = await taskSource.CountAsync(cancellationToken);
var taskIds = await taskSource
.OrderByDescending(x => x.AcademicTerm!.StartDate)
.ThenBy(x => x.Course!.Code)
.ThenBy(x => x.TaskNumber)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.Select(x => x.Id)
.ToListAsync(cancellationToken);
var items = await source
.Where(x => taskIds.Contains(x.TeachingTaskId))
.OrderByDescending(x => x.Status == ExperimentProjectStatus.Published)
.ThenBy(x => x.StartDate)
.ThenBy(x => x.Code)
@@ -135,6 +240,8 @@ public sealed class ExperimentsController(
{
x.Id,
x.TeachingTaskId,
x.ScheduleEntryId,
x.ScheduleWeek,
x.Code,
x.Name,
x.ArrangementMode,
@@ -157,6 +264,19 @@ public sealed class ExperimentsController(
ClassNames = x.TeachingTask.Classes
.OrderBy(item => item.AdministrativeClass!.Code)
.Select(item => item.AdministrativeClass!.Name),
ScheduleEntry = x.ScheduleEntryId == null ? null : new
{
x.ScheduleEntry!.DayOfWeek,
x.ScheduleEntry.StartPeriod,
x.ScheduleEntry.PeriodCount,
x.ScheduleEntry.StartWeek,
x.ScheduleEntry.EndWeek,
x.ScheduleEntry.WeekPattern,
ProjectWeek = x.ScheduleWeek,
ClassroomName = x.ScheduleEntry.Classroom!.Name,
BuildingName = x.ScheduleEntry.Classroom.Building!.Name,
CampusName = x.ScheduleEntry.Classroom.Building.Campus!.Name
},
Sessions = x.Sessions
.OrderBy(item => item.SessionDate)
.ThenBy(item => item.StartPeriod)
@@ -176,7 +296,9 @@ public sealed class ExperimentsController(
CampusName = item.Classroom.Building.Campus!.Name
})
})
.ToListAsync(cancellationToken));
.ToListAsync(cancellationToken);
return Ok(new { Items = items, Total = total, Page = page, PageSize = pageSize });
}
[HttpGet("student")]
@@ -209,6 +331,8 @@ public sealed class ExperimentsController(
x.Code,
x.Name,
x.ArrangementMode,
x.ScheduleEntryId,
x.ScheduleWeek,
x.Description,
x.Requirements,
x.StartDate,
@@ -222,6 +346,19 @@ public sealed class ExperimentsController(
TeacherNames = x.TeachingTask.Teachers
.OrderByDescending(item => item.IsPrimary)
.Select(item => item.Teacher!.Name),
ScheduleEntry = x.ScheduleEntryId == null ? null : new
{
x.ScheduleEntry!.DayOfWeek,
x.ScheduleEntry.StartPeriod,
x.ScheduleEntry.PeriodCount,
x.ScheduleEntry.StartWeek,
x.ScheduleEntry.EndWeek,
x.ScheduleEntry.WeekPattern,
ProjectWeek = x.ScheduleWeek,
ClassroomName = x.ScheduleEntry.Classroom!.Name,
BuildingName = x.ScheduleEntry.Classroom.Building!.Name,
CampusName = x.ScheduleEntry.Classroom.Building.Campus!.Name
},
Sessions = x.Sessions
.Where(item => item.Status == ExperimentSessionStatus.Scheduled)
.OrderBy(item => item.SessionDate)
@@ -272,6 +409,9 @@ public sealed class ExperimentsController(
var problem = ValidateProjectRequest(request, task.AcademicTerm!);
if (problem is not null) return ValidationProblem(problem);
var scheduleEntry = await ValidateScheduleEntryAsync(
request, task.Id, cancellationToken);
if (scheduleEntry.Problem is not null) return ValidationProblem(scheduleEntry.Problem);
var code = request.Code.Trim();
if (await db.ExperimentProjects.AnyAsync(x =>
@@ -283,6 +423,7 @@ public sealed class ExperimentsController(
var project = new ExperimentProject
{
TeachingTaskId = request.TeachingTaskId,
ScheduleEntryId = scheduleEntry.Entry?.Id,
Code = code,
Name = request.Name.Trim(),
ArrangementMode = request.ArrangementMode,
@@ -313,31 +454,80 @@ public sealed class ExperimentsController(
var tasks = await AccessibleTeachingTasks().AsNoTracking()
.Include(x => x.AcademicTerm)
.Where(x =>
taskIds.Contains(x.Id) &&
x.Status == TeachingTaskStatus.Published)
.WhereIn(taskIds, x => x.Id)
.Where(x => x.Status == TeachingTaskStatus.Published)
.OrderBy(x => x.TaskNumber)
.ToListAsync(cancellationToken);
if (tasks.Count != taskIds.Count)
return ValidationProblem("部分教学任务不存在、未发布或不在当前管理范围内。");
var first = tasks[0];
if (tasks.Any(x =>
if (request.ArrangementMode == ExperimentArrangementMode.SelfScheduled && tasks.Any(x =>
x.AcademicTermId != first.AcademicTermId ||
x.CourseId != first.CourseId))
return ValidationProblem("批量设置仅支持同一学期、同一课程的教学任务。");
var code = request.Code.Trim();
if (request.ArrangementMode == ExperimentArrangementMode.SelfScheduled)
{
var conflictingTaskNumbers = await db.ExperimentProjects.AsNoTracking()
.Where(x =>
taskIds.Contains(x.TeachingTaskId) &&
x.Code == code)
.WhereIn(taskIds, x => x.TeachingTaskId)
.Where(x => x.Code == code)
.Select(x => x.TeachingTask!.TaskNumber)
.OrderBy(x => x)
.ToListAsync(cancellationToken);
if (conflictingTaskNumbers.Count > 0)
return ConflictProblem(
$"以下教学任务已存在实验项目编码 {code}{string.Join("", conflictingTaskNumbers)}。");
}
var scheduledEntries = request.ArrangementMode == ExperimentArrangementMode.Centralized
? await db.ScheduleEntries.AsNoTracking()
.Where(x => x.SchedulePlan!.Status == SchedulePlanStatus.Published &&
x.Kind == ScheduleEntryKind.Experiment &&
x.ClassroomId.HasValue &&
taskIds.Contains(x.TeachingTaskId))
.OrderBy(x => x.TeachingTaskId)
.ThenBy(x => x.DayOfWeek)
.ThenBy(x => x.StartPeriod)
.ToListAsync(cancellationToken)
: [];
if (request.ArrangementMode == ExperimentArrangementMode.Centralized &&
tasks.Any(task => scheduledEntries.All(entry => entry.TeachingTaskId != task.Id)))
return ValidationProblem("所选教学班中包含未排入实验室的已发布实验课,请先完成课表安排。");
var scheduledOccurrences = scheduledEntries
.SelectMany(entry => Enumerable.Range(
entry.StartWeek,
entry.EndWeek - entry.StartWeek + 1)
.Where(week => FreeClassroomRules.MatchesWeek(entry.WeekPattern, week))
.Select(week => (Entry: entry, Week: week)))
.ToList();
var legacyProjects = scheduledEntries.Count > 0
? await db.ExperimentProjects
.Where(x => x.Code == code && x.ScheduleEntryId.HasValue &&
x.ScheduleWeek == null &&
taskIds.Contains(x.TeachingTaskId))
.ToListAsync(cancellationToken)
: [];
if (legacyProjects.Any(x => x.Status != ExperimentProjectStatus.Draft))
return ConflictProblem("存在旧版已发布实验项目,不能自动拆分为每周项目;请先关闭后重新设置。");
if (scheduledOccurrences.Count > 0)
{
var entryIds = scheduledOccurrences.Select(x => x.Entry.Id).Distinct().ToList();
var existingOccurrences = await db.ExperimentProjects.AsNoTracking()
.Where(x => x.Code == code && x.ScheduleEntryId.HasValue &&
x.ScheduleWeek.HasValue && entryIds.Contains(x.ScheduleEntryId.Value))
.Select(x => new { ScheduleEntryId = x.ScheduleEntryId!.Value, ScheduleWeek = x.ScheduleWeek!.Value })
.ToListAsync(cancellationToken);
var existingKeys = existingOccurrences
.Select(x => (x.ScheduleEntryId, x.ScheduleWeek))
.ToHashSet();
if (scheduledOccurrences.Any(x => existingKeys.Contains((x.Entry.Id, x.Week))))
return ConflictProblem("所选实验课中已存在相同实验项目编码和周次,不能重复生成。");
}
var projects = new List<ExperimentProject>(tasks.Count);
foreach (var task in tasks)
@@ -346,9 +536,33 @@ public sealed class ExperimentsController(
var problem = ValidateProjectRequest(item, task.AcademicTerm!);
if (problem is not null) return ValidationProblem(problem);
IEnumerable<(ScheduleEntry? Entry, int? Week)> taskOccurrences =
request.ArrangementMode == ExperimentArrangementMode.Centralized
? scheduledOccurrences
.Where(item => item.Entry.TeachingTaskId == task.Id)
.Select(item => ((ScheduleEntry?)item.Entry, (int?)item.Week))
: [(null, null)];
foreach (var occurrence in taskOccurrences)
{
var scheduleEntry = occurrence.Entry;
var legacy = scheduleEntry is null ? null : legacyProjects
.SingleOrDefault(x => x.ScheduleEntryId == scheduleEntry.Id);
if (legacy is not null)
{
var firstWeek = scheduledOccurrences
.Where(item => item.Entry.Id == scheduleEntry!.Id)
.Min(item => item.Week);
if (occurrence.Week == firstWeek)
{
legacy.ScheduleWeek = occurrence.Week;
continue;
}
}
projects.Add(new ExperimentProject
{
TeachingTaskId = task.Id,
ScheduleEntryId = occurrence.Entry?.Id,
ScheduleWeek = occurrence.Week,
Code = code,
Name = request.Name.Trim(),
ArrangementMode = request.ArrangementMode,
@@ -358,6 +572,7 @@ public sealed class ExperimentsController(
EndDate = request.EndDate
});
}
}
db.ExperimentProjects.AddRange(projects);
await db.SaveChangesAsync(cancellationToken);
@@ -389,6 +604,9 @@ public sealed class ExperimentsController(
request,
project.TeachingTask!.AcademicTerm!);
if (problem is not null) return ValidationProblem(problem);
var scheduleEntry = await ValidateScheduleEntryAsync(
request, project.TeachingTaskId, cancellationToken);
if (scheduleEntry.Problem is not null) return ValidationProblem(scheduleEntry.Problem);
var code = request.Code.Trim();
if (await db.ExperimentProjects.AnyAsync(x =>
@@ -401,6 +619,7 @@ public sealed class ExperimentsController(
project.Code = code;
project.Name = request.Name.Trim();
project.ArrangementMode = request.ArrangementMode;
project.ScheduleEntryId = scheduleEntry.Entry?.Id;
project.Description = Normalize(request.Description);
project.Requirements = Normalize(request.Requirements);
project.StartDate = request.StartDate;
@@ -426,6 +645,26 @@ public sealed class ExperimentsController(
return NoContent();
}
[HttpDelete("batch")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> DeleteProjects(
ExperimentProjectBulkRequest request,
CancellationToken cancellationToken)
{
var ids = ValidateBulkProjectIds(request.ProjectIds);
if (ids is null) return ValidationProblem("请选择 1 至 100 个实验项目。");
var projects = await ScopedProjects()
.Where(x => ids.Contains(x.Id))
.ToListAsync(cancellationToken);
if (projects.Count != ids.Count) return NotFound();
if (projects.Any(x => x.Status != ExperimentProjectStatus.Draft))
return ConflictProblem("批量删除只能包含草稿实验项目。");
db.ExperimentProjects.RemoveRange(projects);
await db.SaveChangesAsync(cancellationToken);
return NoContent();
}
[HttpPost("{id:guid}/publish")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> PublishProject(
@@ -440,9 +679,14 @@ public sealed class ExperimentsController(
if (project is null) return NotFound();
if (project.Status != ExperimentProjectStatus.Draft)
return ConflictProblem("只有草稿实验项目可以发布。");
if (!project.Sessions.Any(x =>
x.Status == ExperimentSessionStatus.Scheduled))
return ConflictProblem("请至少安排一个有效实验场次后再发布。");
var hasSchedule = project.ArrangementMode == ExperimentArrangementMode.Centralized
? project.ScheduleEntryId.HasValue || project.Sessions.Any(x =>
x.Status == ExperimentSessionStatus.Scheduled)
: project.Sessions.Any(x => x.Status == ExperimentSessionStatus.Scheduled);
if (!hasSchedule)
return ConflictProblem(project.ArrangementMode == ExperimentArrangementMode.Centralized
? "请先绑定已发布课表中的实验课后再发布。"
: "请至少安排一个有效实验场次后再发布。");
if (project.Sessions.Any(x =>
x.Status == ExperimentSessionStatus.Scheduled &&
(x.SessionDate < project.StartDate ||
@@ -452,31 +696,47 @@ public sealed class ExperimentsController(
project.Status = ExperimentProjectStatus.Published;
project.PublishedAt = DateTime.UtcNow;
await db.SaveChangesAsync(cancellationToken);
var userIds = await TeachingTaskRosterQuery
.ForTask(db, project.TeachingTaskId)
.Where(x => x.UserId.HasValue)
.Select(x => x.UserId!.Value)
.Distinct()
.ToListAsync(cancellationToken);
if (userIds.Count > 0)
{
var mode = project.ArrangementMode ==
ExperimentArrangementMode.Centralized
? "集中安排"
: "自行预约";
await NotificationService.SendToUserIdsAsync(
db,
userIds,
"实验项目已发布",
$"《{project.TeachingTask!.Course!.Name}》已发布“{project.Name}”({mode}),请查看实验安排。",
"/experiments",
cancellationToken,
NotificationCategory.Schedule);
}
await NotifyProjectPublishedAsync(project, cancellationToken);
return NoContent();
}
[HttpPost("batch/publish")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> PublishProjects(
ExperimentProjectBulkRequest request,
CancellationToken cancellationToken)
{
var ids = ValidateBulkProjectIds(request.ProjectIds);
if (ids is null) return ValidationProblem("请选择 1 至 100 个实验项目。");
if (await ScopedProjects().CountAsync(x => ids.Contains(x.Id), cancellationToken) != ids.Count)
return NotFound();
var userId = currentUserDataScope.Current.UserId;
var job = new ExamPublishJob
{
Kind = ExamPublishJobKind.ExperimentProjects,
PlanId = ids[0],
RequestedByUserId = userId == Guid.Empty ? null : userId,
ProjectIdsJson = JsonSerializer.Serialize(ids),
CurrentStep = "等待后台校验"
};
db.ExamPublishJobs.Add(job);
db.BackgroundJobOutboxMessages.Add(BackgroundJobOutboxMessage.Create(
BackgroundJobKind.ExamPublish, job.Id));
await db.SaveChangesAsync(cancellationToken);
return Accepted(new { JobId = job.Id, Status = job.Status, Message = "实验项目发布任务已提交。" });
}
[HttpGet("batch/publish-jobs/{jobId:guid}")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> GetPublishJob(Guid jobId, CancellationToken cancellationToken)
{
var job = await db.ExamPublishJobs.AsNoTracking().FirstOrDefaultAsync(x =>
x.Id == jobId && x.Kind == ExamPublishJobKind.ExperimentProjects,
cancellationToken);
if (job is null) return NotFound();
return Ok(new { job.Id, job.Status, job.CurrentStep, job.ErrorMessage, job.StartedAt, job.CompletedAt });
}
[HttpPost("{id:guid}/close")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> CloseProject(
@@ -508,6 +768,8 @@ public sealed class ExperimentsController(
if (project is null) return NotFound();
if (project.Status == ExperimentProjectStatus.Closed)
return ConflictProblem("已关闭实验项目不能再增加场次。");
if (project.ArrangementMode == ExperimentArrangementMode.Centralized)
return ConflictProblem("集中安排的实验项目直接使用已发布课表中的实验课,不能在此重复排时派地点。");
var problem = await ValidateSessionAsync(
project,
@@ -576,7 +838,7 @@ public sealed class ExperimentsController(
var projects = await ScopedProjects()
.Include(x => x.TeachingTask)
.ThenInclude(x => x!.AcademicTerm)
.Where(x => projectIds.Contains(x.Id))
.WhereIn(projectIds, x => x.Id)
.ToDictionaryAsync(x => x.Id, cancellationToken);
if (projects.Count != projectIds.Count)
return ValidationProblem(
@@ -590,6 +852,9 @@ public sealed class ExperimentsController(
if (project.Status == ExperimentProjectStatus.Closed)
return ConflictProblem(
$"实验项目“{project.Name}”已关闭,不能再增加场次。");
if (project.ArrangementMode == ExperimentArrangementMode.Centralized)
return ConflictProblem(
$"实验项目“{project.Name}”为集中安排,请直接使用已发布课表中的实验课。");
var sessionRequest = item.ToSessionRequest();
var problem = await ValidateSessionAsync(
@@ -932,6 +1197,8 @@ public sealed class ExperimentsController(
x.Id == request.ClassroomId && x.IsEnabled,
cancellationToken);
if (classroom is null) return "实验教室不存在或已停用。";
if (!TeachingVenueNatureRules.SupportsExperiment(classroom.TeachingVenueNature))
return "所选场地未标注实验教学性质。";
if (request.Capacity > classroom.Capacity)
return $"场次容量不能超过教室容量 {classroom.Capacity} 人。";
if (project.ArrangementMode ==
@@ -1157,6 +1424,31 @@ public sealed class ExperimentsController(
.Distinct()
.ToListAsync(cancellationToken);
private async Task NotifyProjectPublishedAsync(
ExperimentProject project,
CancellationToken cancellationToken)
{
var userIds = await RosterUserIdsAsync(project.TeachingTaskId, cancellationToken);
if (userIds.Count == 0) return;
var mode = project.ArrangementMode == ExperimentArrangementMode.Centralized
? "集中安排"
: "自行预约";
await NotificationService.SendToUserIdsAsync(
db,
userIds,
"实验项目已发布",
$"《{project.TeachingTask!.Course!.Name}》已发布“{project.Name}”({mode}),请查看实验安排。",
"/experiments",
cancellationToken,
NotificationCategory.Schedule);
}
private static List<Guid>? ValidateBulkProjectIds(IReadOnlyList<Guid>? projectIds)
{
var ids = projectIds?.Where(x => x != Guid.Empty).Distinct().ToList();
return ids is { Count: > 0 and <= 100 } ? ids : null;
}
private static string? ValidateProjectRequest(
ExperimentProjectRequest request,
AcademicTerm term)
@@ -1175,6 +1467,30 @@ public sealed class ExperimentsController(
return null;
}
private async Task<(ScheduleEntry? Entry, string? Problem)> ValidateScheduleEntryAsync(
ExperimentProjectRequest request,
Guid teachingTaskId,
CancellationToken cancellationToken)
{
if (request.ArrangementMode == ExperimentArrangementMode.SelfScheduled)
return request.ScheduleEntryId.HasValue
? (null, "自行安排的实验项目不能绑定课表实验课。")
: (null, null);
if (!request.ScheduleEntryId.HasValue)
return (null, "集中安排的实验项目必须绑定已发布课表中的实验课。");
var entry = await db.ScheduleEntries
.Include(x => x.SchedulePlan)
.FirstOrDefaultAsync(x => x.Id == request.ScheduleEntryId, cancellationToken);
if (entry is null || entry.SchedulePlan!.Status != SchedulePlanStatus.Published ||
entry.Kind != ScheduleEntryKind.Experiment || !entry.ClassroomId.HasValue ||
entry.TeachingTaskId != teachingTaskId)
return (null, "只能绑定本教学任务已发布、已安排实验室的实验课。");
if (!await AccessibleTeachingTasks().AnyAsync(x => x.Id == teachingTaskId, cancellationToken))
return (null, "该教学任务不在当前管理范围内。");
return (entry, null);
}
private static string? Normalize(string? value) =>
string.IsNullOrWhiteSpace(value) ? null : value.Trim();
@@ -1195,7 +1511,8 @@ public sealed record ExperimentProjectRequest(
[MaxLength(1000)] string? Description,
[MaxLength(1000)] string? Requirements,
DateOnly StartDate,
DateOnly EndDate);
DateOnly EndDate,
Guid? ScheduleEntryId = null);
public sealed record ExperimentProjectBatchRequest(
[Required] IReadOnlyList<Guid> TeachingTaskIds,
@@ -1219,6 +1536,9 @@ public sealed record ExperimentProjectBatchRequest(
EndDate);
}
public sealed record ExperimentProjectBulkRequest(
[Required] IReadOnlyList<Guid> ProjectIds);
public sealed record ExperimentSessionRequest(
Guid ClassroomId,
DateOnly SessionDate,
@@ -0,0 +1,596 @@
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Domain.System;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Caching;
using Jiaowu.Api.Infrastructure.Grades;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Jiaowu.Api.Controllers;
[ApiController]
[Authorize(Roles = AnalyticsUsers)]
[Route("api/grade-analytics")]
public sealed class GradeAnalyticsController(
AppDbContext db,
ICurrentUserDataScope currentUserDataScope,
IAppCache? cache = null) : ControllerBase
{
private const string AnalyticsUsers =
SystemRoles.SuperAdmin + "," +
SystemRoles.AcademicAdmin + "," +
SystemRoles.CollegeAdmin + "," +
SystemRoles.Leader + "," +
SystemRoles.Teacher;
private const string ScheduleManagers =
SystemRoles.SuperAdmin + "," + SystemRoles.AcademicAdmin;
[HttpGet("refresh-schedule")]
[Authorize(Roles = ScheduleManagers)]
public async Task<ActionResult> GetRefreshSchedule(CancellationToken cancellationToken)
{
var setting = await db.CourseGradeStatisticsRefreshSettings.AsNoTracking()
.SingleOrDefaultAsync(
x => x.Key == CourseGradeStatisticsRefreshSetting.DefaultKey,
cancellationToken);
var defaults = new CourseGradeStatisticsRefreshSetting();
var enabled = setting?.IsEnabled ?? defaults.IsEnabled;
var intervalSeconds = setting?.IntervalSeconds ?? defaults.IntervalSeconds;
var batchSize = setting?.BatchSize ?? defaults.BatchSize;
var lastRunAt = setting?.LastRunAt;
return Ok(new
{
IsEnabled = enabled,
IntervalSeconds = intervalSeconds,
BatchSize = batchSize,
LastRunAt = lastRunAt,
NextRunAt = enabled && lastRunAt.HasValue
? lastRunAt.Value.AddSeconds(intervalSeconds)
: null as DateTime?
});
}
[HttpPut("refresh-schedule")]
[Authorize(Roles = ScheduleManagers)]
public async Task<ActionResult> SaveRefreshSchedule(
SaveGradeStatisticsRefreshScheduleRequest request,
CancellationToken cancellationToken)
{
if (request.IntervalSeconds is < 10 or > 86400)
return BadRequest(new ProblemDetails
{
Title = "刷新间隔应在 10 秒到 24 小时之间。",
Status = StatusCodes.Status400BadRequest
});
if (request.BatchSize is < 1 or > 5000)
return BadRequest(new ProblemDetails
{
Title = "单次刷新批量应在 1 到 5000 之间。",
Status = StatusCodes.Status400BadRequest
});
var setting = await db.CourseGradeStatisticsRefreshSettings
.SingleOrDefaultAsync(
x => x.Key == CourseGradeStatisticsRefreshSetting.DefaultKey,
cancellationToken);
if (setting is null)
{
setting = new CourseGradeStatisticsRefreshSetting();
db.CourseGradeStatisticsRefreshSettings.Add(setting);
}
setting.IsEnabled = request.IsEnabled;
setting.IntervalSeconds = request.IntervalSeconds;
setting.BatchSize = request.BatchSize;
await db.SaveChangesAsync(cancellationToken);
return NoContent();
}
[HttpGet("teaching-classes")]
public async Task<ActionResult> GetTeachingClasses(
Guid? academicTermId,
string? keyword,
int page = 1,
int pageSize = 20,
CancellationToken cancellationToken = default)
{
page = Math.Max(1, page);
pageSize = Math.Clamp(pageSize, 1, 100);
keyword = string.IsNullOrWhiteSpace(keyword) ? null : keyword.Trim();
var source = db.TeachingTaskGradeStatistics.AsNoTracking()
.Where(x => VisibleTeachingTasks().Any(task => task.Id == x.TeachingTaskId));
if (academicTermId.HasValue)
source = source.Where(x => x.AcademicTermId == academicTermId);
if (keyword is not null)
source = source.Where(x =>
x.TeachingTask!.TaskNumber.Contains(keyword) ||
x.TeachingTask.Name.Contains(keyword) ||
x.TeachingTask.Course!.Code.Contains(keyword) ||
x.TeachingTask.Course.Name.Contains(keyword));
var total = await source.CountAsync(cancellationToken);
var items = await source
.OrderByDescending(x => x.TeachingTask!.AcademicTerm!.StartDate)
.ThenBy(x => x.TeachingTask!.Course!.Code)
.ThenBy(x => x.TeachingTask!.TaskNumber)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.Select(x => new
{
x.GradeSheetId,
x.TeachingTaskId,
x.TeachingTask!.TaskNumber,
TaskName = x.TeachingTask.Name,
CourseCode = x.TeachingTask.Course!.Code,
CourseName = x.TeachingTask.Course.Name,
TermName = x.TeachingTask.AcademicTerm!.Name,
x.AcademicTermId,
TeacherNames = x.TeachingTask.Teachers
.OrderByDescending(item => item.IsPrimary)
.Select(item => item.Teacher!.Name),
ClassNames = x.TeachingTask.Classes
.Select(item => item.AdministrativeClass!.Name),
x.StudentCount,
x.AverageScore,
x.PassRate,
x.ExcellentRate,
x.CalculatedAt
})
.ToListAsync(cancellationToken);
return Ok(new { Items = items, Total = total, Page = page, PageSize = pageSize });
}
[HttpGet("teaching-classes/{gradeSheetId:guid}")]
public async Task<ActionResult> GetTeachingClassAnalysis(
Guid gradeSheetId,
CancellationToken cancellationToken)
{
var sheet = await db.GradeSheets.AsNoTracking()
.Where(x => x.Id == gradeSheetId &&
VisibleTeachingTasks().Any(task => task.Id == x.TeachingTaskId))
.Select(x => new AnalysisTarget(
x.Id,
x.TeachingTaskId,
x.TeachingTask!.CourseId,
x.TeachingTask.AcademicTermId,
x.TeachingTask.Course!.CollegeId,
x.TeachingTask.TaskNumber,
x.TeachingTask.Name,
x.TeachingTask.Course.Code,
x.TeachingTask.Course.Name,
x.TeachingTask.AcademicTerm!.Name))
.FirstOrDefaultAsync(cancellationToken);
if (sheet is null) return NotFound();
var report = await (cache ?? NoOpAppCache.Instance).GetOrCreateAsync(
AppCacheKeys.TeachingTaskGradeAnalytics(gradeSheetId),
token => BuildReportAsync(sheet, token),
AppCacheProfile.Analytics,
[AppCacheTags.CourseGradeStatistics],
cancellationToken);
return Ok(report);
}
[HttpGet("teaching-classes/{gradeSheetId:guid}/report.docx")]
public async Task<ActionResult> ExportTeachingClassAnalysisReport(
Guid gradeSheetId,
CancellationToken cancellationToken)
{
var sheet = await db.GradeSheets.AsNoTracking()
.Where(x => x.Id == gradeSheetId &&
VisibleTeachingTasks().Any(task => task.Id == x.TeachingTaskId))
.Select(x => new AnalysisTarget(
x.Id,
x.TeachingTaskId,
x.TeachingTask!.CourseId,
x.TeachingTask.AcademicTermId,
x.TeachingTask.Course!.CollegeId,
x.TeachingTask.TaskNumber,
x.TeachingTask.Name,
x.TeachingTask.Course.Code,
x.TeachingTask.Course.Name,
x.TeachingTask.AcademicTerm!.Name))
.FirstOrDefaultAsync(cancellationToken);
if (sheet is null) return NotFound();
var report = await (cache ?? NoOpAppCache.Instance).GetOrCreateAsync(
AppCacheKeys.TeachingTaskGradeAnalytics(gradeSheetId),
token => BuildReportAsync(sheet, token),
AppCacheProfile.Analytics,
[AppCacheTags.CourseGradeStatistics],
cancellationToken);
if (report.IsRefreshing || report.Summary is null)
return Conflict(new ProblemDetails
{
Title = "成绩统计尚未生成",
Detail = "请先重新计算当前教学班,待统计完成后再导出。",
Status = StatusCodes.Status409Conflict
});
var content = GradeAnalysisWordReportGenerator.Generate(report, DateTime.Now);
var fileName = $"{SanitizeFileName(report.CourseCode)}-{SanitizeFileName(report.TaskNumber)}-成绩分析报告.docx";
return File(
content,
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
fileName);
}
[HttpPost("teaching-classes/{gradeSheetId:guid}/refresh")]
public async Task<ActionResult> RefreshTeachingClassAnalysis(
Guid gradeSheetId,
CancellationToken cancellationToken)
{
var exists = await db.GradeSheets.AsNoTracking()
.AnyAsync(x => x.Id == gradeSheetId &&
VisibleTeachingTasks().Any(task => task.Id == x.TeachingTaskId),
cancellationToken);
if (!exists) return NotFound();
var job = new CourseGradeStatisticsRefreshJob { GradeSheetId = gradeSheetId };
db.CourseGradeStatisticsRefreshJobs.Add(job);
db.BackgroundJobOutboxMessages.Add(BackgroundJobOutboxMessage.Create(
BackgroundJobKind.CourseGradeStatisticsRefresh,
job.Id));
await db.SaveChangesAsync(cancellationToken);
return Accepted(new { job.Id });
}
private async Task<TeachingClassAnalysisReport> BuildReportAsync(
AnalysisTarget target,
CancellationToken cancellationToken)
{
var statistic = await db.TeachingTaskGradeStatistics.AsNoTracking()
.Where(x => x.GradeSheetId == target.GradeSheetId)
.Select(x => new TeachingClassMetrics(
x.StudentCount,
x.PassedCount,
x.ExcellentCount,
x.HighestScore,
x.AverageScore,
x.MedianScore,
x.LowestScore,
x.StandardDeviation,
x.PassRate,
x.ExcellentRate,
x.CalculatedAt,
x.ScoreBands.OrderBy(band => band.SortOrder)
.Select(band => new ScoreBand(
band.Label,
band.LowerBound,
band.UpperBound,
band.StudentCount))
.ToArray()))
.FirstOrDefaultAsync(cancellationToken);
if (statistic is null)
return new TeachingClassAnalysisReport(
true,
target.GradeSheetId,
target.TeachingTaskId,
target.TaskNumber,
target.TaskName,
target.CourseCode,
target.CourseName,
target.TermName,
null,
[],
[],
[],
null);
var peerRows = await db.TeachingTaskGradeStatistics.AsNoTracking()
.Where(x => x.CourseId == target.CourseId &&
x.AcademicTermId == target.AcademicTermId)
.OrderByDescending(x => x.AverageScore)
.Select(x => new
{
x.GradeSheetId,
x.TeachingTaskId,
x.TeachingTask!.TaskNumber,
TaskName = x.TeachingTask.Name,
TeacherNames = x.TeachingTask.Teachers
.OrderByDescending(item => item.IsPrimary)
.Select(item => item.Teacher!.Name).ToArray(),
ClassNames = x.TeachingTask.Classes
.Select(item => item.AdministrativeClass!.Name).ToArray(),
x.StudentCount,
x.HighestScore,
x.AverageScore,
x.MedianScore,
x.LowestScore,
x.StandardDeviation,
x.PassRate,
x.ExcellentRate
})
.ToListAsync(cancellationToken);
var peers = peerRows.Select(x => new TeachingClassComparison(
x.GradeSheetId,
x.TeachingTaskId,
x.TaskNumber,
x.TaskName,
string.Join("、", x.TeacherNames),
string.Join("、", x.ClassNames),
x.StudentCount,
x.HighestScore,
x.AverageScore,
x.MedianScore,
x.LowestScore,
x.StandardDeviation,
x.PassRate,
x.ExcellentRate,
x.GradeSheetId == target.GradeSheetId)).ToArray();
var classProfiles = await db.GradeRecords.AsNoTracking()
.Where(x => x.GradeSheetId == target.GradeSheetId)
.Select(x => new ClassProfile(
x.Student!.AdministrativeClassId,
x.Student.AdministrativeClass!.Name,
x.Student.AdministrativeClass.MajorId,
x.Student.AdministrativeClass.Major!.Name,
x.Student.AdministrativeClass.Major.CollegeId,
x.Student.AdministrativeClass.Major.College!.Name))
.Distinct()
.ToListAsync(cancellationToken);
var scopeStatistics = await db.CourseGradeStatistics.AsNoTracking()
.Where(x => x.CourseId == target.CourseId &&
x.AcademicTermId == target.AcademicTermId)
.ToListAsync(cancellationToken);
var benchmarks = BuildBenchmarks(classProfiles, scopeStatistics);
var selectedTeacherIds = await db.TeachingTaskTeachers.AsNoTracking()
.Where(x => x.TeachingTaskId == target.TeachingTaskId)
.Select(x => x.TeacherId)
.ToListAsync(cancellationToken);
var historicalTaskRows = await db.TeachingTaskGradeStatistics.AsNoTracking()
.Where(x => x.CourseId == target.CourseId &&
x.TeachingTask!.Teachers.Any(link =>
selectedTeacherIds.Contains(link.TeacherId)))
.Select(x => new
{
x.AcademicTermId,
TermName = x.TeachingTask!.AcademicTerm!.Name,
x.TeachingTask.AcademicTerm.StartDate,
x.StudentCount,
x.PassedCount,
x.ExcellentCount,
x.AverageScore
})
.ToListAsync(cancellationToken);
var courseHistory = await db.CourseGradeStatistics.AsNoTracking()
.Where(x => x.CourseId == target.CourseId &&
x.Scope == CourseGradeStatisticScope.University)
.Select(x => new
{
x.AcademicTermId,
TermName = db.AcademicTerms.Where(term => term.Id == x.AcademicTermId)
.Select(term => term.Name).First(),
StartDate = db.AcademicTerms.Where(term => term.Id == x.AcademicTermId)
.Select(term => term.StartDate).First(),
x.StudentCount,
x.AverageScore,
x.PassRate,
ExcellentRate = x.StudentCount == 0 ? 0m :
Math.Round((decimal)x.From90To100Count / x.StudentCount * 100m, 2)
})
.ToListAsync(cancellationToken);
var teacherByTerm = historicalTaskRows
.GroupBy(x => new { x.AcademicTermId, x.TermName, x.StartDate })
.ToDictionary(group => group.Key.AcademicTermId, group =>
{
var count = group.Sum(x => x.StudentCount);
return new HistoricalSeriesValue(
count,
count == 0 ? 0m : Math.Round(
group.Sum(x => x.AverageScore * x.StudentCount) / count, 1),
count == 0 ? 0m : Math.Round(
(decimal)group.Sum(x => x.PassedCount) / count * 100m, 2),
count == 0 ? 0m : Math.Round(
(decimal)group.Sum(x => x.ExcellentCount) / count * 100m, 2));
});
var history = courseHistory
.OrderBy(x => x.StartDate)
.Select(x => new HistoricalComparison(
x.AcademicTermId,
x.TermName,
x.StudentCount,
x.AverageScore,
x.PassRate,
x.ExcellentRate,
teacherByTerm.GetValueOrDefault(x.AcademicTermId)))
.ToArray();
var university = scopeStatistics.FirstOrDefault(x =>
x.Scope == CourseGradeStatisticScope.University);
return new TeachingClassAnalysisReport(
false,
target.GradeSheetId,
target.TeachingTaskId,
target.TaskNumber,
target.TaskName,
target.CourseCode,
target.CourseName,
target.TermName,
statistic,
peers,
benchmarks,
history,
university is null ? null : new ComparisonDelta(
Math.Round(statistic.AverageScore - university.AverageScore, 1),
Math.Round(statistic.PassRate - university.PassRate, 2),
university.AverageScore,
university.PassRate));
}
private static ScopeBenchmark[] BuildBenchmarks(
IEnumerable<ClassProfile> classProfiles,
IReadOnlyCollection<CourseGradeStatistic> statistics)
{
var profiles = classProfiles.ToArray();
var rows = new List<ScopeBenchmark>();
foreach (var profile in profiles)
AddBenchmark(rows, statistics, CourseGradeStatisticScope.AdministrativeClass,
profile.ClassId, "行政班", profile.ClassName);
foreach (var profile in profiles.GroupBy(x => x.MajorId).Select(x => x.First()))
AddBenchmark(rows, statistics, CourseGradeStatisticScope.Major,
profile.MajorId, "专业", profile.MajorName);
foreach (var profile in profiles.GroupBy(x => x.CollegeId).Select(x => x.First()))
AddBenchmark(rows, statistics, CourseGradeStatisticScope.College,
profile.CollegeId, "学院", profile.CollegeName);
AddBenchmark(rows, statistics, CourseGradeStatisticScope.University,
null, "全校", "全校同课程");
return rows.ToArray();
}
private static void AddBenchmark(
ICollection<ScopeBenchmark> target,
IEnumerable<CourseGradeStatistic> source,
CourseGradeStatisticScope scope,
Guid? entityId,
string scopeLabel,
string name)
{
var item = source.FirstOrDefault(x =>
x.Scope == scope && x.ScopeEntityId == entityId);
if (item is null || target.Any(x => x.Scope == scopeLabel && x.Name == name)) return;
target.Add(new ScopeBenchmark(
scopeLabel,
name,
item.StudentCount,
item.HighestScore,
item.AverageScore,
item.LowestScore,
item.PassRate));
}
private IQueryable<TeachingTask> VisibleTeachingTasks()
{
var scope = currentUserDataScope.Current;
var source = db.TeachingTasks.AsQueryable();
if (scope.Scope == DataScope.All) return source;
if (scope.Scope == DataScope.College)
return source.Where(x => x.Course!.CollegeId == scope.RestrictedCollegeId);
if (scope.IsInRole(SystemRoles.Teacher))
return source.Where(x =>
x.Teachers.Any(link => link.Teacher!.UserId == scope.UserId));
return source.Where(_ => false);
}
private static string SanitizeFileName(string value)
{
var invalid = Path.GetInvalidFileNameChars();
return string.Concat(value.Select(character => invalid.Contains(character) ? '_' : character));
}
private sealed record AnalysisTarget(
Guid GradeSheetId,
Guid TeachingTaskId,
Guid CourseId,
Guid AcademicTermId,
Guid CourseCollegeId,
string TaskNumber,
string TaskName,
string CourseCode,
string CourseName,
string TermName);
private sealed record ClassProfile(
Guid ClassId,
string ClassName,
Guid MajorId,
string MajorName,
Guid CollegeId,
string CollegeName);
public sealed record ScoreBand(
string Label,
decimal LowerBound,
decimal? UpperBound,
int StudentCount);
public sealed record TeachingClassMetrics(
int StudentCount,
int PassedCount,
int ExcellentCount,
decimal HighestScore,
decimal AverageScore,
decimal MedianScore,
decimal LowestScore,
decimal StandardDeviation,
decimal PassRate,
decimal ExcellentRate,
DateTime CalculatedAt,
IReadOnlyList<ScoreBand> ScoreBands);
public sealed record TeachingClassComparison(
Guid GradeSheetId,
Guid TeachingTaskId,
string TaskNumber,
string TaskName,
string TeacherNames,
string ClassNames,
int StudentCount,
decimal HighestScore,
decimal AverageScore,
decimal MedianScore,
decimal LowestScore,
decimal StandardDeviation,
decimal PassRate,
decimal ExcellentRate,
bool IsSelected);
public sealed record ScopeBenchmark(
string Scope,
string Name,
int StudentCount,
decimal HighestScore,
decimal AverageScore,
decimal LowestScore,
decimal PassRate);
public sealed record HistoricalSeriesValue(
int StudentCount,
decimal AverageScore,
decimal PassRate,
decimal ExcellentRate);
public sealed record HistoricalComparison(
Guid AcademicTermId,
string TermName,
int CourseStudentCount,
decimal CourseAverageScore,
decimal CoursePassRate,
decimal CourseExcellentRate,
HistoricalSeriesValue? Instructor);
public sealed record ComparisonDelta(
decimal AverageScoreDifference,
decimal PassRateDifference,
decimal UniversityAverageScore,
decimal UniversityPassRate);
public sealed record TeachingClassAnalysisReport(
bool IsRefreshing,
Guid GradeSheetId,
Guid TeachingTaskId,
string TaskNumber,
string TaskName,
string CourseCode,
string CourseName,
string TermName,
TeachingClassMetrics? Summary,
IReadOnlyList<TeachingClassComparison> PeerTeachingClasses,
IReadOnlyList<ScopeBenchmark> ScopeBenchmarks,
IReadOnlyList<HistoricalComparison> History,
ComparisonDelta? UniversityDelta);
}
public sealed record SaveGradeStatisticsRefreshScheduleRequest(
bool IsEnabled,
int IntervalSeconds,
int BatchSize);
+187 -6
View File
@@ -3,7 +3,9 @@ using System.Globalization;
using Jiaowu.Api.Contracts;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Domain.System;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Caching;
using Jiaowu.Api.Infrastructure.Excel;
using Jiaowu.Api.Infrastructure.Grades;
using Jiaowu.Api.Infrastructure.Persistence;
@@ -19,7 +21,8 @@ namespace Jiaowu.Api.Controllers;
[Route("api/grades")]
public sealed class GradesController(
AppDbContext db,
ICurrentUserDataScope currentUserDataScope) : ControllerBase
ICurrentUserDataScope currentUserDataScope,
IAppCache? cache = null) : ControllerBase
{
private const string SheetUsers =
SystemRoles.SuperAdmin + "," +
@@ -37,6 +40,9 @@ public sealed class GradesController(
SystemRoles.SuperAdmin + "," +
SystemRoles.AcademicAdmin;
private const string StatisticsUsers =
SheetUsers + "," + SystemRoles.Leader + "," + SystemRoles.Student;
[HttpGet("sheets")]
[Authorize(Roles = SheetUsers)]
public async Task<ActionResult> GetSheets(
@@ -145,6 +151,7 @@ public sealed class GradesController(
var task = await AccessibleTasks()
.Include(x => x.Teachers)
.ThenInclude(x => x.Teacher)
.FirstOrDefaultAsync(x => x.Id == request.TeachingTaskId, cancellationToken);
if (task is null) return NotFound();
if (task.Status is not (TeachingTaskStatus.Published or TeachingTaskStatus.Closed))
@@ -699,7 +706,7 @@ public sealed class GradesController(
var itemNames = sheet.Items.Select(i => i.Name).ToList();
var headers = new List<string> { "学号", "姓名", "班级", "平时成绩" };
headers.AddRange(itemNames);
headers.AddRange(["期末成绩", "考试状态", "备注"]);
headers.AddRange(["总分(自动计算)", "期末成绩", "考试状态", "备注"]);
var rows = sheet.Records.Select(record =>
{
@@ -716,6 +723,7 @@ public sealed class GradesController(
.FirstOrDefault(s => s.GradeItemId == item.Id)?.Score;
values.Add(score);
}
values.Add(null);
values.Add(record.FinalScore);
values.Add(record.ExamStatus == GradeExamStatus.Normal ? "正常" :
record.ExamStatus == GradeExamStatus.Absent ? "缺考" :
@@ -729,13 +737,56 @@ public sealed class GradesController(
{
"请勿修改第一行列名;学号、姓名、班级列请勿修改,用于匹配学生。",
"成绩列填写 0—100 的数值,留空表示暂未录入。",
"总分(自动计算)列由 Excel 按各部分比例自动计算,仅供填写时预览;上传时系统不会采用该列结果。",
"考试状态填写:正常、缺考、缓考 或 免修,留空默认为正常。",
$"本成绩单共 {sheet.Items.Count} 个分项:{string.Join("", itemNames)}。",
"导入后会自动重新计算总评成绩和绩点。"
};
var regularColumn = 4;
var itemColumns = Enumerable.Range(5, sheet.Items.Count).ToArray();
var totalColumn = regularColumn + itemColumns.Length + 1;
var finalColumn = totalColumn + 1;
var statusColumn = finalColumn + 1;
var weightedColumns = new List<(int Column, decimal Weight)> { (regularColumn, sheet.RegularWeight) };
weightedColumns.AddRange(sheet.Items.Select((item, index) =>
(itemColumns[index], item.Weight)));
weightedColumns.Add((finalColumn, sheet.FinalWeight));
var requiredColumns = weightedColumns.Where(x => x.Weight > 0).ToArray();
var scoreColumns = weightedColumns.Select(x => x.Column)
.Append(totalColumn)
.ToArray();
var bytes = ExcelWorkbookHelper.Create(
"成绩导入", headers, rows, instructions);
"成绩导入", headers, rows, instructions,
(worksheet, rowNumber) =>
{
var componentReferences = requiredColumns
.Select(x => $"{ColumnLetter(x.Column)}{rowNumber}")
.ToArray();
var weightedExpression = string.Join("+", weightedColumns.Select(x =>
$"{ColumnLetter(x.Column)}{rowNumber}*{x.Weight.ToString(CultureInfo.InvariantCulture)}/100"));
var statusReference = $"{ColumnLetter(statusColumn)}{rowNumber}";
var formula =
$"=IF(OR({statusReference}=\"\",{statusReference}=\"缓考\",{statusReference}=\"免修\"),\"\",IF(COUNT({string.Join(",", componentReferences)})={requiredColumns.Length},ROUND({weightedExpression},1),\"\"))";
var cell = worksheet.Cell(rowNumber, totalColumn);
cell.FormulaA1 = formula;
cell.Style.NumberFormat.Format = "0.0";
cell.Style.Font.Bold = true;
cell.Style.Fill.BackgroundColor = ClosedXML.Excel.XLColor.FromHtml("#E8F1FB");
foreach (var scoreColumn in scoreColumns)
{
var conditionalFormat = worksheet
.Range(rowNumber, scoreColumn, rowNumber, scoreColumn)
.AddConditionalFormat();
var failingScoreFormat = conditionalFormat.WhenLessThan(60);
failingScoreFormat.Fill.BackgroundColor =
ClosedXML.Excel.XLColor.FromHtml("#FDECEC");
failingScoreFormat.Font.FontColor =
ClosedXML.Excel.XLColor.FromHtml("#B42318");
}
});
var taskName = sheet.TeachingTask!.Name;
return File(bytes, ExcelWorkbookHelper.ContentType,
$"成绩导入模板-{taskName}.xlsx");
@@ -768,13 +819,15 @@ public sealed class GradesController(
var itemNames = sheet.Items.Select(i => i.Name).ToList();
var headers = new List<string> { "学号", "姓名", "班级", "平时成绩" };
headers.AddRange(itemNames);
headers.AddRange(["期末成绩", "考试状态", "备注"]);
headers.AddRange(["总分(自动计算)", "期末成绩", "考试状态", "备注"]);
IReadOnlyList<ExcelRow> rows;
try
{
rows = await ExcelWorkbookHelper.ReadAsync(
file, headers, cancellationToken);
file,
headers.Where(x => x != "总分(自动计算)").ToArray(),
cancellationToken);
}
catch (InvalidDataException exception)
{
@@ -810,7 +863,7 @@ public sealed class GradesController(
var regularScore = ParseOptionalDecimal(row, "平时成绩", 0, 100, errors);
if (errors.Count > 0 && errors[^1].Contains(row.RowNumber.ToString())) continue;
// Parse final score
// Parse final score. The formula-driven total column is intentionally ignored.
var finalScore = ParseOptionalDecimal(row, "期末成绩", 0, 100, errors);
if (errors.Count > 0 && errors[^1].Contains(row.RowNumber.ToString())) continue;
@@ -902,6 +955,7 @@ public sealed class GradesController(
.Select(x => new
{
x.Id,
GradeSheetId = x.GradeSheetId,
AcademicTermId = x.GradeSheet!.TeachingTask!.AcademicTermId,
TermName = x.GradeSheet.TeachingTask.AcademicTerm!.Name,
x.GradeSheet.TeachingTaskId,
@@ -918,6 +972,121 @@ public sealed class GradesController(
return Ok(new { Student = student, Records = records });
}
[HttpGet("sheets/{id:guid}/statistics")]
[Authorize(Roles = StatisticsUsers)]
public async Task<ActionResult> GetCourseStatistics(
Guid id,
CancellationToken cancellationToken)
{
var scope = currentUserDataScope.Current;
var sheet = await db.GradeSheets.AsNoTracking()
.Where(x => x.Id == id)
.Select(x => new
{
x.Id,
x.Status,
x.TeachingTask!.CourseId,
x.TeachingTask.AcademicTermId,
CourseName = x.TeachingTask.Course!.Name,
CourseCode = x.TeachingTask.Course.Code,
TermName = x.TeachingTask.AcademicTerm!.Name
})
.FirstOrDefaultAsync(cancellationToken);
if (sheet is null) return NotFound();
Guid? classId = null;
Guid? majorId = null;
Guid? collegeId = null;
if (scope.IsInRole(SystemRoles.Student))
{
if (sheet.Status != GradeSheetStatus.Published)
return NotFound();
var student = await db.GradeRecords.AsNoTracking()
.Where(x => x.GradeSheetId == id && x.Student!.UserId == scope.UserId)
.Select(x => new
{
x.Student!.AdministrativeClassId,
MajorId = x.Student.AdministrativeClass!.MajorId,
CollegeId = x.Student.AdministrativeClass.Major!.CollegeId
})
.FirstOrDefaultAsync(cancellationToken);
if (student is null) return Forbid();
classId = student.AdministrativeClassId;
majorId = student.MajorId;
collegeId = student.CollegeId;
}
else if (scope.Scope == DataScope.College)
{
collegeId = scope.RestrictedCollegeId;
if (collegeId == Guid.Empty || !scope.CanAccessCollege(
await db.Courses.Where(x => x.Id == sheet.CourseId)
.Select(x => x.CollegeId).FirstAsync(cancellationToken)))
return Forbid();
}
else if (scope.IsInRole(SystemRoles.Counselor))
{
var allowedClassIds = await db.AdministrativeClasses.AsNoTracking()
.Where(x => x.CounselorUserId == scope.UserId)
.Select(x => x.Id)
.ToListAsync(cancellationToken);
if (allowedClassIds.Count == 0) return Forbid();
// A counselor sees their classes plus the matching major/college
// benchmarks, never an unrelated class-level statistic.
classId = allowedClassIds.First();
majorId = await db.AdministrativeClasses.Where(x => x.Id == classId)
.Select(x => x.MajorId).FirstAsync(cancellationToken);
collegeId = await db.Majors.Where(x => x.Id == majorId)
.Select(x => x.CollegeId).FirstAsync(cancellationToken);
}
var cacheKey = AppCacheKeys.CourseGradeStatistics(id);
var statistics = await (cache ?? NoOpAppCache.Instance).GetOrCreateAsync(cacheKey, async token =>
{
var source = db.CourseGradeStatistics.AsNoTracking()
.Where(x => x.CourseId == sheet.CourseId &&
x.AcademicTermId == sheet.AcademicTermId);
return await source.Select(x => new
{
x.Scope, x.ScopeEntityId, x.StudentCount, x.PassedCount,
x.Below60Count, x.From60To69Count, x.From70To79Count,
x.From80To89Count, x.From90To100Count,
x.HighestScore, x.AverageScore, x.LowestScore, x.PassRate,
x.CalculatedAt
}).ToListAsync(token);
}, AppCacheProfile.Analytics,
[AppCacheTags.CourseGradeStatistics], cancellationToken);
object? Find(CourseGradeStatisticScope statisticScope, Guid? entityId)
{
var item = statistics.FirstOrDefault(x => x.Scope == statisticScope &&
x.ScopeEntityId == entityId);
return item is null ? null : new
{
item.Scope, item.ScopeEntityId, item.StudentCount, item.PassedCount,
item.HighestScore, item.AverageScore, item.LowestScore, item.PassRate,
item.CalculatedAt,
Distribution = new[]
{
new { Range = "059", Count = item.Below60Count },
new { Range = "6069", Count = item.From60To69Count },
new { Range = "7079", Count = item.From70To79Count },
new { Range = "8089", Count = item.From80To89Count },
new { Range = "90100", Count = item.From90To100Count }
}
};
}
return Ok(new
{
sheet.CourseName, sheet.CourseCode, sheet.TermName,
IsRefreshing = !statistics.Any(),
Class = classId.HasValue ? Find(CourseGradeStatisticScope.AdministrativeClass, classId) : null,
Major = majorId.HasValue ? Find(CourseGradeStatisticScope.Major, majorId) : null,
College = collegeId.HasValue ? Find(CourseGradeStatisticScope.College, collegeId) : null,
University = scope.Scope == DataScope.All || scope.IsInRole(SystemRoles.Student)
? Find(CourseGradeStatisticScope.University, null) : null
});
}
private IQueryable<TeachingTask> AccessibleTasks()
{
var source = db.TeachingTasks.AsQueryable();
@@ -1041,6 +1210,18 @@ public sealed class GradesController(
private static string? Normalize(string? value) =>
string.IsNullOrWhiteSpace(value) ? null : value.Trim();
private static string ColumnLetter(int column)
{
var result = string.Empty;
while (column > 0)
{
column--;
result = (char)('A' + column % 26) + result;
column /= 26;
}
return result;
}
}
public sealed record GradeSheetRequest(
@@ -737,6 +737,7 @@ public sealed class MakeupExamsController(
.Include(x => x.Enrollments)
.Include(x => x.TeachingTask!)
.ThenInclude(x => x.Teachers)
.ThenInclude(x => x.Teacher)
.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
if (session is null) return NotFound();
if (session.MakeupExamPlan!.Status != MakeupExamPlanStatus.Published)
@@ -79,6 +79,38 @@ public sealed class OperationsController(
CancellationToken cancellationToken) =>
Ok(await healthService.CheckAsync(cancellationToken));
[HttpGet("swagger")]
public async Task<ActionResult<SwaggerDocumentationSettings>> GetSwaggerSettings(
CancellationToken cancellationToken) =>
Ok(new SwaggerDocumentationSettings(await IsSwaggerEnabledAsync(cancellationToken)));
[HttpPut("swagger")]
public async Task<ActionResult<SwaggerDocumentationSettings>> UpdateSwaggerSettings(
UpdateSwaggerDocumentationSettings request,
CancellationToken cancellationToken)
{
var setting = await db.SystemFeatureSettings.SingleOrDefaultAsync(
x => x.Key == SystemFeatureKeys.SwaggerDocumentation,
cancellationToken);
if (setting is null)
{
setting = new SystemFeatureSetting
{
Key = SystemFeatureKeys.SwaggerDocumentation,
IsEnabled = request.IsEnabled
};
db.SystemFeatureSettings.Add(setting);
}
else
{
setting.IsEnabled = request.IsEnabled;
setting.UpdatedAt = DateTime.UtcNow;
}
await db.SaveChangesAsync(cancellationToken);
return Ok(new SwaggerDocumentationSettings(setting.IsEnabled));
}
[HttpGet("audit-logs")]
public async Task<ActionResult<PagedResult<AuditLogItem>>> GetAuditLogs(
[FromQuery] int page = 1,
@@ -523,6 +555,12 @@ public sealed class OperationsController(
x.CreatedAt >= from,
cancellationToken);
private async Task<bool> IsSwaggerEnabledAsync(CancellationToken cancellationToken) =>
await db.SystemFeatureSettings.AsNoTracking()
.Where(x => x.Key == SystemFeatureKeys.SwaggerDocumentation)
.Select(x => (bool?)x.IsEnabled)
.SingleOrDefaultAsync(cancellationToken) ?? false;
private ActionResult? ValidatePaging(int page, int pageSize)
{
if (page is < 1 or > 100000 || pageSize is < 1 or > 100)
@@ -604,3 +642,7 @@ public sealed record OperationsSummary(
public sealed record CreateBackupRequest([MaxLength(200)] string? Note);
public sealed record RestoreDrillRequest([Required] string Confirmation);
public sealed record SwaggerDocumentationSettings(bool IsEnabled);
public sealed record UpdateSwaggerDocumentationSettings(bool IsEnabled);
@@ -0,0 +1,238 @@
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Excel;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Jiaowu.Api.Controllers;
[ApiController]
[Authorize]
[Route("api/other-exams")]
public sealed class OtherExamsController(AppDbContext db, ICurrentUserDataScope scope) : ControllerBase
{
private const string Managers = SystemRoles.SuperAdmin + "," + SystemRoles.AcademicAdmin;
[HttpGet("batches")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> GetBatches(CancellationToken ct) => Ok(await db.OtherExamBatches
.AsNoTracking().OrderByDescending(x => x.ExamDate).ThenByDescending(x => x.CreatedAt)
.Select(x => new { x.Id, x.ExamCode, x.Name, x.Organizer, x.ExamDate, x.MetricKind, x.MaxScore, x.LevelOptions, x.Status, x.PublicationCount, x.PublishedAt, ResultCount = x.Results.Count })
.ToListAsync(ct));
[HttpPost("batches")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> CreateBatch(CreateOtherExamRequest request, CancellationToken ct)
{
var code = Normalize(request.ExamCode)?.ToUpperInvariant();
var name = Normalize(request.Name);
if (code is null || name is null) return ValidationProblem("考试编码和考试名称不能为空。");
var error = ValidateDefinition(request.MetricKind, request.MaxScore, request.LevelOptions);
if (error is not null) return ValidationProblem(error);
var definitionConflict = await db.OtherExamBatches.AnyAsync(x =>
x.ExamCode == code && (x.MetricKind != request.MetricKind || x.MaxScore != request.MaxScore || x.LevelOptions != Normalize(request.LevelOptions)), ct);
if (definitionConflict) return ConflictProblem("同一考试编码已经使用了不同的评价方式或评价参数,请检查考试编码。");
var batch = new OtherExamBatch { ExamCode = code, Name = name, Organizer = Normalize(request.Organizer), ExamDate = request.ExamDate, MetricKind = request.MetricKind, MaxScore = request.MaxScore, LevelOptions = Normalize(request.LevelOptions) };
db.OtherExamBatches.Add(batch);
await db.SaveChangesAsync(ct);
return Ok(new { batch.Id });
}
[HttpGet("students/lookup")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> LookupStudent(string studentNumber, CancellationToken ct)
{
var number = Normalize(studentNumber);
if (number is null) return ValidationProblem("请输入学号。");
var student = await db.Students.AsNoTracking().Where(x => x.StudentNumber == number)
.Select(x => new { x.Id, x.StudentNumber, x.Name, CollegeName = x.AdministrativeClass!.Major!.College!.Name, ClassName = x.AdministrativeClass!.Name }).FirstOrDefaultAsync(ct);
return student is null ? NotFound(new ProblemDetails { Detail = "未找到该学号对应的学生档案。", Status = 404 }) : Ok(student);
}
[HttpGet("batches/{id:guid}")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> GetBatch(Guid id, CancellationToken ct)
{
var batch = await db.OtherExamBatches.AsNoTracking().Where(x => x.Id == id)
.Select(x => new { x.Id, x.ExamCode, x.Name, x.Organizer, x.ExamDate, x.MetricKind, x.MaxScore, x.LevelOptions, x.Status, x.PublicationCount, x.PublishedAt }).FirstOrDefaultAsync(ct);
if (batch is null) return NotFound();
var results = await db.OtherExamResults.AsNoTracking().Where(x => x.OtherExamBatchId == id)
.OrderBy(x => x.Student!.StudentNumber)
.Select(x => new { x.Id, x.StudentId, StudentNumber = x.Student!.StudentNumber, StudentName = x.Student.Name, CollegeName = x.Student.AdministrativeClass!.Major!.College!.Name, ClassName = x.Student.AdministrativeClass.Name, x.AttemptNumber, x.Score, x.Level, x.IsPassed, x.Notes }).ToListAsync(ct);
return Ok(new { Batch = batch, Results = results });
}
[HttpPut("batches/{id:guid}/results")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> ReplaceResults(Guid id, ReplaceOtherExamResultsRequest request, CancellationToken ct)
{
var batch = await db.OtherExamBatches.Include(x => x.Results).FirstOrDefaultAsync(x => x.Id == id, ct);
if (batch is null) return NotFound();
var result = await ReplaceResultsAsync(batch, request.Results, ct);
return result is null ? Ok(new { updated = batch.Results.Count }) : result;
}
[HttpGet("batches/{id:guid}/template")]
[Authorize(Roles = Managers)]
public async Task<IActionResult> DownloadTemplate(Guid id, CancellationToken ct)
{
var batch = await db.OtherExamBatches.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id, ct);
if (batch is null) return NotFound();
var headers = HeadersFor(batch);
var bytes = ExcelWorkbookHelper.Create("其他考试成绩导入", headers, [], ["第一行为表头,请勿修改;每行填写一名学生。", "学号用于自动匹配姓名、学院和班级,参加次数由系统自动计算。"]);
return File(bytes, ExcelWorkbookHelper.ContentType, $"其他考试成绩导入模板-{batch.ExamCode ?? batch.Name}.xlsx");
}
[HttpPost("batches/{id:guid}/import")]
[Authorize(Roles = Managers)]
[RequestSizeLimit(10 * 1024 * 1024)]
public async Task<ActionResult> Import(Guid id, IFormFile file, CancellationToken ct)
{
var batch = await db.OtherExamBatches.Include(x => x.Results).FirstOrDefaultAsync(x => x.Id == id, ct);
if (batch is null) return NotFound();
IReadOnlyList<ExcelRow> rows;
try { rows = await ExcelWorkbookHelper.ReadAsync(file, HeadersFor(batch), ct); }
catch (InvalidDataException ex) { return ValidationProblem(ex.Message); }
if (rows.Count == 0) return ValidationProblem("Excel 中没有可导入的成绩数据。");
var inputs = new List<OtherExamResultRequest>();
var errors = new List<string>();
foreach (var row in rows)
{
var number = row["学号"].Trim();
if (number.Length == 0) { errors.Add($"第 {row.RowNumber} 行:学号不能为空。"); continue; }
var score = batch.MetricKind == OtherExamMetricKind.Score ? ParseScore(row, batch, errors) : null;
var level = batch.MetricKind == OtherExamMetricKind.Level ? Normalize(row["等级"]) : null;
var passed = batch.MetricKind == OtherExamMetricKind.PassFail ? ParsePass(row["是否合格"], row.RowNumber, errors) : null;
inputs.Add(new OtherExamResultRequest(number, score, level, passed, Normalize(row["备注"])));
}
if (errors.Count > 0) return ImportValidationProblem(errors);
var result = await ReplaceResultsAsync(batch, inputs, ct);
return result ?? Ok(new { updated = inputs.Count });
}
[HttpPost("batches/{id:guid}/publish")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> Publish(Guid id, CancellationToken ct)
{
var batch = await db.OtherExamBatches.Include(x => x.Results).FirstOrDefaultAsync(x => x.Id == id, ct);
if (batch is null) return NotFound();
if (batch.Results.Count == 0) return ConflictProblem("没有成绩记录,不能发布。");
batch.Status = OtherExamBatchStatus.Published;
batch.PublicationCount++;
batch.PublishedAt = DateTime.UtcNow;
await db.SaveChangesAsync(ct);
return Ok(new { batch.PublicationCount, batch.PublishedAt });
}
[HttpGet("mine")]
[Authorize(Roles = SystemRoles.Student)]
public async Task<ActionResult> Mine(CancellationToken ct)
{
var studentId = await db.Students.Where(x => x.UserId == scope.Current.UserId).Select(x => (Guid?)x.Id).FirstOrDefaultAsync(ct);
if (studentId is null) return ConflictProblem("当前账号未关联有效学生档案。");
var history = await db.OtherExamResults.AsNoTracking().Where(x => x.StudentId == studentId && x.OtherExamBatch!.Status == OtherExamBatchStatus.Published)
.OrderByDescending(x => x.OtherExamBatch!.ExamDate).ThenByDescending(x => x.AttemptNumber)
.Select(x => new { x.Id, ExamCode = x.OtherExamBatch!.ExamCode ?? x.OtherExamBatch.Name, BatchId = x.OtherExamBatchId, ExamName = x.OtherExamBatch.Name, x.OtherExamBatch.ExamDate, x.OtherExamBatch.MetricKind, x.OtherExamBatch.MaxScore, x.OtherExamBatch.LevelOptions, x.AttemptNumber, x.Score, x.Level, x.IsPassed, x.OtherExamBatch.PublishedAt }).ToListAsync(ct);
var best = history.GroupBy(x => x.ExamCode).Select(g => g.OrderByDescending(x => Rank(x.MetricKind, x.Score, x.Level, x.IsPassed, x.LevelOptions)).ThenByDescending(x => x.ExamDate).First()).ToList();
return Ok(new { Best = best, History = history });
}
private async Task<ActionResult?> ReplaceResultsAsync(OtherExamBatch batch, IReadOnlyList<OtherExamResultRequest> inputs, CancellationToken ct)
{
var numbers = inputs.Select(x => x.StudentNumber.Trim()).ToList();
if (numbers.Count != numbers.Distinct(StringComparer.OrdinalIgnoreCase).Count()) return ValidationProblem("同一考试批次中学生不能重复出现。");
var studentRows = await db.Students
.Where(x => numbers.Contains(x.StudentNumber))
.ToListAsync(ct);
var students = studentRows.ToDictionary(x => x.StudentNumber, StringComparer.OrdinalIgnoreCase);
if (students.Count != numbers.Count) return ValidationProblem("存在不存在的学号,请先检查学生档案。");
foreach (var item in inputs)
{
var error = ValidateResult(batch, item.Score, item.Level, item.IsPassed);
if (error is not null) return ValidationProblem(error);
}
var studentIds = students.Values.Select(x => x.Id).ToList();
var beforeCount = await db.OtherExamResults.AsNoTracking()
.Where(x => x.OtherExamBatchId != batch.Id && studentIds.Contains(x.StudentId) && (x.OtherExamBatch!.ExamCode == batch.ExamCode || (x.OtherExamBatch.ExamCode == null && batch.ExamCode == null && x.OtherExamBatch.Name == batch.Name)) && (x.OtherExamBatch.ExamDate < batch.ExamDate || (x.OtherExamBatch.ExamDate == batch.ExamDate && x.OtherExamBatch.CreatedAt < batch.CreatedAt)))
.GroupBy(x => x.StudentId).Select(x => new { StudentId = x.Key, Count = x.Count() }).ToDictionaryAsync(x => x.StudentId, x => x.Count, ct);
return await db.ExecuteInRetriableTransactionAsync<ActionResult?>(async transaction =>
{
db.OtherExamResults.RemoveRange(batch.Results);
batch.Status = OtherExamBatchStatus.Draft;
await db.SaveChangesAsync(ct);
batch.Results = inputs.Select(x =>
{
var student = students[x.StudentNumber.Trim()];
return new OtherExamResult
{
OtherExamBatchId = batch.Id,
StudentId = student.Id,
AttemptNumber = beforeCount.GetValueOrDefault(student.Id) + 1,
Score = x.Score,
Level = Normalize(x.Level),
IsPassed = x.IsPassed,
Notes = Normalize(x.Notes)
};
}).ToList();
await db.SaveChangesAsync(ct);
await transaction.CommitAsync(ct);
return null;
}, ct);
}
private static string[] HeadersFor(OtherExamBatch batch) => batch.MetricKind switch
{
OtherExamMetricKind.Score => ["学号", "成绩", "备注"],
OtherExamMetricKind.Level => ["学号", "等级", "备注"],
_ => ["学号", "是否合格", "备注"]
};
private static decimal? ParseScore(ExcelRow row, OtherExamBatch batch, List<string> errors)
{
if (decimal.TryParse(row["成绩"], NumberStyles.Number, CultureInfo.InvariantCulture, out var value) && value >= 0 && value <= batch.MaxScore) return value;
errors.Add($"第 {row.RowNumber} 行:成绩必须在 0 到 {batch.MaxScore:0.##} 之间。"); return null;
}
private static bool? ParsePass(string value, int row, List<string> errors)
{
if (value is "合格" or "是" or "通过" or "true" or "True") return true;
if (value is "不合格" or "否" or "未通过" or "false" or "False") return false;
errors.Add($"第 {row} 行:是否合格请填写合格或不合格。"); return null;
}
private static string? ValidateDefinition(OtherExamMetricKind kind, decimal? max, string? levels) => kind switch
{
OtherExamMetricKind.Score when !max.HasValue || max <= 0 => "分数制必须填写大于 0 的满分。",
OtherExamMetricKind.Level when string.IsNullOrWhiteSpace(levels) => "等级制必须填写等级选项。",
_ => null
};
private static string? ValidateResult(OtherExamBatch b, decimal? score, string? level, bool? pass) => b.MetricKind switch
{
OtherExamMetricKind.Score when !score.HasValue || score < 0 || score > b.MaxScore => "分数必须在 0 到满分之间。",
OtherExamMetricKind.Level when string.IsNullOrWhiteSpace(level) => "等级制必须填写等级。",
OtherExamMetricKind.PassFail when !pass.HasValue => "合格/不合格考试必须填写结果。",
_ => null
};
private static int Rank(OtherExamMetricKind kind, decimal? score, string? level, bool? pass, string? options)
{
if (kind == OtherExamMetricKind.Score) return (int)((score ?? -1) * 1000);
if (kind == OtherExamMetricKind.PassFail) return pass == true ? 1 : 0;
var levels = (options ?? "").Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
var index = Array.IndexOf(levels, level ?? "");
return index >= 0 ? levels.Length - index : -1;
}
private ActionResult ImportValidationProblem(IReadOnlyList<string> errors)
{
foreach (var error in errors.Take(50)) ModelState.AddModelError("file", error);
return ValidationProblem(ModelState);
}
private static string? Normalize(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
private static ConflictObjectResult ConflictProblem(string message) => new(new ProblemDetails { Status = 409, Detail = message });
}
public sealed record CreateOtherExamRequest([Required] string ExamCode, [Required] string Name, DateOnly ExamDate, OtherExamMetricKind MetricKind, decimal? MaxScore, string? LevelOptions, string? Organizer);
public sealed record ReplaceOtherExamResultsRequest(List<OtherExamResultRequest> Results);
public sealed record OtherExamResultRequest([Required] string StudentNumber, decimal? Score, string? Level, bool? IsPassed, string? Notes);
@@ -105,6 +105,7 @@ public sealed class ScheduleSettingsController(AppDbContext db, IAppCache cache)
var constraints = await db.TeachingTaskScheduleConstraints.AsNoTracking()
.WhereIn(taskIds, x => x.TeachingTaskId)
.Include(x => x.AllowedClassrooms)
.Include(x => x.AllowedExperimentClassrooms)
.ToDictionaryAsync(x => x.TeachingTaskId, cancellationToken);
return Ok(tasks.Select(task =>
{
@@ -132,11 +133,16 @@ public sealed class ScheduleSettingsController(AppDbContext db, IAppCache cache)
: constraint?.RequiresClassroom ?? true,
constraint?.RequiredCampusId,
constraint?.RequiredBuildingId,
constraint?.ExperimentRequiredCampusId,
constraint?.ExperimentRequiredBuildingId,
AllowedDayOfWeeks = ParseDays(constraint?.AllowedDayOfWeeks),
constraint?.EarliestPeriod,
constraint?.LatestPeriod,
AllowedClassroomIds = constraint?.AllowedClassrooms
.Select(x => x.ClassroomId) ?? []
.Select(x => x.ClassroomId) ?? [],
AllowedExperimentClassroomIds = constraint?.AllowedExperimentClassrooms
.Select(x => x.ClassroomId) ?? [],
AllowedExperimentVenueNatures = constraint?.AllowedExperimentVenueNatures ?? 0
};
}));
}
@@ -167,6 +173,7 @@ public sealed class ScheduleSettingsController(AppDbContext db, IAppCache cache)
{
var flexibleConstraint = await db.TeachingTaskScheduleConstraints
.Include(x => x.AllowedClassrooms)
.Include(x => x.AllowedExperimentClassrooms)
.FirstOrDefaultAsync(x => x.TeachingTaskId == teachingTaskId, cancellationToken);
if (flexibleConstraint is not null)
{
@@ -194,6 +201,22 @@ public sealed class ScheduleSettingsController(AppDbContext db, IAppCache cache)
cancellationToken))
return ValidationProblem("指定校区不存在或已停用。");
Building? experimentBuilding = null;
if (request.ExperimentRequiredBuildingId.HasValue)
{
experimentBuilding = await db.Buildings.AsNoTracking()
.FirstOrDefaultAsync(x => x.Id == request.ExperimentRequiredBuildingId && x.IsEnabled,
cancellationToken);
if (experimentBuilding is null) return ValidationProblem("指定实验教学楼不存在或已停用。");
if (request.ExperimentRequiredCampusId.HasValue &&
experimentBuilding.CampusId != request.ExperimentRequiredCampusId)
return ValidationProblem("指定实验教学楼不属于所选校区。");
}
if (request.ExperimentRequiredCampusId.HasValue &&
!await db.Campuses.AnyAsync(x => x.Id == request.ExperimentRequiredCampusId && x.IsEnabled,
cancellationToken))
return ValidationProblem("指定实验校区不存在或已停用。");
var allowedRooms = await db.Classrooms.AsNoTracking()
.Where(x => x.IsEnabled)
.WhereIn(request.AllowedClassroomIds, x => x.Id)
@@ -207,8 +230,23 @@ public sealed class ScheduleSettingsController(AppDbContext db, IAppCache cache)
allowedRooms.Any(x => x.Building!.CampusId != request.RequiredCampusId))
return ValidationProblem("指定教室必须位于所选校区。");
var allowedExperimentRoomIds = request.AllowedExperimentClassroomIds?.Distinct().ToArray() ?? [];
var allowedExperimentRooms = await db.Classrooms.AsNoTracking()
.Where(x => x.IsEnabled)
.WhereIn(allowedExperimentRoomIds, x => x.Id)
.Include(x => x.Building)
.ToListAsync(cancellationToken);
if (allowedExperimentRooms.Count != allowedExperimentRoomIds.Length)
return ValidationProblem("部分指定实验场地不存在或已停用。");
if (experimentBuilding is not null && allowedExperimentRooms.Any(x => x.BuildingId != experimentBuilding.Id))
return ValidationProblem("指定实验场地必须位于所选实验教学楼。");
if (request.ExperimentRequiredCampusId.HasValue &&
allowedExperimentRooms.Any(x => x.Building!.CampusId != request.ExperimentRequiredCampusId))
return ValidationProblem("指定实验场地必须位于所选实验校区。");
var constraint = await db.TeachingTaskScheduleConstraints
.Include(x => x.AllowedClassrooms)
.Include(x => x.AllowedExperimentClassrooms)
.FirstOrDefaultAsync(x => x.TeachingTaskId == teachingTaskId, cancellationToken);
if (constraint is null)
{
@@ -222,16 +260,28 @@ public sealed class ScheduleSettingsController(AppDbContext db, IAppCache cache)
constraint.RequiredBuildingId = request.RequiresClassroom
? request.RequiredBuildingId
: null;
constraint.ExperimentRequiredCampusId = request.RequiresClassroom
? request.ExperimentRequiredCampusId
: null;
constraint.ExperimentRequiredBuildingId = request.RequiresClassroom
? request.ExperimentRequiredBuildingId
: null;
constraint.AllowedDayOfWeeks = request.AllowedDayOfWeeks.Count == 0
? null
: string.Join(',', request.AllowedDayOfWeeks.Distinct().Order());
constraint.EarliestPeriod = request.EarliestPeriod;
constraint.LatestPeriod = request.LatestPeriod;
constraint.AllowedExperimentVenueNatures = request.AllowedExperimentVenueNatures;
db.TeachingTaskAllowedClassrooms.RemoveRange(constraint.AllowedClassrooms);
db.TeachingTaskAllowedExperimentClassrooms.RemoveRange(constraint.AllowedExperimentClassrooms);
constraint.AllowedClassrooms = request.RequiresClassroom
? request.AllowedClassroomIds.Distinct().Select(classroomId =>
new TeachingTaskAllowedClassroom { ClassroomId = classroomId }).ToList()
: [];
constraint.AllowedExperimentClassrooms = request.RequiresClassroom
? allowedExperimentRoomIds.Select(classroomId =>
new TeachingTaskAllowedExperimentClassroom { ClassroomId = classroomId }).ToList()
: [];
await db.SaveChangesAsync(cancellationToken);
return NoContent();
}
@@ -257,18 +307,23 @@ public sealed class ScheduleSettingsController(AppDbContext db, IAppCache cache)
!request.RequiresClassroom.HasValue &&
request.AllowedDayOfWeeks is null &&
!request.UpdateClassroomScope &&
!request.UpdateExperimentClassroomScope &&
!request.AllowedExperimentVenueNatures.HasValue &&
!request.UpdatePeriodRange &&
!request.EarliestPeriod.HasValue &&
!request.LatestPeriod.HasValue)
return ValidationProblem("请至少选择一项需要批量修改的设置。");
if (request.UpdateClassroomScope && request.RequiresClassroom == false)
return ValidationProblem("批量指定教室范围时,场地要求不能设置为不占用教室。");
if (request.UpdateExperimentClassroomScope && request.RequiresClassroom == false)
return ValidationProblem("批量指定实验场地时,场地要求不能设置为不占用教室。");
var tasks = await db.TeachingTasks
.Where(x =>
x.AcademicTermId == request.AcademicTermId &&
x.Status == TeachingTaskStatus.Published)
.WhereIn(taskIds, x => x.Id)
.Include(x => x.Course)
.ToListAsync(cancellationToken);
if (tasks.Count != taskIds.Length)
return ValidationProblem("部分教学任务不存在、未发布或不属于当前学期。");
@@ -279,9 +334,16 @@ public sealed class ScheduleSettingsController(AppDbContext db, IAppCache cache)
(request.SchedulingMode ?? task.SchedulingMode) ==
TeachingTaskSchedulingMode.Flexible))
return ConflictProblem("非排时课程不能指定教室,请先将当前筛选结果限定为正常排课课程。");
if (request.UpdateExperimentClassroomScope && tasks.Any(task =>
(request.SchedulingMode ?? task.SchedulingMode) ==
TeachingTaskSchedulingMode.Flexible))
return ConflictProblem("非排时课程不能指定实验场地,请先将当前筛选结果限定为正常排课课程。");
Building? building = null;
List<Classroom> allowedRooms = [];
var experimentRoomIds = request.AllowedExperimentClassroomIds?.Distinct().ToArray() ?? [];
Building? experimentBuilding = null;
List<Classroom> allowedExperimentRooms = [];
if (request.UpdateClassroomScope)
{
if (request.RequiredBuildingId.HasValue)
@@ -318,10 +380,42 @@ public sealed class ScheduleSettingsController(AppDbContext db, IAppCache cache)
x.Building!.CampusId != request.RequiredCampusId))
return ValidationProblem("指定教室必须位于所选校区。");
}
if (request.UpdateExperimentClassroomScope)
{
if (request.ExperimentRequiredBuildingId.HasValue)
{
experimentBuilding = await db.Buildings.AsNoTracking()
.FirstOrDefaultAsync(x => x.Id == request.ExperimentRequiredBuildingId && x.IsEnabled,
cancellationToken);
if (experimentBuilding is null)
return ValidationProblem("指定实验教学楼不存在或已停用。");
if (request.ExperimentRequiredCampusId.HasValue &&
experimentBuilding.CampusId != request.ExperimentRequiredCampusId)
return ValidationProblem("指定实验教学楼不属于所选实验校区。");
}
if (request.ExperimentRequiredCampusId.HasValue &&
!await db.Campuses.AnyAsync(x => x.Id == request.ExperimentRequiredCampusId && x.IsEnabled,
cancellationToken))
return ValidationProblem("指定实验校区不存在或已停用。");
allowedExperimentRooms = await db.Classrooms.AsNoTracking()
.Where(x => x.IsEnabled)
.WhereIn(experimentRoomIds, x => x.Id)
.Include(x => x.Building)
.ToListAsync(cancellationToken);
if (allowedExperimentRooms.Count != experimentRoomIds.Length)
return ValidationProblem("部分指定实验场地不存在或已停用。");
if (experimentBuilding is not null &&
allowedExperimentRooms.Any(x => x.BuildingId != experimentBuilding.Id))
return ValidationProblem("指定实验场地必须位于所选实验教学楼。");
if (request.ExperimentRequiredCampusId.HasValue &&
allowedExperimentRooms.Any(x => x.Building!.CampusId != request.ExperimentRequiredCampusId))
return ValidationProblem("指定实验场地必须位于所选实验校区。");
}
var constraints = await db.TeachingTaskScheduleConstraints
.WhereIn(taskIds, x => x.TeachingTaskId)
.Include(x => x.AllowedClassrooms)
.Include(x => x.AllowedExperimentClassrooms)
.ToDictionaryAsync(x => x.TeachingTaskId, cancellationToken);
foreach (var task in tasks)
{
@@ -340,6 +434,8 @@ public sealed class ScheduleSettingsController(AppDbContext db, IAppCache cache)
request.RequiresClassroom.HasValue ||
request.AllowedDayOfWeeks is not null ||
request.UpdateClassroomScope ||
request.UpdateExperimentClassroomScope ||
request.AllowedExperimentVenueNatures.HasValue ||
request.UpdatePeriodRange;
if (!changesConstraint) continue;
constraint = new TeachingTaskScheduleConstraint { TeachingTaskId = task.Id };
@@ -355,7 +451,10 @@ public sealed class ScheduleSettingsController(AppDbContext db, IAppCache cache)
constraint.RequiredCampusId = null;
constraint.RequiredBuildingId = null;
db.TeachingTaskAllowedClassrooms.RemoveRange(constraint.AllowedClassrooms);
db.TeachingTaskAllowedExperimentClassrooms.RemoveRange(
constraint.AllowedExperimentClassrooms);
constraint.AllowedClassrooms = [];
constraint.AllowedExperimentClassrooms = [];
}
}
if (request.AllowedDayOfWeeks is not null)
@@ -377,6 +476,17 @@ public sealed class ScheduleSettingsController(AppDbContext db, IAppCache cache)
ClassroomId = room.Id
}).ToList();
}
if (task.Course?.PracticeHours > 0 && request.AllowedExperimentVenueNatures.HasValue)
constraint.AllowedExperimentVenueNatures = request.AllowedExperimentVenueNatures.Value;
if (task.Course?.PracticeHours > 0 && request.UpdateExperimentClassroomScope)
{
constraint.ExperimentRequiredCampusId = request.ExperimentRequiredCampusId;
constraint.ExperimentRequiredBuildingId = request.ExperimentRequiredBuildingId;
db.TeachingTaskAllowedExperimentClassrooms.RemoveRange(
constraint.AllowedExperimentClassrooms);
constraint.AllowedExperimentClassrooms = allowedExperimentRooms.Select(room =>
new TeachingTaskAllowedExperimentClassroom { ClassroomId = room.Id }).ToList();
}
if (request.UpdatePeriodRange)
{
constraint.EarliestPeriod = request.EarliestPeriod;
@@ -400,11 +510,15 @@ public sealed class ScheduleSettingsController(AppDbContext db, IAppCache cache)
constraint.RequiresClassroom = false;
constraint.RequiredCampusId = null;
constraint.RequiredBuildingId = null;
constraint.ExperimentRequiredCampusId = null;
constraint.ExperimentRequiredBuildingId = null;
constraint.AllowedDayOfWeeks = null;
constraint.EarliestPeriod = null;
constraint.LatestPeriod = null;
db.TeachingTaskAllowedClassrooms.RemoveRange(constraint.AllowedClassrooms);
db.TeachingTaskAllowedExperimentClassrooms.RemoveRange(constraint.AllowedExperimentClassrooms);
constraint.AllowedClassrooms = [];
constraint.AllowedExperimentClassrooms = [];
}
private ActionResult ConflictProblem(string detail) =>
@@ -438,7 +552,11 @@ public sealed record TeachingTaskScheduleConstraintRequest(
IReadOnlyList<Guid> AllowedClassroomIds,
IReadOnlyList<int> AllowedDayOfWeeks,
[Range(1, 30)] int? EarliestPeriod,
[Range(1, 30)] int? LatestPeriod);
[Range(1, 30)] int? LatestPeriod,
TeachingVenueNature AllowedExperimentVenueNatures = 0,
IReadOnlyList<Guid>? AllowedExperimentClassroomIds = null,
Guid? ExperimentRequiredCampusId = null,
Guid? ExperimentRequiredBuildingId = null);
public sealed record TeachingTaskScheduleConstraintBatchRequest(
Guid AcademicTermId,
@@ -452,4 +570,9 @@ public sealed record TeachingTaskScheduleConstraintBatchRequest(
IReadOnlyList<Guid>? AllowedClassroomIds,
bool UpdatePeriodRange,
[Range(1, 30)] int? EarliestPeriod,
[Range(1, 30)] int? LatestPeriod);
[Range(1, 30)] int? LatestPeriod,
bool UpdateExperimentClassroomScope = false,
TeachingVenueNature? AllowedExperimentVenueNatures = null,
IReadOnlyList<Guid>? AllowedExperimentClassroomIds = null,
Guid? ExperimentRequiredCampusId = null,
Guid? ExperimentRequiredBuildingId = null);
@@ -552,6 +552,7 @@ public sealed class SchedulesController(
var constraint = await db.TeachingTaskScheduleConstraints.AsNoTracking()
.Include(x => x.AllowedClassrooms)
.Include(x => x.AllowedExperimentClassrooms)
.FirstOrDefaultAsync(
x => x.TeachingTaskId == request.TeachingTaskId,
cancellationToken);
@@ -580,22 +581,40 @@ public sealed class SchedulesController(
x => x.Id == request.ClassroomId && x.IsEnabled,
cancellationToken);
if (classroom is null) return ValidationProblem("所选教室不存在或已停用。");
if (request.Kind == ScheduleEntryKind.Experiment &&
!IsExperimentRoom(classroom.RoomType))
return ValidationProblem(
$"实验课必须安排在实验室、实训室或机房;“{classroom.Name}”的场地类型为“{classroom.RoomType}”。");
if (constraint?.RequiredCampusId is Guid campusId &&
if (request.Kind != ScheduleEntryKind.Experiment &&
constraint?.RequiredCampusId is Guid campusId &&
classroom.Building!.CampusId != campusId)
return ValidationProblem("所选教室不在该课程指定的校区。");
if (constraint?.RequiredBuildingId is Guid buildingId &&
if (request.Kind != ScheduleEntryKind.Experiment &&
constraint?.RequiredBuildingId is Guid buildingId &&
classroom.BuildingId != buildingId)
return ValidationProblem("所选教室不在该课程指定的教学楼。");
if (request.Kind == ScheduleEntryKind.Experiment &&
constraint?.ExperimentRequiredCampusId is Guid experimentCampusId &&
classroom.Building!.CampusId != experimentCampusId)
return ValidationProblem("所选场地不在该实验课指定的校区。");
if (request.Kind == ScheduleEntryKind.Experiment &&
constraint?.ExperimentRequiredBuildingId is Guid experimentBuildingId &&
classroom.BuildingId != experimentBuildingId)
return ValidationProblem("所选场地不在该实验课指定的教学楼。");
var allowedClassroomIds = constraint?.AllowedClassrooms
.Select(x => x.ClassroomId)
.ToHashSet() ?? [];
if (allowedClassroomIds.Count > 0 &&
if (request.Kind != ScheduleEntryKind.Experiment && allowedClassroomIds.Count > 0 &&
!allowedClassroomIds.Contains(classroom.Id))
return ValidationProblem("所选教室不在该课程指定的教室范围内。");
if (request.Kind == ScheduleEntryKind.Experiment &&
constraint?.AllowedExperimentVenueNatures is { } allowedNatures &&
allowedNatures != 0 &&
(classroom.TeachingVenueNature & allowedNatures) == 0)
return ValidationProblem("所选场地不在该实验课允许的教学场地性质范围内。");
var allowedExperimentClassroomIds = constraint?.AllowedExperimentClassrooms
.Select(x => x.ClassroomId)
.ToHashSet() ?? [];
if (request.Kind == ScheduleEntryKind.Experiment &&
allowedExperimentClassroomIds.Count > 0 &&
!allowedExperimentClassroomIds.Contains(classroom.Id))
return ValidationProblem("所选场地不在该实验课指定的场地范围内。");
}
var studentCount = task.Classes.Sum(x =>
x.AdministrativeClass!.Students.Count(student =>
@@ -655,11 +674,6 @@ public sealed class SchedulesController(
.Select(int.Parse)
.ToHashSet();
private static bool IsExperimentRoom(string roomType) =>
roomType.Contains("实验", StringComparison.OrdinalIgnoreCase) ||
roomType.Contains("实训", StringComparison.OrdinalIgnoreCase) ||
roomType.Contains("机房", StringComparison.OrdinalIgnoreCase) ||
roomType.Contains("语音", StringComparison.OrdinalIgnoreCase);
private async Task<ActionResult> SaveAsync(
Guid id,
@@ -21,32 +21,45 @@ public sealed class WarningsController(AppDbContext db, ICurrentUserDataScope sc
[Authorize(Roles = Managers)]
public async Task<ActionResult> GetRules(Guid academicTermId, CancellationToken ct) =>
Ok(await db.WarningRules.AsNoTracking().Where(x => x.AcademicTermId == academicTermId)
.OrderBy(x => x.Type).Select(x => new { x.Id, x.Type, x.Name, x.Threshold, x.IsEnabled, x.NotifyStudent, x.NotifyCounselor, x.Description, x.AutoCheckEnabled, CheckDayOfWeek = x.CheckDayOfWeek ?? 0, x.CheckHour, x.CheckMinute, x.LastCheckAt })
.OrderBy(x => x.Type).Select(x => new { x.Id, Type = (int)x.Type, x.Name, x.Threshold, x.IsEnabled, x.NotifyStudent, x.NotifyCounselor, x.Description, x.AutoCheckEnabled, CheckDayOfWeek = x.CheckDayOfWeek ?? 0, x.CheckHour, x.CheckMinute, x.LastCheckAt })
.ToListAsync(ct));
[HttpPut("rules")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> SaveRules(Guid academicTermId, List<WarningRuleDto> rules, CancellationToken ct)
{
if (rules.GroupBy(x => x.Type).Any(group => group.Count() > 1))
return BadRequest(new ProblemDetails { Title = "预警类型不能重复。", Status = StatusCodes.Status400BadRequest });
if (rules.Any(x => x.CheckDayOfWeek is < 0 or > 7 || x.CheckHour is < 0 or > 23 || x.CheckMinute is < 0 or > 59))
return BadRequest(new ProblemDetails { Title = "自动检测时间无效。", Status = StatusCodes.Status400BadRequest });
var existing = await db.WarningRules.Where(x => x.AcademicTermId == academicTermId).ToListAsync(ct);
db.WarningRules.RemoveRange(existing);
var incomingTypes = rules.Select(x => x.Type).ToHashSet();
db.WarningRules.RemoveRange(existing.Where(x => !incomingTypes.Contains(x.Type)));
foreach (var r in rules)
{
db.WarningRules.Add(new WarningRule
var entity = existing.FirstOrDefault(x => x.Type == r.Type);
if (entity is null)
{
entity = new WarningRule
{
AcademicTermId = academicTermId,
Type = r.Type,
Name = r.Name.Trim(),
Threshold = r.Threshold,
IsEnabled = r.IsEnabled,
NotifyStudent = r.NotifyStudent,
NotifyCounselor = r.NotifyCounselor,
Description = r.Description?.Trim(),
AutoCheckEnabled = r.AutoCheckEnabled,
CheckDayOfWeek = r.CheckDayOfWeek == 0 ? null : r.CheckDayOfWeek,
CheckHour = r.CheckHour,
CheckMinute = r.CheckMinute
});
Name = r.Name.Trim()
};
db.WarningRules.Add(entity);
}
entity.Name = r.Name.Trim();
entity.Threshold = r.Threshold;
entity.IsEnabled = r.IsEnabled;
entity.NotifyStudent = r.NotifyStudent;
entity.NotifyCounselor = r.NotifyCounselor;
entity.Description = r.Description?.Trim();
entity.AutoCheckEnabled = r.AutoCheckEnabled;
entity.CheckDayOfWeek = r.CheckDayOfWeek == 0 ? null : r.CheckDayOfWeek;
entity.CheckHour = r.CheckHour;
entity.CheckMinute = r.CheckMinute;
}
await db.SaveChangesAsync(ct);
return NoContent();
@@ -120,7 +133,7 @@ public sealed class WarningsController(AppDbContext db, ICurrentUserDataScope sc
}
if (academicTermId.HasValue) q = q.Where(x => x.AcademicTermId == academicTermId);
if (type.HasValue) q = q.Where(x => x.Type == type);
return Ok(await q.OrderByDescending(x => x.CreatedAt).Select(x => new { x.Id, x.StudentId, StudentName = x.Student!.Name, StudentNumber = x.Student.StudentNumber, ClassName = x.Student.AdministrativeClass!.Name, x.Type, x.Status, x.TriggerValue, x.Detail, x.AcknowledgedAt, x.AcknowledgeComment, x.CreatedAt }).ToListAsync(ct));
return Ok(await q.OrderByDescending(x => x.CreatedAt).Select(x => new { x.Id, x.StudentId, StudentName = x.Student!.Name, StudentNumber = x.Student.StudentNumber, ClassName = x.Student.AdministrativeClass!.Name, Type = (int)x.Type, Status = (int)x.Status, x.TriggerValue, x.Detail, x.AcknowledgedAt, x.AcknowledgeComment, x.CreatedAt }).ToListAsync(ct));
}
// ═══════════ Student ═══════════
@@ -131,7 +144,7 @@ public sealed class WarningsController(AppDbContext db, ICurrentUserDataScope sc
var sid = await GetStudentIdAsync(ct);
if (sid is null) return StudentNotFound();
return Ok(await db.WarningRecords.AsNoTracking().Where(x => x.StudentId == sid).OrderByDescending(x => x.CreatedAt)
.Select(x => new { x.Id, x.Type, x.Status, x.TriggerValue, x.Detail, x.AcknowledgedAt, x.AcknowledgeComment, x.CreatedAt, TermName = x.AcademicTermId })
.Select(x => new { x.Id, Type = (int)x.Type, Status = (int)x.Status, x.TriggerValue, x.Detail, x.AcknowledgedAt, x.AcknowledgeComment, x.CreatedAt, TermName = x.AcademicTermId })
.ToListAsync(ct));
}
@@ -0,0 +1,14 @@
using Jiaowu.Api.Domain.Common;
namespace Jiaowu.Api.Domain.Academic;
public sealed class CourseGradeStatisticsRefreshSetting : EntityBase
{
public const string DefaultKey = "default";
public string Key { get; set; } = DefaultKey;
public bool IsEnabled { get; set; } = true;
public int IntervalSeconds { get; set; } = 300;
public int BatchSize { get; set; } = 100;
public DateTime? LastRunAt { get; set; }
}
@@ -38,6 +38,22 @@ public sealed class CurriculumCourse : EntityBase
public string? Notes { get; set; }
}
public sealed class CourseGroup : EntityBase
{
public required string Code { get; set; }
public required string Name { get; set; }
public string? Description { get; set; }
public ICollection<CourseGroupCourse> Courses { get; set; } = [];
}
public sealed class CourseGroupCourse : EntityBase
{
public Guid CourseGroupId { get; set; }
public CourseGroup? CourseGroup { get; set; }
public Guid CourseId { get; set; }
public Course? Course { get; set; }
}
public enum CurriculumPlanStatus
{
Draft = 1,
@@ -20,6 +20,7 @@ public sealed class ExamArrangementJob : EntityBase
public Guid PlanId { get; set; }
public Guid? ActivePlanId { get; set; }
public Guid? RequestedByUserId { get; set; }
public string? ProjectIdsJson { get; set; }
public string? SessionIdsJson { get; set; }
public bool AssignClassrooms { get; set; }
public bool AssignInvigilators { get; set; }
@@ -138,6 +139,7 @@ public sealed class ExamPublishJob : EntityBase
public Guid PlanId { get; set; }
public Guid? ActivePlanId { get; set; }
public Guid? RequestedByUserId { get; set; }
public string? ProjectIdsJson { get; set; }
public ExamPublishJobStatus Status { get; set; } = ExamPublishJobStatus.Queued;
public string? CurrentStep { get; set; }
public string? ErrorMessage { get; set; }
@@ -148,7 +150,8 @@ public sealed class ExamPublishJob : EntityBase
public enum ExamPublishJobKind
{
FormalExam = 1,
MakeupExam = 2
MakeupExam = 2,
ExperimentProjects = 3
}
public enum ExamPublishJobStatus
@@ -6,6 +6,11 @@ public sealed class ExperimentProject : EntityBase
{
public Guid TeachingTaskId { get; set; }
public TeachingTask? TeachingTask { get; set; }
// 集中安排的项目复用已发布课表中的实验课,不再维护一份重复的场次。
public Guid? ScheduleEntryId { get; set; }
public ScheduleEntry? ScheduleEntry { get; set; }
// 集中安排按课表的具体周次拆分为实验项目;自行安排为空。
public int? ScheduleWeek { get; set; }
public required string Code { get; set; }
public required string Name { get; set; }
public ExperimentArrangementMode ArrangementMode { get; set; }
@@ -51,6 +51,22 @@ public sealed class ExperimentGradeRecord : EntityBase
public ICollection<ExperimentGradeItemScore> ItemScores { get; set; } = [];
}
/// <summary>
/// A student's persisted experiment-part score for one teaching task.
/// The score is the weighted average of every published experiment project.
/// </summary>
public sealed class ExperimentCourseGrade : EntityBase
{
public Guid TeachingTaskId { get; set; }
public TeachingTask? TeachingTask { get; set; }
public Guid StudentId { get; set; }
public Student? Student { get; set; }
public decimal? WeightedAverageScore { get; set; }
public decimal TotalWeight { get; set; }
public int PublishedProjectCount { get; set; }
public DateTime RefreshedAt { get; set; }
}
public sealed class ExperimentGradeItemScore
{
public Guid ExperimentGradeRecordId { get; set; }
@@ -54,6 +54,99 @@ public sealed class GradeItemScore
public decimal? Score { get; set; }
}
/// <summary>
/// Persisted course-result aggregate. One course/term is materialized at each
/// organizational level so the result-analysis page never aggregates raw
/// grade records on request.
/// </summary>
public sealed class CourseGradeStatistic : EntityBase
{
public Guid CourseId { get; set; }
public Guid AcademicTermId { get; set; }
public CourseGradeStatisticScope Scope { get; set; }
public Guid? ScopeEntityId { get; set; }
public int StudentCount { get; set; }
public int PassedCount { get; set; }
public int Below60Count { get; set; }
public int From60To69Count { get; set; }
public int From70To79Count { get; set; }
public int From80To89Count { get; set; }
public int From90To100Count { get; set; }
public decimal HighestScore { get; set; }
public decimal AverageScore { get; set; }
public decimal LowestScore { get; set; }
public decimal PassRate { get; set; }
public DateTime CalculatedAt { get; set; }
}
/// <summary>
/// Materialized analysis for one published teaching class. Course/term
/// organizational benchmarks stay in <see cref="CourseGradeStatistic"/>;
/// this table is the grain used for peer-class and historical comparisons.
/// </summary>
public sealed class TeachingTaskGradeStatistic : EntityBase
{
public Guid GradeSheetId { get; set; }
public GradeSheet? GradeSheet { get; set; }
public Guid TeachingTaskId { get; set; }
public TeachingTask? TeachingTask { get; set; }
public Guid CourseId { get; set; }
public Guid AcademicTermId { get; set; }
public int StudentCount { get; set; }
public int PassedCount { get; set; }
public int ExcellentCount { get; set; }
public decimal HighestScore { get; set; }
public decimal AverageScore { get; set; }
public decimal MedianScore { get; set; }
public decimal LowestScore { get; set; }
public decimal StandardDeviation { get; set; }
public decimal PassRate { get; set; }
public decimal ExcellentRate { get; set; }
public DateTime CalculatedAt { get; set; }
public ICollection<TeachingTaskGradeScoreBand> ScoreBands { get; set; } = [];
}
/// <summary>
/// Flexible score-band rows are kept separately so future band definitions do
/// not require widening the teaching-class summary table.
/// </summary>
public sealed class TeachingTaskGradeScoreBand : EntityBase
{
public Guid TeachingTaskGradeStatisticId { get; set; }
public TeachingTaskGradeStatistic? TeachingTaskGradeStatistic { get; set; }
public required string Label { get; set; }
public decimal LowerBound { get; set; }
public decimal? UpperBound { get; set; }
public int StudentCount { get; set; }
public int SortOrder { get; set; }
}
public enum CourseGradeStatisticScope
{
AdministrativeClass = 1,
Major = 2,
College = 3,
University = 4
}
public sealed class CourseGradeStatisticsRefreshJob : EntityBase
{
public Guid GradeSheetId { get; set; }
public CourseGradeStatisticsRefreshJobStatus Status { get; set; } =
CourseGradeStatisticsRefreshJobStatus.Queued;
public DateTime? StartedAt { get; set; }
public DateTime? CompletedAt { get; set; }
public string? ErrorMessage { get; set; }
}
public enum CourseGradeStatisticsRefreshJobStatus
{
Queued = 1,
Running = 2,
Succeeded = 3,
Failed = 4
}
public enum GradeSheetStatus
{
Draft = 1,
@@ -46,9 +46,35 @@ public sealed class Classroom : CatalogEntity
public Building? Building { get; set; }
public int Capacity { get; set; }
public string RoomType { get; set; } = "普通教室";
public TeachingVenueNature TeachingVenueNature { get; set; } =
TeachingVenueNature.GeneralClassroom;
public string? Equipment { get; set; }
}
[Flags]
public enum TeachingVenueNature
{
GeneralClassroom = 1,
Laboratory = 2,
TrainingRoom = 4,
ComputerLab = 8,
LanguageLab = 16,
SportsVenue = 32,
ArtsVenue = 64
}
public static class TeachingVenueNatureRules
{
public const TeachingVenueNature ExperimentTeaching =
TeachingVenueNature.Laboratory |
TeachingVenueNature.TrainingRoom |
TeachingVenueNature.ComputerLab |
TeachingVenueNature.LanguageLab;
public static bool SupportsExperiment(TeachingVenueNature value) =>
(value & ExperimentTeaching) != 0;
}
public sealed class AcademicTerm : CatalogEntity
{
public required string AcademicYear { get; set; }
@@ -0,0 +1,44 @@
using Jiaowu.Api.Domain.Common;
namespace Jiaowu.Api.Domain.Academic;
public sealed class OtherExamBatch : EntityBase
{
public string? ExamCode { get; set; }
public required string Name { get; set; }
public string? Organizer { get; set; }
public DateOnly ExamDate { get; set; }
public OtherExamMetricKind MetricKind { get; set; }
public decimal? MaxScore { get; set; }
public string? LevelOptions { get; set; }
public OtherExamBatchStatus Status { get; set; } = OtherExamBatchStatus.Draft;
public int PublicationCount { get; set; }
public DateTime? PublishedAt { get; set; }
public ICollection<OtherExamResult> Results { get; set; } = [];
}
public sealed class OtherExamResult : EntityBase
{
public Guid OtherExamBatchId { get; set; }
public OtherExamBatch? OtherExamBatch { get; set; }
public Guid StudentId { get; set; }
public Student? Student { get; set; }
public int AttemptNumber { get; set; } = 1;
public decimal? Score { get; set; }
public string? Level { get; set; }
public bool? IsPassed { get; set; }
public string? Notes { get; set; }
}
public enum OtherExamMetricKind
{
PassFail = 1,
Level = 2,
Score = 3
}
public enum OtherExamBatchStatus
{
Draft = 1,
Published = 2
}
@@ -52,10 +52,16 @@ public sealed class TeachingTaskScheduleConstraint : EntityBase
public Campus? RequiredCampus { get; set; }
public Guid? RequiredBuildingId { get; set; }
public Building? RequiredBuilding { get; set; }
public Guid? ExperimentRequiredCampusId { get; set; }
public Campus? ExperimentRequiredCampus { get; set; }
public Guid? ExperimentRequiredBuildingId { get; set; }
public Building? ExperimentRequiredBuilding { get; set; }
public string? AllowedDayOfWeeks { get; set; }
public int? EarliestPeriod { get; set; }
public int? LatestPeriod { get; set; }
public TeachingVenueNature AllowedExperimentVenueNatures { get; set; }
public ICollection<TeachingTaskAllowedClassroom> AllowedClassrooms { get; set; } = [];
public ICollection<TeachingTaskAllowedExperimentClassroom> AllowedExperimentClassrooms { get; set; } = [];
}
public sealed class TeachingTaskAllowedClassroom
@@ -66,6 +72,31 @@ public sealed class TeachingTaskAllowedClassroom
public Classroom? Classroom { get; set; }
}
public sealed class PublishedScheduleOccurrence : EntityBase
{
public Guid SchedulePlanId { get; set; }
public Guid AcademicTermId { get; set; }
public Guid ScheduleEntryId { get; set; }
public Guid TeachingTaskId { get; set; }
public Guid? ClassroomId { get; set; }
public int Week { get; set; }
public int DayOfWeek { get; set; }
public int StartPeriod { get; set; }
public int PeriodCount { get; set; }
public ScheduleEntryKind Kind { get; set; }
public ScheduleEntry? ScheduleEntry { get; set; }
public TeachingTask? TeachingTask { get; set; }
public Classroom? Classroom { get; set; }
}
public sealed class TeachingTaskAllowedExperimentClassroom
{
public Guid TeachingTaskScheduleConstraintId { get; set; }
public TeachingTaskScheduleConstraint? TeachingTaskScheduleConstraint { get; set; }
public Guid ClassroomId { get; set; }
public Classroom? Classroom { get; set; }
}
public sealed class AutomaticScheduleJob : EntityBase
{
public Guid SchedulePlanId { get; set; }
@@ -33,7 +33,8 @@ public enum BackgroundJobKind
MakeupExamAuto = 3,
ExamArrangement = 4,
ExamSignInExport = 5,
ExamPublish = 6
ExamPublish = 6,
CourseGradeStatisticsRefresh = 7
}
public enum BackgroundJobOutboxState
@@ -0,0 +1,14 @@
using Jiaowu.Api.Domain.Common;
namespace Jiaowu.Api.Domain.System;
public static class SystemFeatureKeys
{
public const string SwaggerDocumentation = "SwaggerDocumentation";
}
public sealed class SystemFeatureSetting : EntityBase
{
public required string Key { get; set; }
public bool IsEnabled { get; set; }
}
@@ -16,6 +16,7 @@ public sealed class BackgroundJobOptions
public int ExamArrangementConcurrency { get; set; } = 1;
public int ExamSignInExportConcurrency { get; set; } = 1;
public int ExamPublishConcurrency { get; set; } = 1;
public int CourseGradeStatisticsRefreshConcurrency { get; set; } = 1;
public string Exchange { get; set; } = "jiaowu.background-jobs";
public string QueuePrefix { get; set; } = "jiaowu.background-jobs";
public bool UseQuorumQueues { get; set; } = true;
@@ -35,6 +36,8 @@ public sealed class BackgroundJobOptions
BackgroundJobKind.ExamArrangement => ExamArrangementConcurrency,
BackgroundJobKind.ExamSignInExport => ExamSignInExportConcurrency,
BackgroundJobKind.ExamPublish => ExamPublishConcurrency,
BackgroundJobKind.CourseGradeStatisticsRefresh =>
CourseGradeStatisticsRefreshConcurrency,
_ => throw new ArgumentOutOfRangeException(nameof(kind), kind, null)
};
}
@@ -130,6 +130,15 @@ public sealed class BackgroundJobOutboxPublisher(
message.JobId == x.Id))
.Select(x => x.Id)
.ToListAsync(cancellationToken);
var gradeStatisticsJobs = await db.CourseGradeStatisticsRefreshJobs.AsNoTracking()
.Where(x =>
(x.Status == CourseGradeStatisticsRefreshJobStatus.Queued ||
x.Status == CourseGradeStatisticsRefreshJobStatus.Running) &&
!db.BackgroundJobOutboxMessages.Any(message =>
message.JobKind == BackgroundJobKind.CourseGradeStatisticsRefresh &&
message.JobId == x.Id))
.Select(x => x.Id)
.ToListAsync(cancellationToken);
var missingKeys = automaticJobs
.Select(id => (BackgroundJobKind.AutomaticSchedule, id))
@@ -143,6 +152,8 @@ public sealed class BackgroundJobOutboxPublisher(
(BackgroundJobKind.ExamSignInExport, id)))
.Concat(publishJobs2.Select(id =>
(BackgroundJobKind.ExamPublish, id)))
.Concat(gradeStatisticsJobs.Select(id =>
(BackgroundJobKind.CourseGradeStatisticsRefresh, id)))
.ToList();
foreach (var (kind, jobId) in missingKeys)
{
@@ -2,6 +2,7 @@ using System.Diagnostics;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.System;
using Jiaowu.Api.Infrastructure.Exams;
using Jiaowu.Api.Infrastructure.Grades;
using Jiaowu.Api.Infrastructure.Persistence;
using Jiaowu.Api.Infrastructure.Scheduling;
using Microsoft.EntityFrameworkCore;
@@ -100,6 +101,11 @@ public sealed class BackgroundJobRunner(
.GetRequiredService<ExamPublishJobProcessor>()
.ProcessAsync(message.JobId, cancellationToken);
break;
case BackgroundJobKind.CourseGradeStatisticsRefresh:
await scope.ServiceProvider
.GetRequiredService<CourseGradeStatisticsRefreshJobProcessor>()
.ProcessAsync(message.JobId, cancellationToken);
break;
default:
throw new InvalidOperationException(
$"Unsupported background job kind '{message.JobKind}'.");
@@ -308,6 +314,19 @@ public sealed class BackgroundJobRunner(
.SetProperty(x => x.CompletedAt, completedAt),
cancellationToken);
break;
case BackgroundJobKind.CourseGradeStatisticsRefresh:
await db.CourseGradeStatisticsRefreshJobs
.Where(x => x.Id == message.JobId &&
x.Status != CourseGradeStatisticsRefreshJobStatus.Succeeded &&
x.Status != CourseGradeStatisticsRefreshJobStatus.Failed)
.ExecuteUpdateAsync(
setters => setters
.SetProperty(x => x.Status,
CourseGradeStatisticsRefreshJobStatus.Failed)
.SetProperty(x => x.ErrorMessage, error)
.SetProperty(x => x.CompletedAt, completedAt),
cancellationToken);
break;
default:
throw new ArgumentOutOfRangeException(
nameof(message.JobKind),
@@ -319,7 +319,8 @@ internal static class RabbitMqBackgroundJobTopology
BackgroundJobKind.MakeupExamAuto,
BackgroundJobKind.ExamArrangement,
BackgroundJobKind.ExamSignInExport,
BackgroundJobKind.ExamPublish
BackgroundJobKind.ExamPublish,
BackgroundJobKind.CourseGradeStatisticsRefresh
];
public static async Task<IConnection> CreateConnectionAsync(
@@ -418,6 +419,7 @@ internal static class RabbitMqBackgroundJobTopology
BackgroundJobKind.ExamArrangement => "exam.arrangement",
BackgroundJobKind.ExamSignInExport => "exam.sign-in-export",
BackgroundJobKind.ExamPublish => "exam.publish",
BackgroundJobKind.CourseGradeStatisticsRefresh => "grade-statistics.refresh",
_ => throw new ArgumentOutOfRangeException(nameof(kind), kind, null)
};
@@ -182,12 +182,19 @@ public static class AppCacheKeys
return $"statistics:v2:{Normalize(area)}:scope:{Normalize(dataScope)}:" +
$"college:{effectiveCollegeId?.ToString("N") ?? "all"}:{filterPart}";
}
public static string CourseGradeStatistics(Guid gradeSheetId) =>
$"grade-statistics:sheet:{gradeSheetId:N}";
public static string TeachingTaskGradeAnalytics(Guid gradeSheetId) =>
$"grade-analytics:sheet:{gradeSheetId:N}:v1";
}
public static class AppCacheTags
{
public const string BaseData = "base-data";
public const string Analytics = "analytics";
public const string CourseGradeStatistics = "grade-statistics";
public const string Timetables = "timetables";
public const string TimetableOptions = "timetable:options";
@@ -1,8 +1,11 @@
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.System;
using Jiaowu.Api.Infrastructure.Caching;
using Jiaowu.Api.Controllers;
using Jiaowu.Api.Infrastructure.Persistence;
using Jiaowu.Api.Infrastructure.Teaching;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
namespace Jiaowu.Api.Infrastructure.Exams;
@@ -39,6 +42,9 @@ public sealed class ExamPublishJobProcessor(
case ExamPublishJobKind.MakeupExam:
await PublishMakeupExamAsync(job, stoppingToken);
break;
case ExamPublishJobKind.ExperimentProjects:
await PublishExperimentProjectsAsync(job, stoppingToken);
break;
default:
throw new InvalidOperationException(
$"不支持的考试发布类型:{job.Kind}。");
@@ -248,6 +254,58 @@ public sealed class ExamPublishJobProcessor(
await db.SaveChangesAsync(ct);
}
private async Task PublishExperimentProjectsAsync(ExamPublishJob job, CancellationToken ct)
{
var ids = JsonSerializer.Deserialize<List<Guid>>(job.ProjectIdsJson ?? "[]")?
.Where(x => x != Guid.Empty).Distinct().ToList() ?? [];
if (ids.Count is 0 or > 100)
throw new ExamPublishValidationException("实验发布任务的数据无效。请重新提交。");
var projects = await db.ExperimentProjects
.Include(x => x.Sessions)
.Include(x => x.TeachingTask)
.ThenInclude(x => x!.Course)
.Where(x => ids.Contains(x.Id))
.ToListAsync(ct);
if (projects.Count != ids.Count)
throw new ExamPublishValidationException("部分实验项目不存在,请刷新后重新提交。");
foreach (var project in projects)
{
if (project.Status != ExperimentProjectStatus.Draft)
throw new ExamPublishValidationException("批量发布只能包含草稿实验项目。");
var hasSchedule = project.ArrangementMode == ExperimentArrangementMode.Centralized
? project.ScheduleEntryId.HasValue || project.Sessions.Any(x => x.Status == ExperimentSessionStatus.Scheduled)
: project.Sessions.Any(x => x.Status == ExperimentSessionStatus.Scheduled);
if (!hasSchedule)
throw new ExamPublishValidationException($"“{project.Name}”尚未具备发布条件。");
if (project.Sessions.Any(x => x.Status == ExperimentSessionStatus.Scheduled &&
(x.SessionDate < project.StartDate || x.SessionDate > project.EndDate)))
throw new ExamPublishValidationException($"“{project.Name}”存在不在开放日期范围内的实验场次。");
}
job.CurrentStep = "正在发布实验项目";
await db.SaveChangesAsync(ct);
var publishedAt = DateTime.UtcNow;
foreach (var project in projects)
{
project.Status = ExperimentProjectStatus.Published;
project.PublishedAt = publishedAt;
}
await db.SaveChangesAsync(ct);
foreach (var project in projects)
{
var userIds = await TeachingTaskRosterQuery.ForTask(db, project.TeachingTaskId)
.Where(x => x.UserId.HasValue).Select(x => x.UserId!.Value).Distinct().ToListAsync(ct);
if (userIds.Count == 0) continue;
var mode = project.ArrangementMode == ExperimentArrangementMode.Centralized ? "集中安排" : "自行预约";
await NotificationService.SendToUserIdsAsync(db, userIds, "实验项目已发布",
$"《{project.TeachingTask!.Course!.Name}》已发布“{project.Name}”({mode}),请查看实验安排。",
"/experiments", ct, NotificationCategory.Schedule);
}
}
private async Task MarkFailedAsync(Guid jobId, string message)
{
db.ChangeTracker.Clear();
@@ -11,7 +11,8 @@ public static class ExcelWorkbookHelper
string sheetName,
IReadOnlyList<string> headers,
IEnumerable<IReadOnlyList<object?>> rows,
IReadOnlyList<string>? instructions = null)
IReadOnlyList<string>? instructions = null,
Action<IXLWorksheet, int>? configureRow = null)
{
using var workbook = new XLWorkbook();
var sheet = workbook.Worksheets.Add(sheetName);
@@ -33,6 +34,7 @@ public static class ExcelWorkbookHelper
{
SetCellValue(sheet.Cell(rowNumber, column + 1), row[column]);
}
configureRow?.Invoke(sheet, rowNumber);
rowNumber++;
}
@@ -0,0 +1,228 @@
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.System;
using Jiaowu.Api.Infrastructure.BackgroundJobs;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
namespace Jiaowu.Api.Infrastructure.Grades;
/// <summary>
/// Repairs missing or stale materialized grade statistics on a database-
/// configured fixed interval. Grade writes do not enqueue refresh jobs; this
/// worker batches changes made during bulk imports.
/// </summary>
public sealed class CourseGradeStatisticsRefreshWorker(
IServiceScopeFactory scopeFactory,
TimeProvider timeProvider,
ILogger<CourseGradeStatisticsRefreshWorker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
logger.LogInformation("Database-configured course grade statistics scheduler started.");
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(10), timeProvider);
while (!stoppingToken.IsCancellationRequested)
{
try
{
await using var scope = scopeFactory.CreateAsyncScope();
var scheduler = scope.ServiceProvider
.GetRequiredService<CourseGradeStatisticsRefreshScheduler>();
var queued = await scheduler.EnqueueDueAsync(
timeProvider.GetUtcNow().UtcDateTime,
stoppingToken);
if (queued > 0)
logger.LogInformation(
"Scheduled course grade statistics scan queued {Count} refresh jobs.",
queued);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception exception)
{
logger.LogError(exception, "Scheduled course grade statistics scan failed.");
}
if (!await timer.WaitForNextTickAsync(stoppingToken)) break;
}
}
}
public sealed class CourseGradeStatisticsRefreshScheduler(
AppDbContext db,
ILogger<CourseGradeStatisticsRefreshScheduler> logger)
{
public async Task<int> EnqueueDueAsync(
DateTime utcNow,
CancellationToken cancellationToken) =>
await ExecuteWithLeaseAsync(async () =>
{
var setting = await db.CourseGradeStatisticsRefreshSettings
.SingleOrDefaultAsync(
x => x.Key == CourseGradeStatisticsRefreshSetting.DefaultKey,
cancellationToken);
if (setting is null)
{
setting = new CourseGradeStatisticsRefreshSetting();
db.CourseGradeStatisticsRefreshSettings.Add(setting);
}
var interval = TimeSpan.FromSeconds(
Math.Clamp(setting.IntervalSeconds, 10, 86400));
if (!setting.IsEnabled ||
setting.LastRunAt.HasValue && utcNow < setting.LastRunAt.Value + interval)
{
if (db.Entry(setting).State == EntityState.Added)
await db.SaveChangesAsync(cancellationToken);
return 0;
}
setting.LastRunAt = utcNow;
var queued = await EnqueueStaleCoreAsync(setting.BatchSize, cancellationToken);
await db.SaveChangesAsync(cancellationToken);
return queued;
}, cancellationToken);
public async Task<int> EnqueueStaleAsync(
int batchSize,
CancellationToken cancellationToken) =>
await ExecuteWithLeaseAsync(async () =>
{
var queued = await EnqueueStaleCoreAsync(batchSize, cancellationToken);
if (queued > 0) await db.SaveChangesAsync(cancellationToken);
return queued;
}, cancellationToken);
private async Task<int> ExecuteWithLeaseAsync(
Func<Task<int>> action,
CancellationToken cancellationToken)
{
var usesMySqlLease = db.Database.ProviderName?.Contains(
"MySql",
StringComparison.OrdinalIgnoreCase) == true;
if (usesMySqlLease && !await TryAcquireMySqlLeaseAsync(cancellationToken))
{
await db.Database.CloseConnectionAsync();
logger.LogDebug("Another instance owns the grade statistics refresh lease.");
return 0;
}
try
{
return await action();
}
finally
{
if (usesMySqlLease)
await ReleaseMySqlLeaseAsync();
}
}
private async Task<int> EnqueueStaleCoreAsync(
int batchSize,
CancellationToken cancellationToken)
{
batchSize = Math.Clamp(batchSize, 1, 5000);
var activeTargets = await (
from job in db.CourseGradeStatisticsRefreshJobs.AsNoTracking()
join sheet in db.GradeSheets.AsNoTracking()
on job.GradeSheetId equals sheet.Id
where job.Status == CourseGradeStatisticsRefreshJobStatus.Queued ||
job.Status == CourseGradeStatisticsRefreshJobStatus.Running
select new CourseTermTarget(
sheet.TeachingTask!.CourseId,
sheet.TeachingTask.AcademicTermId))
.Distinct()
.ToListAsync(cancellationToken);
var active = activeTargets.ToHashSet();
var rows = await db.GradeSheets.AsNoTracking()
.Where(sheet =>
sheet.Status == GradeSheetStatus.Published &&
sheet.Records.Any(record => record.TotalScore != null))
.Select(sheet => new RefreshCandidate(
sheet.Id,
sheet.TeachingTask!.CourseId,
sheet.TeachingTask.AcademicTermId,
sheet.UpdatedAt,
sheet.Records
.Where(record => record.TotalScore != null)
.Max(record => record.UpdatedAt),
db.TeachingTaskGradeStatistics
.Where(statistic => statistic.GradeSheetId == sheet.Id)
.Select(statistic => (DateTime?)statistic.CalculatedAt)
.FirstOrDefault()))
.ToListAsync(cancellationToken);
var stale = rows
.Where(row =>
row.CalculatedAt is null ||
row.SheetUpdatedAt > row.CalculatedAt ||
row.RecordsUpdatedAt > row.CalculatedAt)
.GroupBy(row => new CourseTermTarget(row.CourseId, row.AcademicTermId))
.Where(group => !active.Contains(group.Key))
.Select(group => group
.OrderByDescending(row => row.RecordsUpdatedAt)
.ThenByDescending(row => row.SheetUpdatedAt)
.First())
.Take(batchSize)
.ToArray();
foreach (var candidate in stale)
{
var job = new CourseGradeStatisticsRefreshJob
{
GradeSheetId = candidate.GradeSheetId
};
db.CourseGradeStatisticsRefreshJobs.Add(job);
db.BackgroundJobOutboxMessages.Add(BackgroundJobOutboxMessage.Create(
BackgroundJobKind.CourseGradeStatisticsRefresh,
job.Id));
}
if (stale.Length == 0) return 0;
logger.LogDebug(
"Queued {Count} stale course grade statistics targets.",
stale.Length);
return stale.Length;
}
private async Task<bool> TryAcquireMySqlLeaseAsync(
CancellationToken cancellationToken)
{
await db.Database.OpenConnectionAsync(cancellationToken);
await using var command = db.Database.GetDbConnection().CreateCommand();
command.CommandText = "SELECT GET_LOCK('jiaowu:grade-statistics-refresh', 0);";
var result = await command.ExecuteScalarAsync(cancellationToken);
return Convert.ToInt32(result) == 1;
}
private async Task ReleaseMySqlLeaseAsync()
{
try
{
await using var command = db.Database.GetDbConnection().CreateCommand();
command.CommandText = "SELECT RELEASE_LOCK('jiaowu:grade-statistics-refresh');";
await command.ExecuteScalarAsync(CancellationToken.None);
}
catch (Exception exception)
{
logger.LogWarning(exception, "Failed to release grade statistics refresh lease.");
}
finally
{
await db.Database.CloseConnectionAsync();
}
}
private sealed record RefreshCandidate(
Guid GradeSheetId,
Guid CourseId,
Guid AcademicTermId,
DateTime SheetUpdatedAt,
DateTime RecordsUpdatedAt,
DateTime? CalculatedAt);
private sealed record CourseTermTarget(Guid CourseId, Guid AcademicTermId);
}
@@ -0,0 +1,250 @@
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Infrastructure.Caching;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
namespace Jiaowu.Api.Infrastructure.Grades;
/// <summary>
/// Rebuilds a course/term's denormalized result statistics. The operation is
/// intentionally idempotent: duplicate RabbitMQ deliveries are safe.
/// </summary>
public sealed class CourseGradeStatisticsRefreshJobProcessor(
AppDbContext db,
IAppCache cache,
ILogger<CourseGradeStatisticsRefreshJobProcessor> logger)
{
public async Task ProcessAsync(Guid jobId, CancellationToken cancellationToken)
{
var job = await db.CourseGradeStatisticsRefreshJobs
.FirstOrDefaultAsync(x => x.Id == jobId, cancellationToken);
if (job is null || job.Status == CourseGradeStatisticsRefreshJobStatus.Succeeded)
return;
job.Status = CourseGradeStatisticsRefreshJobStatus.Running;
job.StartedAt = DateTime.UtcNow;
job.ErrorMessage = null;
await db.SaveChangesAsync(cancellationToken);
var sheetData = await db.GradeSheets.AsNoTracking()
.Where(x => x.Id == job.GradeSheetId)
.Select(x => new { x.Id, x.TeachingTask!.CourseId, x.TeachingTask.AcademicTermId })
.FirstOrDefaultAsync(cancellationToken);
if (sheetData is null)
{
job.Status = CourseGradeStatisticsRefreshJobStatus.Succeeded;
job.CompletedAt = DateTime.UtcNow;
await db.SaveChangesAsync(cancellationToken);
return;
}
var target = new StatisticsTarget(sheetData.CourseId, sheetData.AcademicTermId);
try
{
// Statistics shown to students are based only on formally published
// scores. This prevents an unfinished class from exposing data.
var scores = await db.GradeRecords.AsNoTracking()
.Where(x => x.TotalScore != null &&
x.GradeSheet!.Status == GradeSheetStatus.Published &&
x.GradeSheet.TeachingTask!.CourseId == target.CourseId &&
x.GradeSheet.TeachingTask.AcademicTermId == target.AcademicTermId)
.Select(x => new ScoreRow(
x.GradeSheetId,
x.GradeSheet!.TeachingTaskId,
x.TotalScore!.Value,
x.Student!.AdministrativeClassId,
x.Student.AdministrativeClass!.MajorId,
x.Student.AdministrativeClass.Major!.CollegeId))
.ToListAsync(cancellationToken);
var now = DateTime.UtcNow;
var rebuilt = new List<CourseGradeStatistic>();
AddStatistics(CourseGradeStatisticScope.AdministrativeClass,
scores.GroupBy(x => x.ClassId), rebuilt, target, now);
AddStatistics(CourseGradeStatisticScope.Major,
scores.GroupBy(x => x.MajorId), rebuilt, target, now);
AddStatistics(CourseGradeStatisticScope.College,
scores.GroupBy(x => x.CollegeId), rebuilt, target, now);
AddUniversityStatistic(scores, rebuilt, target, now);
var rebuiltTeachingTasks = scores
.GroupBy(x => new { x.GradeSheetId, x.TeachingTaskId })
.Select(group => CreateTeachingTaskStatistic(
group.Key.GradeSheetId,
group.Key.TeachingTaskId,
group.Select(x => x.Score),
target,
now))
.ToList();
await db.CourseGradeStatistics
.Where(x => x.CourseId == target.CourseId &&
x.AcademicTermId == target.AcademicTermId)
.ExecuteDeleteAsync(cancellationToken);
if (rebuilt.Count > 0)
db.CourseGradeStatistics.AddRange(rebuilt);
var oldTeachingTaskStatisticIds = await db.TeachingTaskGradeStatistics
.Where(x => x.CourseId == target.CourseId &&
x.AcademicTermId == target.AcademicTermId)
.Select(x => x.Id)
.ToListAsync(cancellationToken);
if (oldTeachingTaskStatisticIds.Count > 0)
{
await db.TeachingTaskGradeScoreBands
.Where(x => oldTeachingTaskStatisticIds.Contains(
x.TeachingTaskGradeStatisticId))
.ExecuteDeleteAsync(cancellationToken);
await db.TeachingTaskGradeStatistics
.Where(x => oldTeachingTaskStatisticIds.Contains(x.Id))
.ExecuteDeleteAsync(cancellationToken);
}
if (rebuiltTeachingTasks.Count > 0)
db.TeachingTaskGradeStatistics.AddRange(rebuiltTeachingTasks);
job.Status = CourseGradeStatisticsRefreshJobStatus.Succeeded;
job.CompletedAt = now;
await db.SaveChangesAsync(cancellationToken);
await cache.RemoveByTagAsync(AppCacheTags.CourseGradeStatistics,
cancellationToken);
}
catch (Exception exception)
{
job.Status = CourseGradeStatisticsRefreshJobStatus.Failed;
job.ErrorMessage = exception.GetBaseException().Message[..Math.Min(2000,
exception.GetBaseException().Message.Length)];
await db.SaveChangesAsync(CancellationToken.None);
logger.LogError(exception, "Course grade statistics refresh {JobId} failed.", jobId);
throw;
}
}
private static void AddStatistics(
CourseGradeStatisticScope scope,
IEnumerable<IGrouping<Guid, ScoreRow>> groups,
ICollection<CourseGradeStatistic> target,
StatisticsTarget targetInfo,
DateTime calculatedAt)
{
foreach (var group in groups)
target.Add(Create(scope, group.Key, group.Select(x => x.Score), targetInfo, calculatedAt));
}
private static void AddUniversityStatistic(
IReadOnlyCollection<ScoreRow> scores,
ICollection<CourseGradeStatistic> target,
StatisticsTarget targetInfo,
DateTime calculatedAt)
{
if (scores.Count > 0)
target.Add(Create(CourseGradeStatisticScope.University, null,
scores.Select(x => x.Score), targetInfo, calculatedAt));
}
private static CourseGradeStatistic Create(
CourseGradeStatisticScope scope,
Guid? scopeEntityId,
IEnumerable<decimal> source,
StatisticsTarget targetInfo,
DateTime calculatedAt)
{
var scores = source.ToArray();
var passed = scores.Count(x => x >= 60m);
return new CourseGradeStatistic
{
CourseId = targetInfo.CourseId,
AcademicTermId = targetInfo.AcademicTermId,
Scope = scope,
ScopeEntityId = scopeEntityId,
StudentCount = scores.Length,
PassedCount = passed,
Below60Count = scores.Count(x => x < 60m),
From60To69Count = scores.Count(x => x >= 60m && x < 70m),
From70To79Count = scores.Count(x => x >= 70m && x < 80m),
From80To89Count = scores.Count(x => x >= 80m && x < 90m),
From90To100Count = scores.Count(x => x >= 90m),
HighestScore = scores.Max(),
AverageScore = Math.Round(scores.Average(), 1),
LowestScore = scores.Min(),
PassRate = Math.Round((decimal)passed / scores.Length * 100m, 2),
CalculatedAt = calculatedAt
};
}
private static TeachingTaskGradeStatistic CreateTeachingTaskStatistic(
Guid gradeSheetId,
Guid teachingTaskId,
IEnumerable<decimal> source,
StatisticsTarget targetInfo,
DateTime calculatedAt)
{
var scores = source.OrderBy(x => x).ToArray();
var passed = scores.Count(x => x >= 60m);
var excellent = scores.Count(x => x >= 90m);
var average = scores.Average();
var middle = scores.Length / 2;
var median = scores.Length % 2 == 0
? (scores[middle - 1] + scores[middle]) / 2m
: scores[middle];
var variance = scores.Average(x =>
(double)((x - average) * (x - average)));
var statistic = new TeachingTaskGradeStatistic
{
GradeSheetId = gradeSheetId,
TeachingTaskId = teachingTaskId,
CourseId = targetInfo.CourseId,
AcademicTermId = targetInfo.AcademicTermId,
StudentCount = scores.Length,
PassedCount = passed,
ExcellentCount = excellent,
HighestScore = scores.Max(),
AverageScore = Math.Round(average, 1),
MedianScore = Math.Round(median, 1),
LowestScore = scores.Min(),
StandardDeviation = Math.Round((decimal)Math.Sqrt(variance), 2),
PassRate = Math.Round((decimal)passed / scores.Length * 100m, 2),
ExcellentRate = Math.Round((decimal)excellent / scores.Length * 100m, 2),
CalculatedAt = calculatedAt
};
statistic.ScoreBands =
[
CreateBand(statistic.Id, "059", 0m, 60m,
scores.Count(x => x < 60m), 0),
CreateBand(statistic.Id, "6069", 60m, 70m,
scores.Count(x => x >= 60m && x < 70m), 1),
CreateBand(statistic.Id, "7079", 70m, 80m,
scores.Count(x => x >= 70m && x < 80m), 2),
CreateBand(statistic.Id, "8089", 80m, 90m,
scores.Count(x => x >= 80m && x < 90m), 3),
CreateBand(statistic.Id, "90100", 90m, null,
scores.Count(x => x >= 90m), 4)
];
return statistic;
}
private static TeachingTaskGradeScoreBand CreateBand(
Guid statisticId,
string label,
decimal lowerBound,
decimal? upperBound,
int count,
int sortOrder) => new()
{
TeachingTaskGradeStatisticId = statisticId,
Label = label,
LowerBound = lowerBound,
UpperBound = upperBound,
StudentCount = count,
SortOrder = sortOrder
};
private sealed record ScoreRow(
Guid GradeSheetId,
Guid TeachingTaskId,
decimal Score,
Guid ClassId,
Guid MajorId,
Guid CollegeId);
private sealed record StatisticsTarget(Guid CourseId, Guid AcademicTermId);
}
@@ -5,13 +5,85 @@ namespace Jiaowu.Api.Infrastructure.Grades;
public static class ExperimentGradeAggregationService
{
public static async Task RefreshTeachingTaskAsync(
AppDbContext db,
Guid teachingTaskId,
CancellationToken cancellationToken)
{
var sheets = await LoadPublishedSheetsAsync(
db,
teachingTaskId,
cancellationToken);
var existing = await db.ExperimentCourseGrades
.Where(x => x.TeachingTaskId == teachingTaskId)
.ToDictionaryAsync(x => x.StudentId, cancellationToken);
var studentIds = sheets
.SelectMany(x => x.Scores.Select(score => score.StudentId))
.Distinct()
.ToArray();
var refreshedAt = DateTime.UtcNow;
var totalWeight = sheets.Sum(x => x.ContributionWeight);
foreach (var studentId in studentIds)
{
var score = CalculateStudentScore(sheets, studentId);
if (!existing.Remove(studentId, out var aggregate))
{
aggregate = new Domain.Academic.ExperimentCourseGrade
{
TeachingTaskId = teachingTaskId,
StudentId = studentId
};
db.ExperimentCourseGrades.Add(aggregate);
}
aggregate.WeightedAverageScore = score;
aggregate.TotalWeight = totalWeight;
aggregate.PublishedProjectCount = sheets.Count;
aggregate.RefreshedAt = refreshedAt;
}
db.ExperimentCourseGrades.RemoveRange(existing.Values);
await db.SaveChangesAsync(cancellationToken);
}
public static async Task<ExperimentGradeAggregateResult> CalculateAsync(
AppDbContext db,
Guid teachingTaskId,
IReadOnlyCollection<Guid> studentIds,
CancellationToken cancellationToken)
{
var sheets = await db.ExperimentGradeSheets.AsNoTracking()
var sheets = await LoadPublishedSheetsAsync(
db,
teachingTaskId,
cancellationToken);
var requestedStudentIds = studentIds.Distinct().ToArray();
var persistedScores = await db.ExperimentCourseGrades.AsNoTracking()
.Where(x =>
x.TeachingTaskId == teachingTaskId &&
requestedStudentIds.Contains(x.StudentId))
.ToDictionaryAsync(
x => x.StudentId,
x => x.WeightedAverageScore,
cancellationToken);
var scores = requestedStudentIds.ToDictionary(
studentId => studentId,
studentId => persistedScores.GetValueOrDefault(studentId));
return new ExperimentGradeAggregateResult(
sheets.Count,
sheets.Select(x => new ExperimentGradeAggregateProject(
x.Id,
x.Code,
x.Name,
x.ContributionWeight)).ToList(),
scores);
}
private static Task<List<PublishedExperimentSheet>> LoadPublishedSheetsAsync(
AppDbContext db,
Guid teachingTaskId,
CancellationToken cancellationToken) =>
db.ExperimentGradeSheets.AsNoTracking()
.Where(x =>
x.Status ==
Domain.Academic.ExperimentGradeSheetStatus.Published &&
@@ -28,25 +100,22 @@ public static class ExperimentGradeAggregationService
.AsSplitQuery()
.ToListAsync(cancellationToken);
var scores = new Dictionary<Guid, decimal?>();
foreach (var studentId in studentIds.Distinct())
private static decimal? CalculateStudentScore(
IReadOnlyCollection<PublishedExperimentSheet> sheets,
Guid studentId)
{
decimal weightedTotal = 0;
decimal totalWeight = 0;
var complete = sheets.Count > 0;
if (sheets.Count == 0) return null;
foreach (var sheet in sheets)
{
var score = sheet.Scores.FirstOrDefault(x =>
x.StudentId == studentId);
if (score?.TotalScore is not decimal totalScore)
{
complete = false;
break;
}
if (score?.TotalScore is not decimal totalScore) return null;
weightedTotal += totalScore * sheet.ContributionWeight;
totalWeight += sheet.ContributionWeight;
}
scores[studentId] = complete && totalWeight > 0
return totalWeight > 0
? Math.Round(
weightedTotal / totalWeight,
1,
@@ -54,16 +123,6 @@ public static class ExperimentGradeAggregationService
: null;
}
return new ExperimentGradeAggregateResult(
sheets.Count,
sheets.Select(x => new ExperimentGradeAggregateProject(
x.Id,
x.Code,
x.Name,
x.ContributionWeight)).ToList(),
scores);
}
private sealed record PublishedExperimentSheet(
Guid Id,
string Code,
@@ -0,0 +1,514 @@
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using Jiaowu.Api.Controllers;
using SkiaSharp;
using A = DocumentFormat.OpenXml.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;
using W = DocumentFormat.OpenXml.Wordprocessing;
namespace Jiaowu.Api.Infrastructure.Grades;
public static class GradeAnalysisWordReportGenerator
{
private const string Blue = "2E74B5";
private const string DarkBlue = "1F4D78";
private const string Ink = "263238";
private const string Muted = "68707A";
private const string LightFill = "F2F4F7";
private const int ContentWidth = 9360;
public static byte[] Generate(
GradeAnalyticsController.TeachingClassAnalysisReport report,
DateTime generatedAt)
{
ArgumentNullException.ThrowIfNull(report.Summary);
using var stream = new MemoryStream();
using (var document = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document, true))
{
document.PackageProperties.Title = $"{report.CourseName}成绩分析报告";
document.PackageProperties.Subject = "教学班成绩统计与对比分析";
document.PackageProperties.Creator = "教务管理系统";
document.PackageProperties.Created = generatedAt;
var mainPart = document.AddMainDocumentPart();
mainPart.Document = new Document(new Body());
var settingsPart = mainPart.AddNewPart<DocumentSettingsPart>();
settingsPart.Settings = new Settings(new EvenAndOddHeaders());
settingsPart.Settings.Save();
AddStyles(mainPart);
var headerFooterIds = AddHeaderAndFooter(mainPart);
BuildBody(mainPart, report, generatedAt, headerFooterIds);
mainPart.Document.Save();
}
return stream.ToArray();
}
private static void BuildBody(
MainDocumentPart mainPart,
GradeAnalyticsController.TeachingClassAnalysisReport report,
DateTime generatedAt,
HeaderFooterIds headerFooterIds)
{
var body = mainPart.Document?.Body
?? throw new InvalidOperationException("The report document body has not been initialized.");
var summary = report.Summary!;
body.Append(Paragraph("成绩分析报告", 46, true, "000000", 0, 80));
body.Append(Paragraph($"{report.CourseName} · {report.TaskName}", 28, false, Muted, 0, 220));
body.Append(MetadataTable([
("课程", $"{report.CourseCode} {report.CourseName}"),
("教学班", $"{report.TaskNumber} {report.TaskName}"),
("学期", report.TermName),
("报告生成", generatedAt.ToString("yyyy-MM-dd HH:mm")),
("统计更新", summary.CalculatedAt.ToLocalTime().ToString("yyyy-MM-dd HH:mm")),
("统计对象", $"{summary.StudentCount} 份已发布有效成绩")
]));
body.Append(Heading("一、分析摘要", 1));
body.Append(Callout(BuildExecutiveSummary(report)));
body.Append(MetricsTable(summary));
body.Append(Heading("二、分数段分布", 1));
body.Append(Paragraph("图 1 当前教学班各分数段人数", 20, false, Muted, 80, 80));
body.Append(ImageParagraph(mainPart, DrawScoreBands(summary.ScoreBands), "分数段分布图", 6.3, 3.0));
body.Append(DataTable(
["分数段", "下限", "上限", "人数", "占比"],
summary.ScoreBands.Select(x => new[]
{
x.Label,
x.LowerBound.ToString("0.#"),
x.UpperBound?.ToString("0.#") ?? "无上限",
x.StudentCount.ToString(),
Percent(x.StudentCount, summary.StudentCount)
}),
[1800, 1500, 1500, 1500, 3060]));
body.Append(Heading("三、同课程教学班对比", 1));
body.Append(Paragraph("图 2 同学期同课程各教学班平均分", 20, false, Muted, 80, 80));
var peerChartHeight = Math.Clamp(1.45 + report.PeerTeachingClasses.Count * 0.32, 1.8, 3.35);
body.Append(ImageParagraph(mainPart, DrawPeerAverages(report.PeerTeachingClasses), "教学班平均分对比图", 6.3, peerChartHeight));
body.Append(DataTable(
["教学班 / 教师", "人数", "平均分", "中位数", "标准差", "合格率", "优秀率"],
report.PeerTeachingClasses.Select(x => new[]
{
$"{x.TaskNumber}{(x.IsSelected ? "" : "")}\n{x.TeacherNames}",
x.StudentCount.ToString(),
Score(x.AverageScore),
Score(x.MedianScore),
x.StandardDeviation.ToString("0.00"),
Rate(x.PassRate),
Rate(x.ExcellentRate)
}),
[2600, 820, 1050, 1050, 1050, 1395, 1395]));
body.Append(Heading("四、各范围基准", 1));
body.Append(Paragraph("范围基准按当前课程、当前学期聚合;同一教学班包含多个来源行政班时,将分别列示可用基准。", 22, false, Muted, 0, 100));
body.Append(DataTable(
["范围", "对象", "人数", "最高分", "平均分", "最低分", "合格率"],
report.ScopeBenchmarks.Select(x => new[]
{
x.Scope, x.Name, x.StudentCount.ToString(), Score(x.HighestScore),
Score(x.AverageScore), Score(x.LowestScore), Rate(x.PassRate)
}),
[980, 2200, 900, 1200, 1200, 1200, 1680]));
body.Append(Heading("五、历年成绩趋势", 1));
body.Append(Paragraph("图 3 同课程全校与当前任课教师历年平均分", 20, false, Muted, 80, 80));
body.Append(ImageParagraph(mainPart, DrawHistory(report.History), "历年平均分趋势图", 6.3, 3.15));
body.Append(DataTable(
["学期", "全校人数", "全校平均", "全校合格率", "教师人数", "教师平均", "教师合格率"],
report.History.Select(x => new[]
{
x.TermName,
x.CourseStudentCount.ToString(),
Score(x.CourseAverageScore),
Rate(x.CoursePassRate),
x.Instructor?.StudentCount.ToString() ?? "—",
x.Instructor is null ? "—" : Score(x.Instructor.AverageScore),
x.Instructor is null ? "—" : Rate(x.Instructor.PassRate)
}),
[1700, 1050, 1200, 1450, 1050, 1200, 1710]));
body.Append(Heading("六、统计口径与使用说明", 1));
body.Append(Paragraph("1. 本报告仅统计已正式发布且纳入当前统计任务的有效成绩,不包含草稿、未发布成绩或学生逐人成绩明细。", 22, false, Ink, 0, 80));
body.Append(Paragraph("2. 合格率按成绩达到 60 分计算,优秀率按成绩达到 90 分计算;平均分、中位数和标准差均基于同一批有效成绩。", 22, false, Ink, 0, 80));
body.Append(Paragraph("3. 同课程教学班对比限定为当前学期;历年对比同时展示课程全校口径和当前任课教师所带教学班的加权汇总。", 22, false, Ink, 0, 80));
body.Append(Paragraph("4. 统计结果用于教学诊断和质量改进,不应脱离样本量、课程难度、考核方式等背景作单一排名或评价。", 22, false, Ink, 0, 80));
body.Append(new SectionProperties(
new HeaderReference { Type = HeaderFooterValues.Default, Id = headerFooterIds.DefaultHeader },
new HeaderReference { Type = HeaderFooterValues.Even, Id = headerFooterIds.EvenHeader },
new FooterReference { Type = HeaderFooterValues.Default, Id = headerFooterIds.DefaultFooter },
new FooterReference { Type = HeaderFooterValues.Even, Id = headerFooterIds.EvenFooter },
new PageSize { Width = 12240, Height = 15840 },
new PageMargin { Top = 1440, Right = 1440, Bottom = 1440, Left = 1440, Header = 708, Footer = 708 }));
}
private static string BuildExecutiveSummary(GradeAnalyticsController.TeachingClassAnalysisReport report)
{
var summary = report.Summary!;
var band = summary.ScoreBands.OrderByDescending(x => x.StudentCount).FirstOrDefault();
var parts = new List<string>
{
$"本教学班共纳入 {summary.StudentCount} 份有效成绩,平均分 {Score(summary.AverageScore)},中位数 {Score(summary.MedianScore)},合格率 {Rate(summary.PassRate)},优秀率 {Rate(summary.ExcellentRate)}。"
};
if (band is not null)
parts.Add($"人数最多的分数段为 {band.Label},共 {band.StudentCount} 人,占 {Percent(band.StudentCount, summary.StudentCount)}。 ");
if (report.UniversityDelta is { } delta)
parts.Add($"与本学期全校同课程相比,平均分{Direction(delta.AverageScoreDifference, "")},合格率{Direction(delta.PassRateDifference, "")}。 ");
parts.Add($"成绩标准差为 {summary.StandardDeviation:0.00},分数范围 {Score(summary.LowestScore)}{Score(summary.HighestScore)}。建议结合分数段、同课程教学班和历年趋势综合研判。 ");
return string.Concat(parts);
}
private static string Direction(decimal value, string unit) =>
value > 0 ? $"高 {value:0.0} {unit}" : value < 0 ? $"低 {Math.Abs(value):0.0} {unit}" : "持平";
private static W.Table MetadataTable(IEnumerable<(string Label, string Value)> items)
{
var rows = items.Select(x => new[] { x.Label, x.Value });
return DataTable(["项目", "内容"], rows, [1800, 7560], false);
}
private static W.Table MetricsTable(GradeAnalyticsController.TeachingClassMetrics value)
{
return DataTable(
["指标", "结果", "指标", "结果"],
[
["最高分", Score(value.HighestScore), "最低分", Score(value.LowestScore)],
["平均分", Score(value.AverageScore), "中位数", Score(value.MedianScore)],
["合格人数", $"{value.PassedCount} 人", "合格率", Rate(value.PassRate)],
["优秀人数", $"{value.ExcellentCount} 人", "优秀率", Rate(value.ExcellentRate)],
["标准差", value.StandardDeviation.ToString("0.00"), "有效成绩", $"{value.StudentCount} 份"]
],
[1800, 2880, 1800, 2880]);
}
private static W.Table DataTable(
IReadOnlyList<string> headers,
IEnumerable<string[]> rows,
IReadOnlyList<int> widths,
bool shadeHeader = true)
{
var table = new W.Table();
table.Append(new TableProperties(
new TableWidth { Width = ContentWidth.ToString(), Type = TableWidthUnitValues.Dxa },
new TableIndentation { Width = 120, Type = TableWidthUnitValues.Dxa },
new TableLayout { Type = TableLayoutValues.Fixed },
new TableBorders(
Border<TopBorder>(), Border<LeftBorder>(), Border<BottomBorder>(),
Border<RightBorder>(), Border<InsideHorizontalBorder>(), Border<InsideVerticalBorder>()),
new TableCellMarginDefault(
new TopMargin { Width = "80", Type = TableWidthUnitValues.Dxa },
new TableCellLeftMargin { Width = 120, Type = TableWidthValues.Dxa },
new BottomMargin { Width = "80", Type = TableWidthUnitValues.Dxa },
new TableCellRightMargin { Width = 120, Type = TableWidthValues.Dxa })));
table.Append(new TableGrid(widths.Select(x => new GridColumn { Width = x.ToString() })));
table.Append(Row(headers, widths, shadeHeader ? LightFill : "FFFFFF", true, true));
foreach (var row in rows)
table.Append(Row(row, widths, "FFFFFF", false, false));
return table;
}
private static TableRow Row(
IReadOnlyList<string> values,
IReadOnlyList<int> widths,
string fill,
bool bold,
bool repeat)
{
var row = new TableRow();
if (repeat) row.AppendChild(new TableRowProperties(new TableHeader()));
for (var i = 0; i < widths.Count; i++)
{
var cell = new TableCell();
cell.Append(new TableCellProperties(
new TableCellWidth { Width = widths[i].ToString(), Type = TableWidthUnitValues.Dxa },
new Shading { Fill = fill, Val = ShadingPatternValues.Clear }));
var lines = (i < values.Count ? values[i] : "").Split('\n');
foreach (var line in lines)
cell.Append(Paragraph(line, 19, bold, Ink, 0, 0));
row.Append(cell);
}
return row;
}
private static T Border<T>() where T : BorderType, new() =>
new() { Val = BorderValues.Single, Color = "D6DBE1", Size = 4 };
private static W.Table Callout(string text)
{
return DataTable(["核心结论"], [[text]], [ContentWidth]);
}
private static Paragraph Heading(string text, int level)
{
var paragraph = new Paragraph(new ParagraphProperties(new ParagraphStyleId { Val = $"Heading{level}" }));
paragraph.Append(Run(text, level == 1 ? 32 : 26, true, level == 1 ? Blue : DarkBlue));
return paragraph;
}
private static Paragraph Paragraph(
string text,
int size,
bool bold,
string color,
int before,
int after)
{
var paragraph = new Paragraph(new ParagraphProperties(
new SpacingBetweenLines { Before = before.ToString(), After = after.ToString(), Line = "264", LineRule = LineSpacingRuleValues.Auto }));
paragraph.Append(Run(text, size, bold, color));
return paragraph;
}
private static Run Run(string text, int size, bool bold, string color)
{
return new Run(
new RunProperties(
new RunFonts { Ascii = "Calibri", HighAnsi = "Calibri", EastAsia = "Microsoft YaHei" },
new Bold { Val = bold },
new Color { Val = color },
new FontSize { Val = size.ToString() },
new FontSizeComplexScript { Val = size.ToString() }),
new Text(text) { Space = SpaceProcessingModeValues.Preserve });
}
private static Paragraph ImageParagraph(
MainDocumentPart mainPart,
byte[] image,
string description,
double widthInches,
double heightInches)
{
var part = mainPart.AddImagePart(ImagePartType.Png);
using (var stream = new MemoryStream(image)) part.FeedData(stream);
var relationshipId = mainPart.GetIdOfPart(part);
var width = (long)(widthInches * 914400L);
var height = (long)(heightInches * 914400L);
var drawing = new W.Drawing(
new DW.Inline(
new DW.Extent { Cx = width, Cy = height },
new DW.EffectExtent { LeftEdge = 0, TopEdge = 0, RightEdge = 0, BottomEdge = 0 },
new DW.DocProperties { Id = (UInt32Value)(uint)(mainPart.ImageParts.Count()), Name = description, Description = description },
new DW.NonVisualGraphicFrameDrawingProperties(new A.GraphicFrameLocks { NoChangeAspect = true }),
new A.Graphic(new A.GraphicData(
new PIC.Picture(
new PIC.NonVisualPictureProperties(
new PIC.NonVisualDrawingProperties { Id = 0, Name = description, Description = description },
new PIC.NonVisualPictureDrawingProperties()),
new PIC.BlipFill(
new A.Blip { Embed = relationshipId, CompressionState = A.BlipCompressionValues.Print },
new A.Stretch(new A.FillRectangle())),
new PIC.ShapeProperties(
new A.Transform2D(
new A.Offset { X = 0, Y = 0 },
new A.Extents { Cx = width, Cy = height }),
new A.PresetGeometry(new A.AdjustValueList()) { Preset = A.ShapeTypeValues.Rectangle })))
{ Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" }))
{ DistanceFromTop = 0, DistanceFromBottom = 0, DistanceFromLeft = 0, DistanceFromRight = 0 });
var paragraph = new Paragraph(new ParagraphProperties(
new Justification { Val = JustificationValues.Center },
new SpacingBetweenLines { Before = "0", After = "120" }));
paragraph.Append(new Run(drawing));
return paragraph;
}
private static void AddStyles(MainDocumentPart mainPart)
{
var stylesPart = mainPart.AddNewPart<StyleDefinitionsPart>();
var normal = new Style(
new StyleName { Val = "Normal" },
new StyleRunProperties(
new RunFonts { Ascii = "Calibri", HighAnsi = "Calibri", EastAsia = "Microsoft YaHei" },
new FontSize { Val = "22" }, new Color { Val = Ink }),
new StyleParagraphProperties(
new SpacingBetweenLines { Before = "0", After = "120", Line = "264", LineRule = LineSpacingRuleValues.Auto }))
{ Type = StyleValues.Paragraph, StyleId = "Normal", Default = true };
var h1 = new Style(
new StyleName { Val = "heading 1" },
new BasedOn { Val = "Normal" },
new NextParagraphStyle { Val = "Normal" },
new StyleRunProperties(new RunFonts { Ascii = "Calibri", HighAnsi = "Calibri", EastAsia = "Microsoft YaHei" }, new Bold(), new Color { Val = Blue }, new FontSize { Val = "32" }),
new StyleParagraphProperties(new KeepNext(), new SpacingBetweenLines { Before = "320", After = "160" }))
{ Type = StyleValues.Paragraph, StyleId = "Heading1" };
stylesPart.Styles = new Styles(normal, h1);
stylesPart.Styles.Save();
}
private static HeaderFooterIds AddHeaderAndFooter(MainDocumentPart mainPart)
{
var defaultHeader = mainPart.AddNewPart<HeaderPart>();
defaultHeader.Header = CreateHeader();
defaultHeader.Header.Save();
var evenHeader = mainPart.AddNewPart<HeaderPart>();
evenHeader.Header = CreateHeader();
evenHeader.Header.Save();
var defaultFooter = mainPart.AddNewPart<FooterPart>();
defaultFooter.Footer = CreateFooter();
defaultFooter.Footer.Save();
var evenFooter = mainPart.AddNewPart<FooterPart>();
evenFooter.Footer = CreateFooter();
evenFooter.Footer.Save();
return new HeaderFooterIds(
mainPart.GetIdOfPart(defaultHeader),
mainPart.GetIdOfPart(evenHeader),
mainPart.GetIdOfPart(defaultFooter),
mainPart.GetIdOfPart(evenFooter));
}
private static Header CreateHeader() =>
new(Paragraph("成绩分析报告 | 教务管理系统", 18, false, Muted, 0, 0));
private static Footer CreateFooter()
{
var footerParagraph = new Paragraph(new ParagraphProperties(new Justification { Val = JustificationValues.Right }));
footerParagraph.Append(Run("第 ", 18, false, Muted));
footerParagraph.Append(new Run(new FieldChar { FieldCharType = FieldCharValues.Begin }));
footerParagraph.Append(new Run(new FieldCode(" PAGE ")));
footerParagraph.Append(new Run(new FieldChar { FieldCharType = FieldCharValues.End }));
footerParagraph.Append(Run(" 页", 18, false, Muted));
return new Footer(footerParagraph);
}
private static byte[] DrawScoreBands(IReadOnlyList<GradeAnalyticsController.ScoreBand> rows)
{
return DrawChart(1200, 540, (canvas, typeface) =>
{
DrawAxes(canvas, typeface, "人数", 70, 35, 1080, 430);
var max = Math.Max(1, rows.Max(x => x.StudentCount));
var barWidth = 150f;
var gap = (1000f - rows.Count * barWidth) / Math.Max(1, rows.Count);
for (var i = 0; i < rows.Count; i++)
{
var x = 105 + gap / 2 + i * (barWidth + gap);
var height = rows[i].StudentCount / (float)max * 330;
using var paint = new SKPaint { Color = new SKColor(46, 116, 181), IsAntialias = true };
canvas.DrawRoundRect(new SKRect(x, 430 - height, x + barWidth, 430), 8, 8, paint);
DrawText(canvas, typeface, rows[i].StudentCount.ToString(), x + barWidth / 2, 415 - height, 24, Ink, SKTextAlign.Center, true);
DrawText(canvas, typeface, rows[i].Label, x + barWidth / 2, 475, 18, Muted, SKTextAlign.Center);
}
});
}
private static byte[] DrawPeerAverages(IReadOnlyList<GradeAnalyticsController.TeachingClassComparison> rows)
{
var visible = rows.Take(8).ToArray();
var height = Math.Max(250, 120 + visible.Length * 62);
return DrawChart(1200, height, (canvas, typeface) =>
{
var top = 55f;
var rowHeight = 62f;
DrawText(canvas, typeface, "0", 280, 40, 20, Muted, SKTextAlign.Center);
DrawText(canvas, typeface, "50", 700, 40, 20, Muted, SKTextAlign.Center);
DrawText(canvas, typeface, "100", 1120, 40, 20, Muted, SKTextAlign.Center);
for (var i = 0; i < visible.Length; i++)
{
var y = top + i * rowHeight;
var value = Math.Clamp((float)visible[i].AverageScore, 0, 100);
DrawText(canvas, typeface, visible[i].TaskNumber, 245, y + 28, 21, visible[i].IsSelected ? Blue : Ink, SKTextAlign.Right, visible[i].IsSelected);
using var track = new SKPaint { Color = new SKColor(235, 239, 244) };
using var fill = new SKPaint { Color = visible[i].IsSelected ? new SKColor(46, 116, 181) : new SKColor(155, 177, 202) };
canvas.DrawRoundRect(new SKRect(280, y, 1120, y + 34), 6, 6, track);
canvas.DrawRoundRect(new SKRect(280, y, 280 + value / 100 * 840, y + 34), 6, 6, fill);
DrawText(canvas, typeface, value.ToString("0.0"), 290 + value / 100 * 840, y + 27, 20, Ink, SKTextAlign.Left, true);
}
});
}
private static byte[] DrawHistory(IReadOnlyList<GradeAnalyticsController.HistoricalComparison> rows)
{
return DrawChart(1200, 570, (canvas, typeface) =>
{
DrawAxes(canvas, typeface, "平均分", 70, 35, 1080, 430);
if (rows.Count == 0) return;
var min = 0f;
var max = 100f;
var points = rows.Select((x, i) => new SKPoint(
110 + (rows.Count == 1 ? 480 : i * 950f / (rows.Count - 1)),
430 - ((float)x.CourseAverageScore - min) / (max - min) * 350)).ToArray();
DrawLineSeries(canvas, typeface, points, rows.Select(x => x.CourseAverageScore).ToArray(), new SKColor(46, 116, 181));
var teacher = rows.Select((x, i) => x.Instructor is null ? (SKPoint?)null : new SKPoint(
110 + (rows.Count == 1 ? 480 : i * 950f / (rows.Count - 1)),
430 - ((float)x.Instructor.AverageScore - min) / (max - min) * 350)).ToArray();
DrawOptionalLineSeries(canvas, typeface, teacher, rows.Select(x => x.Instructor?.AverageScore).ToArray(), new SKColor(211, 133, 45));
for (var i = 0; i < rows.Count; i++)
DrawText(canvas, typeface, rows[i].TermName, points[i].X, 480, 20, Muted, SKTextAlign.Center);
using var blue = new SKPaint { Color = new SKColor(46, 116, 181), StrokeWidth = 4 };
using var gold = new SKPaint { Color = new SKColor(211, 133, 45), StrokeWidth = 4 };
canvas.DrawLine(760, 520, 805, 520, blue);
canvas.DrawLine(940, 520, 985, 520, gold);
DrawText(canvas, typeface, "同课程全校", 815, 528, 20, Ink);
DrawText(canvas, typeface, "当前任课教师", 995, 528, 20, Ink);
});
}
private static byte[] DrawChart(int width, int height, Action<SKCanvas, SKTypeface> draw)
{
using var bitmap = new SKBitmap(width, height);
using var canvas = new SKCanvas(bitmap);
canvas.Clear(SKColors.White);
using var typeface = SKTypeface.FromFamilyName("Microsoft YaHei") ?? SKTypeface.Default;
draw(canvas, typeface);
using var image = SKImage.FromBitmap(bitmap);
using var data = image.Encode(SKEncodedImageFormat.Png, 92);
return data.ToArray();
}
private static void DrawAxes(SKCanvas canvas, SKTypeface typeface, string label, float left, float top, float right, float bottom)
{
using var axis = new SKPaint { Color = new SKColor(190, 198, 207), StrokeWidth = 2 };
canvas.DrawLine(left, bottom, right, bottom, axis);
canvas.DrawLine(left, top, left, bottom, axis);
DrawText(canvas, typeface, label, left, 25, 21, Muted);
}
private static void DrawLineSeries(SKCanvas canvas, SKTypeface typeface, SKPoint[] points, decimal[] values, SKColor color)
{
using var paint = new SKPaint { Color = color, StrokeWidth = 4, IsAntialias = true, Style = SKPaintStyle.Stroke };
using var fill = new SKPaint { Color = color, IsAntialias = true };
using var builder = new SKPathBuilder();
builder.MoveTo(points[0]);
foreach (var point in points.Skip(1)) builder.LineTo(point);
using var path = builder.Detach();
canvas.DrawPath(path, paint);
for (var i = 0; i < points.Length; i++)
{
canvas.DrawCircle(points[i], 7, fill);
DrawText(canvas, typeface, values[i].ToString("0.0"), points[i].X, points[i].Y - 14, 19, Ink, SKTextAlign.Center, true);
}
}
private static void DrawOptionalLineSeries(SKCanvas canvas, SKTypeface typeface, SKPoint?[] points, decimal?[] values, SKColor color)
{
var available = points.Select((point, index) => (point, index)).Where(x => x.point.HasValue).ToArray();
if (available.Length == 0) return;
using var paint = new SKPaint { Color = color, StrokeWidth = 4, IsAntialias = true, Style = SKPaintStyle.Stroke };
using var fill = new SKPaint { Color = color, IsAntialias = true };
for (var i = 1; i < available.Length; i++) canvas.DrawLine(available[i - 1].point!.Value, available[i].point!.Value, paint);
foreach (var item in available)
{
var point = item.point!.Value;
canvas.DrawCircle(point, 7, fill);
DrawText(canvas, typeface, values[item.index]!.Value.ToString("0.0"), point.X, point.Y + 28, 19, Ink, SKTextAlign.Center, true);
}
}
private static void DrawText(SKCanvas canvas, SKTypeface typeface, string text, float x, float y, float size, string color, SKTextAlign align = SKTextAlign.Left, bool bold = false)
{
using var font = new SKFont(typeface, size) { Embolden = bold };
using var paint = new SKPaint { Color = SKColor.Parse(color), IsAntialias = true };
canvas.DrawText(text, x, y, align, font, paint);
}
private static string Score(decimal value) => value.ToString("0.0");
private static string Rate(decimal value) => $"{value:0.0}%";
private static string Percent(int value, int total) => total == 0 ? "0.0%" : $"{(decimal)value / total * 100m:0.0}%";
private sealed record HeaderFooterIds(
string DefaultHeader,
string EvenHeader,
string DefaultFooter,
string EvenFooter);
}
@@ -26,6 +26,8 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
public DbSet<CurriculumPlan> CurriculumPlans => Set<CurriculumPlan>();
public DbSet<CurriculumModule> CurriculumModules => Set<CurriculumModule>();
public DbSet<CurriculumCourse> CurriculumCourses => Set<CurriculumCourse>();
public DbSet<CourseGroup> CourseGroups => Set<CourseGroup>();
public DbSet<CourseGroupCourse> CourseGroupCourses => Set<CourseGroupCourse>();
public DbSet<TeachingTask> TeachingTasks => Set<TeachingTask>();
public DbSet<TeachingTaskTeacher> TeachingTaskTeachers => Set<TeachingTaskTeacher>();
public DbSet<TeachingTaskClass> TeachingTaskClasses => Set<TeachingTaskClass>();
@@ -33,11 +35,14 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
Set<TeacherCourseApplication>();
public DbSet<SchedulePlan> SchedulePlans => Set<SchedulePlan>();
public DbSet<ScheduleEntry> ScheduleEntries => Set<ScheduleEntry>();
public DbSet<PublishedScheduleOccurrence> PublishedScheduleOccurrences => Set<PublishedScheduleOccurrence>();
public DbSet<ScheduleTimeSlot> ScheduleTimeSlots => Set<ScheduleTimeSlot>();
public DbSet<TeachingTaskScheduleConstraint> TeachingTaskScheduleConstraints =>
Set<TeachingTaskScheduleConstraint>();
public DbSet<TeachingTaskAllowedClassroom> TeachingTaskAllowedClassrooms =>
Set<TeachingTaskAllowedClassroom>();
public DbSet<TeachingTaskAllowedExperimentClassroom> TeachingTaskAllowedExperimentClassrooms =>
Set<TeachingTaskAllowedExperimentClassroom>();
public DbSet<AutomaticScheduleJob> AutomaticScheduleJobs =>
Set<AutomaticScheduleJob>();
public DbSet<SchedulePublishJob> SchedulePublishJobs =>
@@ -53,6 +58,8 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
Set<ExperimentGradeItem>();
public DbSet<ExperimentGradeRecord> ExperimentGradeRecords =>
Set<ExperimentGradeRecord>();
public DbSet<ExperimentCourseGrade> ExperimentCourseGrades =>
Set<ExperimentCourseGrade>();
public DbSet<ExperimentGradeItemScore> ExperimentGradeItemScores =>
Set<ExperimentGradeItemScore>();
public DbSet<CourseSelectionRound> CourseSelectionRounds =>
@@ -66,6 +73,16 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
public DbSet<GradeRecord> GradeRecords => Set<GradeRecord>();
public DbSet<GradeItem> GradeItems => Set<GradeItem>();
public DbSet<GradeItemScore> GradeItemScores => Set<GradeItemScore>();
public DbSet<CourseGradeStatistic> CourseGradeStatistics =>
Set<CourseGradeStatistic>();
public DbSet<TeachingTaskGradeStatistic> TeachingTaskGradeStatistics =>
Set<TeachingTaskGradeStatistic>();
public DbSet<TeachingTaskGradeScoreBand> TeachingTaskGradeScoreBands =>
Set<TeachingTaskGradeScoreBand>();
public DbSet<CourseGradeStatisticsRefreshJob> CourseGradeStatisticsRefreshJobs =>
Set<CourseGradeStatisticsRefreshJob>();
public DbSet<OtherExamBatch> OtherExamBatches => Set<OtherExamBatch>();
public DbSet<OtherExamResult> OtherExamResults => Set<OtherExamResult>();
public DbSet<AttendanceSheet> AttendanceSheets => Set<AttendanceSheet>();
public DbSet<AttendanceRecord> AttendanceRecords => Set<AttendanceRecord>();
public DbSet<AttendanceCheckInAttempt> AttendanceCheckInAttempts =>
@@ -127,6 +144,10 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
Set<BackgroundJobOutboxMessage>();
public DbSet<AppUpdateRelease> AppUpdateReleases =>
Set<AppUpdateRelease>();
public DbSet<SystemFeatureSetting> SystemFeatureSettings =>
Set<SystemFeatureSetting>();
public DbSet<CourseGradeStatisticsRefreshSetting> CourseGradeStatisticsRefreshSettings =>
Set<CourseGradeStatisticsRefreshSetting>();
public DbSet<RefreshSession> RefreshSessions => Set<RefreshSession>();
protected override void ConfigureConventions(
@@ -450,7 +471,8 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
builder.Entity<ScheduleEntry>(entity =>
{
entity.Property(x => x.Kind)
.HasDefaultValue(ScheduleEntryKind.Lecture);
.HasDefaultValue(ScheduleEntryKind.Lecture)
.HasSentinel((ScheduleEntryKind)0);
entity.Property(x => x.Notes).HasMaxLength(500);
entity.HasIndex(x => new
{
@@ -498,6 +520,14 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
.WithMany()
.HasForeignKey(x => x.RequiredBuildingId)
.OnDelete(DeleteBehavior.Restrict);
entity.HasOne(x => x.ExperimentRequiredCampus)
.WithMany()
.HasForeignKey(x => x.ExperimentRequiredCampusId)
.OnDelete(DeleteBehavior.Restrict);
entity.HasOne(x => x.ExperimentRequiredBuilding)
.WithMany()
.HasForeignKey(x => x.ExperimentRequiredBuildingId)
.OnDelete(DeleteBehavior.Restrict);
});
builder.Entity<TeachingTaskAllowedClassroom>(entity =>
@@ -517,6 +547,57 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
.OnDelete(DeleteBehavior.Restrict);
});
builder.Entity<CourseGroup>(entity =>
{
entity.Property(x => x.Code).HasMaxLength(30);
entity.Property(x => x.Name).HasMaxLength(100);
entity.Property(x => x.Description).HasMaxLength(500);
entity.HasIndex(x => x.Code).IsUnique();
});
builder.Entity<CourseGroupCourse>(entity =>
{
entity.HasIndex(x => new { x.CourseGroupId, x.CourseId }).IsUnique();
entity.HasOne(x => x.CourseGroup)
.WithMany(x => x.Courses)
.HasForeignKey(x => x.CourseGroupId)
.OnDelete(DeleteBehavior.Cascade);
entity.HasOne(x => x.Course)
.WithMany()
.HasForeignKey(x => x.CourseId)
.OnDelete(DeleteBehavior.Restrict);
});
builder.Entity<PublishedScheduleOccurrence>(entity =>
{
entity.HasIndex(x => new { x.AcademicTermId, x.TeachingTaskId, x.Week });
entity.HasIndex(x => new
{
x.AcademicTermId,
x.Week,
x.DayOfWeek,
x.StartPeriod,
x.ClassroomId
});
entity.HasIndex(x => new { x.SchedulePlanId, x.ClassroomId, x.Week, x.DayOfWeek, x.StartPeriod });
entity.HasIndex(x => new { x.ScheduleEntryId, x.Week }).IsUnique();
entity.HasOne(x => x.ScheduleEntry).WithMany().HasForeignKey(x => x.ScheduleEntryId).OnDelete(DeleteBehavior.Cascade);
entity.HasOne(x => x.TeachingTask).WithMany().HasForeignKey(x => x.TeachingTaskId).OnDelete(DeleteBehavior.Restrict);
entity.HasOne(x => x.Classroom).WithMany().HasForeignKey(x => x.ClassroomId).OnDelete(DeleteBehavior.SetNull);
});
builder.Entity<TeachingTaskAllowedExperimentClassroom>(entity =>
{
entity.HasKey(x => new { x.TeachingTaskScheduleConstraintId, x.ClassroomId });
entity.HasOne(x => x.TeachingTaskScheduleConstraint)
.WithMany(x => x.AllowedExperimentClassrooms)
.HasForeignKey(x => x.TeachingTaskScheduleConstraintId)
.OnDelete(DeleteBehavior.Cascade);
entity.HasOne(x => x.Classroom)
.WithMany()
.HasForeignKey(x => x.ClassroomId)
.OnDelete(DeleteBehavior.Restrict);
});
builder.Entity<AutomaticScheduleJob>(entity =>
{
entity.Property(x => x.ErrorMessage).HasMaxLength(2000);
@@ -601,11 +682,24 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
entity.Property(x => x.Name).HasMaxLength(120);
entity.Property(x => x.Description).HasMaxLength(1000);
entity.Property(x => x.Requirements).HasMaxLength(1000);
entity.HasIndex(x => new { x.TeachingTaskId, x.Code }).IsUnique();
// 集中安排会为同一教学任务的每一条实验课表记录生成项目;
// 自行安排仍由控制器保持“教学任务 + 编码”唯一。
entity.HasIndex(x => new
{
x.TeachingTaskId,
x.Code,
x.ScheduleEntryId,
x.ScheduleWeek
})
.IsUnique();
entity.HasIndex(x => new { x.Status, x.StartDate, x.EndDate });
entity.HasOne(x => x.TeachingTask).WithMany()
.HasForeignKey(x => x.TeachingTaskId)
.OnDelete(DeleteBehavior.Restrict);
entity.HasIndex(x => x.ScheduleEntryId);
entity.HasOne(x => x.ScheduleEntry).WithMany()
.HasForeignKey(x => x.ScheduleEntryId)
.OnDelete(DeleteBehavior.Restrict);
});
builder.Entity<ExperimentSession>(entity =>
@@ -703,6 +797,21 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
.OnDelete(DeleteBehavior.Restrict);
});
builder.Entity<ExperimentCourseGrade>(entity =>
{
entity.Property(x => x.WeightedAverageScore).HasPrecision(5, 1);
entity.Property(x => x.TotalWeight).HasPrecision(8, 1);
entity.HasIndex(x => new { x.TeachingTaskId, x.StudentId })
.IsUnique();
entity.HasIndex(x => x.StudentId);
entity.HasOne(x => x.TeachingTask).WithMany()
.HasForeignKey(x => x.TeachingTaskId)
.OnDelete(DeleteBehavior.Cascade);
entity.HasOne(x => x.Student).WithMany()
.HasForeignKey(x => x.StudentId)
.OnDelete(DeleteBehavior.Restrict);
});
builder.Entity<ExperimentGradeItemScore>(entity =>
{
entity.HasKey(x => new
@@ -802,7 +911,8 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
entity.Property(x => x.Name).HasMaxLength(60);
entity.Property(x => x.Weight).HasPrecision(5, 1);
entity.Property(x => x.SourceType)
.HasDefaultValue(GradeItemSourceType.Manual);
.HasDefaultValue(GradeItemSourceType.Manual)
.HasSentinel((GradeItemSourceType)0);
entity.HasIndex(x => new { x.GradeSheetId, x.SortOrder });
entity.HasOne(x => x.GradeSheet)
.WithMany(x => x.Items)
@@ -843,6 +953,72 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
.OnDelete(DeleteBehavior.Restrict);
});
builder.Entity<CourseGradeStatistic>(entity =>
{
entity.Property(x => x.HighestScore).HasPrecision(5, 1);
entity.Property(x => x.AverageScore).HasPrecision(5, 1);
entity.Property(x => x.LowestScore).HasPrecision(5, 1);
entity.Property(x => x.PassRate).HasPrecision(5, 2);
entity.HasIndex(x => new
{
x.CourseId, x.AcademicTermId, x.Scope, x.ScopeEntityId
}).IsUnique().HasDatabaseName("UX_CourseGradeStatistics_Scope");
entity.HasIndex(x => new { x.AcademicTermId, x.Scope, x.ScopeEntityId });
entity.HasOne<Course>().WithMany().HasForeignKey(x => x.CourseId)
.OnDelete(DeleteBehavior.Restrict);
entity.HasOne<AcademicTerm>().WithMany().HasForeignKey(x => x.AcademicTermId)
.OnDelete(DeleteBehavior.Restrict);
});
builder.Entity<TeachingTaskGradeStatistic>(entity =>
{
entity.Property(x => x.HighestScore).HasPrecision(5, 1);
entity.Property(x => x.AverageScore).HasPrecision(5, 1);
entity.Property(x => x.MedianScore).HasPrecision(5, 1);
entity.Property(x => x.LowestScore).HasPrecision(5, 1);
entity.Property(x => x.StandardDeviation).HasPrecision(6, 2);
entity.Property(x => x.PassRate).HasPrecision(5, 2);
entity.Property(x => x.ExcellentRate).HasPrecision(5, 2);
entity.HasIndex(x => x.GradeSheetId).IsUnique();
entity.HasIndex(x => x.TeachingTaskId).IsUnique();
entity.HasIndex(x => new { x.CourseId, x.AcademicTermId });
entity.HasOne(x => x.GradeSheet).WithOne()
.HasForeignKey<TeachingTaskGradeStatistic>(x => x.GradeSheetId)
.OnDelete(DeleteBehavior.Cascade);
entity.HasOne(x => x.TeachingTask).WithOne()
.HasForeignKey<TeachingTaskGradeStatistic>(x => x.TeachingTaskId)
.OnDelete(DeleteBehavior.Cascade);
entity.HasOne<Course>().WithMany().HasForeignKey(x => x.CourseId)
.OnDelete(DeleteBehavior.Restrict);
entity.HasOne<AcademicTerm>().WithMany().HasForeignKey(x => x.AcademicTermId)
.OnDelete(DeleteBehavior.Restrict);
});
builder.Entity<TeachingTaskGradeScoreBand>(entity =>
{
entity.Property(x => x.Label).HasMaxLength(30);
entity.Property(x => x.LowerBound).HasPrecision(5, 1);
entity.Property(x => x.UpperBound).HasPrecision(5, 1);
entity.HasIndex(x => new
{
x.TeachingTaskGradeStatisticId,
x.SortOrder
}).IsUnique();
entity.HasOne(x => x.TeachingTaskGradeStatistic)
.WithMany(x => x.ScoreBands)
.HasForeignKey(x => x.TeachingTaskGradeStatisticId)
.OnDelete(DeleteBehavior.Cascade);
});
builder.Entity<CourseGradeStatisticsRefreshJob>(entity =>
{
entity.Property(x => x.ErrorMessage).HasMaxLength(2000);
entity.HasIndex(x => new { x.Status, x.CreatedAt });
entity.HasIndex(x => x.GradeSheetId);
entity.HasOne<GradeSheet>().WithMany().HasForeignKey(x => x.GradeSheetId)
.OnDelete(DeleteBehavior.Cascade);
});
builder.Entity<AttendanceSheet>(entity =>
{
entity.Property(x => x.Name).HasMaxLength(120);
@@ -1186,6 +1362,27 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
entity.HasOne(x => x.GradeRecord).WithMany()
.HasForeignKey(x => x.GradeRecordId).OnDelete(DeleteBehavior.Restrict);
});
builder.Entity<OtherExamBatch>(entity =>
{
entity.Property(x => x.ExamCode).HasMaxLength(60);
entity.Property(x => x.Name).HasMaxLength(150);
entity.Property(x => x.Organizer).HasMaxLength(150);
entity.Property(x => x.LevelOptions).HasMaxLength(500);
entity.Property(x => x.MaxScore).HasPrecision(8, 2);
entity.HasIndex(x => new { x.Status, x.ExamDate });
});
builder.Entity<OtherExamResult>(entity =>
{
entity.Property(x => x.Score).HasPrecision(8, 2);
entity.Property(x => x.Level).HasMaxLength(50);
entity.Property(x => x.Notes).HasMaxLength(500);
entity.HasIndex(x => new { x.OtherExamBatchId, x.StudentId, x.AttemptNumber }).IsUnique();
entity.HasIndex(x => new { x.StudentId, x.OtherExamBatchId });
entity.HasOne(x => x.OtherExamBatch).WithMany(x => x.Results)
.HasForeignKey(x => x.OtherExamBatchId).OnDelete(DeleteBehavior.Cascade);
entity.HasOne(x => x.Student).WithMany()
.HasForeignKey(x => x.StudentId).OnDelete(DeleteBehavior.Restrict);
});
builder.Entity<WarningRule>(entity =>
{
entity.Property(x => x.Name).HasMaxLength(100);
@@ -1352,6 +1549,18 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
entity.HasIndex(x => x.CreatedAt);
});
builder.Entity<SystemFeatureSetting>(entity =>
{
entity.Property(x => x.Key).HasMaxLength(100);
entity.HasIndex(x => x.Key).IsUnique();
});
builder.Entity<CourseGradeStatisticsRefreshSetting>(entity =>
{
entity.Property(x => x.Key).HasMaxLength(50);
entity.HasIndex(x => x.Key).IsUnique();
});
builder.Entity<OfficialDocument>(entity =>
{
entity.Property(x => x.DocumentNumber).HasMaxLength(50);
@@ -82,6 +82,26 @@ public sealed class DevelopmentSqliteMigrator(
"20260803_43_refresh_sessions";
private const string StudentPersonalProfileMigration =
"20260803_44_student_personal_profile";
private const string OtherExamResultsMigration =
"20260808_45_other_exam_results";
private const string CourseGradeStatisticsMigration =
"20260808_46_course_grade_statistics";
private const string CourseGradeDistributionMigration =
"20260809_47_course_grade_distribution";
private const string TeachingTaskGradeAnalyticsMigration =
"20260809_48_teaching_task_grade_analytics";
private const string SwaggerDocumentationSettingMigration =
"20260809_49_swagger_documentation_setting";
private const string ExperimentClassroomConstraintsMigration =
"20260809_50_experiment_classroom_constraints";
private const string SeparateExperimentClassroomScopeMigration =
"20260809_51_separate_experiment_classroom_scope";
private const string ReusableCourseGroupsMigration =
"20260809_52_reusable_course_groups";
private const string CourseGradeStatisticsRefreshSettingsMigration =
"20260809_53_course_grade_statistics_refresh_settings";
private const string ExperimentCourseGradesMigration =
"20260809_54_experiment_course_grades";
public async Task MigrateAsync(CancellationToken cancellationToken = default)
{
@@ -613,6 +633,104 @@ public sealed class DevelopmentSqliteMigrator(
StudentPersonalProfileMigration,
studentPersonalProfileExists ? [] : StudentPersonalProfileStatements,
cancellationToken);
var otherExamCodeExists = await db.Database
.SqlQueryRaw<int>(
"""
SELECT COUNT(*) AS "Value"
FROM pragma_table_info('OtherExamBatches')
WHERE name = 'ExamCode'
""")
.AnyAsync(value => value > 0, cancellationToken);
var otherExamBatchExists = await db.Database
.SqlQueryRaw<int>(
"""
SELECT COUNT(*) AS "Value"
FROM sqlite_master
WHERE type = 'table' AND name = 'OtherExamBatches'
""")
.AnyAsync(value => value > 0, cancellationToken);
await ApplyMigrationAsync(
OtherExamResultsMigration,
!otherExamBatchExists
? OtherExamResultsStatements.Skip(1)
: otherExamCodeExists
? OtherExamResultsStatements.Skip(1)
: OtherExamResultsStatements,
cancellationToken);
await ApplyMigrationAsync(
CourseGradeStatisticsMigration,
CourseGradeStatisticsStatements,
cancellationToken);
var courseGradeStatisticColumns = (await db.Database
.SqlQueryRaw<string>(
"""
SELECT name AS "Value"
FROM pragma_table_info('CourseGradeStatistics')
""")
.ToListAsync(cancellationToken))
.ToHashSet(StringComparer.OrdinalIgnoreCase);
var missingDistributionStatements = CourseGradeDistributionColumns
.Select((column, index) => new { column, index })
.Where(x => !courseGradeStatisticColumns.Contains(x.column))
.Select(x => CourseGradeDistributionStatements[x.index]);
await ApplyMigrationAsync(
CourseGradeDistributionMigration,
missingDistributionStatements,
cancellationToken);
await ApplyMigrationAsync(
TeachingTaskGradeAnalyticsMigration,
TeachingTaskGradeAnalyticsStatements,
cancellationToken);
var gradeRefreshSettingsExist = await db.Database
.SqlQueryRaw<int>(
"SELECT COUNT(*) AS \"Value\" FROM sqlite_master WHERE type = 'table' AND name = 'CourseGradeStatisticsRefreshSettings'")
.AnyAsync(value => value > 0, cancellationToken);
await ApplyMigrationAsync(
CourseGradeStatisticsRefreshSettingsMigration,
gradeRefreshSettingsExist ? [] : CourseGradeStatisticsRefreshSettingsStatements,
cancellationToken);
var swaggerSettingsExist = await db.Database
.SqlQueryRaw<int>(
"SELECT COUNT(*) AS \"Value\" FROM sqlite_master WHERE type = 'table' AND name = 'SystemFeatureSettings'")
.AnyAsync(value => value > 0, cancellationToken);
await ApplyMigrationAsync(
SwaggerDocumentationSettingMigration,
swaggerSettingsExist ? [] : SwaggerDocumentationSettingStatements,
cancellationToken);
var experimentClassroomConstraintsExist = await db.Database
.SqlQueryRaw<int>(
"SELECT COUNT(*) AS \"Value\" FROM sqlite_master WHERE type = 'table' AND name = 'TeachingTaskAllowedExperimentClassrooms'")
.AnyAsync(value => value > 0, cancellationToken);
await ApplyMigrationAsync(
ExperimentClassroomConstraintsMigration,
experimentClassroomConstraintsExist ? [] : ExperimentClassroomConstraintStatements,
cancellationToken);
var experimentScopeColumns = (await db.Database.SqlQueryRaw<string>(
"SELECT name AS \"Value\" FROM pragma_table_info('TeachingTaskScheduleConstraints')")
.ToListAsync(cancellationToken))
.ToHashSet(StringComparer.OrdinalIgnoreCase);
await ApplyMigrationAsync(
SeparateExperimentClassroomScopeMigration,
experimentScopeColumns.Contains("ExperimentRequiredCampusId")
? []
: SeparateExperimentClassroomScopeStatements,
cancellationToken);
var courseGroupsExist = await db.Database
.SqlQueryRaw<int>(
"SELECT COUNT(*) AS \"Value\" FROM sqlite_master WHERE type = 'table' AND name = 'CourseGroups'")
.AnyAsync(value => value > 0, cancellationToken);
await ApplyMigrationAsync(
ReusableCourseGroupsMigration,
courseGroupsExist ? [] : ReusableCourseGroupsStatements,
cancellationToken);
var experimentCourseGradesExist = await db.Database
.SqlQueryRaw<int>(
"SELECT COUNT(*) AS \"Value\" FROM sqlite_master WHERE type = 'table' AND name = 'ExperimentCourseGrades'")
.AnyAsync(value => value > 0, cancellationToken);
await ApplyMigrationAsync(
ExperimentCourseGradesMigration,
experimentCourseGradesExist ? [] : ExperimentCourseGradesStatements,
cancellationToken);
}
private async Task ApplyMigrationAsync(
@@ -2173,6 +2291,56 @@ public sealed class DevelopmentSqliteMigrator(
"""ALTER TABLE "Students" ADD COLUMN "WeChat" TEXT NULL;"""
];
private static readonly string[] OtherExamResultsStatements =
[
"""ALTER TABLE "OtherExamBatches" ADD COLUMN "ExamCode" TEXT NULL;""",
"""CREATE TABLE IF NOT EXISTS "OtherExamBatches" ("Id" TEXT NOT NULL CONSTRAINT "PK_OtherExamBatches" PRIMARY KEY, "ExamCode" TEXT NULL, "Name" TEXT NOT NULL, "Organizer" TEXT NULL, "ExamDate" TEXT NOT NULL, "MetricKind" INTEGER NOT NULL, "MaxScore" TEXT NULL, "LevelOptions" TEXT NULL, "Status" INTEGER NOT NULL, "PublicationCount" INTEGER NOT NULL, "PublishedAt" TEXT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL);""",
"""CREATE INDEX IF NOT EXISTS "IX_OtherExamBatches_Status_ExamDate" ON "OtherExamBatches" ("Status", "ExamDate");""",
"""CREATE TABLE IF NOT EXISTS "OtherExamResults" ("Id" TEXT NOT NULL CONSTRAINT "PK_OtherExamResults" PRIMARY KEY, "OtherExamBatchId" TEXT NOT NULL, "StudentId" TEXT NOT NULL, "AttemptNumber" INTEGER NOT NULL, "Score" TEXT NULL, "Level" TEXT NULL, "IsPassed" INTEGER NULL, "Notes" TEXT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, CONSTRAINT "FK_OtherExamResults_OtherExamBatches" FOREIGN KEY ("OtherExamBatchId") REFERENCES "OtherExamBatches" ("Id") ON DELETE CASCADE, CONSTRAINT "FK_OtherExamResults_Students" FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id") ON DELETE RESTRICT);""",
"""DROP INDEX IF EXISTS "IX_OtherExamResults_OtherExamBatchId_StudentId_AttemptNumber";""",
"""CREATE UNIQUE INDEX IF NOT EXISTS "IX_OtherExamResults_OtherExamBatchId_StudentId" ON "OtherExamResults" ("OtherExamBatchId", "StudentId");""",
"""CREATE INDEX IF NOT EXISTS "IX_OtherExamResults_StudentId_OtherExamBatchId" ON "OtherExamResults" ("StudentId", "OtherExamBatchId");"""
];
private static readonly string[] CourseGradeStatisticsStatements =
[
"""CREATE TABLE IF NOT EXISTS "CourseGradeStatistics" ("Id" TEXT NOT NULL CONSTRAINT "PK_CourseGradeStatistics" PRIMARY KEY, "CourseId" TEXT NOT NULL, "AcademicTermId" TEXT NOT NULL, "Scope" INTEGER NOT NULL, "ScopeEntityId" TEXT NULL, "StudentCount" INTEGER NOT NULL, "PassedCount" INTEGER NOT NULL, "HighestScore" TEXT NOT NULL, "AverageScore" TEXT NOT NULL, "LowestScore" TEXT NOT NULL, "PassRate" TEXT NOT NULL, "CalculatedAt" TEXT NOT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, CONSTRAINT "FK_CourseGradeStatistics_Courses_CourseId" FOREIGN KEY ("CourseId") REFERENCES "Courses" ("Id") ON DELETE RESTRICT, CONSTRAINT "FK_CourseGradeStatistics_AcademicTerms_AcademicTermId" FOREIGN KEY ("AcademicTermId") REFERENCES "AcademicTerms" ("Id") ON DELETE RESTRICT);""",
"""CREATE UNIQUE INDEX IF NOT EXISTS "UX_CourseGradeStatistics_Scope" ON "CourseGradeStatistics" ("CourseId", "AcademicTermId", "Scope", "ScopeEntityId");""",
"""CREATE INDEX IF NOT EXISTS "IX_CourseGradeStatistics_AcademicTermId_Scope_ScopeEntityId" ON "CourseGradeStatistics" ("AcademicTermId", "Scope", "ScopeEntityId");""",
"""CREATE TABLE IF NOT EXISTS "CourseGradeStatisticsRefreshJobs" ("Id" TEXT NOT NULL CONSTRAINT "PK_CourseGradeStatisticsRefreshJobs" PRIMARY KEY, "GradeSheetId" TEXT NOT NULL, "Status" INTEGER NOT NULL, "StartedAt" TEXT NULL, "CompletedAt" TEXT NULL, "ErrorMessage" TEXT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, CONSTRAINT "FK_CourseGradeStatisticsRefreshJobs_GradeSheets_GradeSheetId" FOREIGN KEY ("GradeSheetId") REFERENCES "GradeSheets" ("Id") ON DELETE CASCADE);""",
"""CREATE INDEX IF NOT EXISTS "IX_CourseGradeStatisticsRefreshJobs_GradeSheetId" ON "CourseGradeStatisticsRefreshJobs" ("GradeSheetId");""",
"""CREATE INDEX IF NOT EXISTS "IX_CourseGradeStatisticsRefreshJobs_Status_CreatedAt" ON "CourseGradeStatisticsRefreshJobs" ("Status", "CreatedAt");"""
];
private static readonly string[] CourseGradeDistributionStatements =
[
"""ALTER TABLE "CourseGradeStatistics" ADD COLUMN "Below60Count" INTEGER NOT NULL DEFAULT 0;""",
"""ALTER TABLE "CourseGradeStatistics" ADD COLUMN "From60To69Count" INTEGER NOT NULL DEFAULT 0;""",
"""ALTER TABLE "CourseGradeStatistics" ADD COLUMN "From70To79Count" INTEGER NOT NULL DEFAULT 0;""",
"""ALTER TABLE "CourseGradeStatistics" ADD COLUMN "From80To89Count" INTEGER NOT NULL DEFAULT 0;""",
"""ALTER TABLE "CourseGradeStatistics" ADD COLUMN "From90To100Count" INTEGER NOT NULL DEFAULT 0;"""
];
private static readonly string[] CourseGradeDistributionColumns =
[
"Below60Count",
"From60To69Count",
"From70To79Count",
"From80To89Count",
"From90To100Count"
];
private static readonly string[] TeachingTaskGradeAnalyticsStatements =
[
"""CREATE TABLE IF NOT EXISTS "TeachingTaskGradeStatistics" ("Id" TEXT NOT NULL CONSTRAINT "PK_TeachingTaskGradeStatistics" PRIMARY KEY, "GradeSheetId" TEXT NOT NULL, "TeachingTaskId" TEXT NOT NULL, "CourseId" TEXT NOT NULL, "AcademicTermId" TEXT NOT NULL, "StudentCount" INTEGER NOT NULL, "PassedCount" INTEGER NOT NULL, "ExcellentCount" INTEGER NOT NULL, "HighestScore" TEXT NOT NULL, "AverageScore" TEXT NOT NULL, "MedianScore" TEXT NOT NULL, "LowestScore" TEXT NOT NULL, "StandardDeviation" TEXT NOT NULL, "PassRate" TEXT NOT NULL, "ExcellentRate" TEXT NOT NULL, "CalculatedAt" TEXT NOT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, CONSTRAINT "FK_TeachingTaskGradeStatistics_GradeSheets" FOREIGN KEY ("GradeSheetId") REFERENCES "GradeSheets" ("Id") ON DELETE CASCADE, CONSTRAINT "FK_TeachingTaskGradeStatistics_TeachingTasks" FOREIGN KEY ("TeachingTaskId") REFERENCES "TeachingTasks" ("Id") ON DELETE CASCADE, CONSTRAINT "FK_TeachingTaskGradeStatistics_Courses" FOREIGN KEY ("CourseId") REFERENCES "Courses" ("Id") ON DELETE RESTRICT, CONSTRAINT "FK_TeachingTaskGradeStatistics_AcademicTerms" FOREIGN KEY ("AcademicTermId") REFERENCES "AcademicTerms" ("Id") ON DELETE RESTRICT);""",
"""CREATE UNIQUE INDEX IF NOT EXISTS "IX_TeachingTaskGradeStatistics_GradeSheetId" ON "TeachingTaskGradeStatistics" ("GradeSheetId");""",
"""CREATE UNIQUE INDEX IF NOT EXISTS "IX_TeachingTaskGradeStatistics_TeachingTaskId" ON "TeachingTaskGradeStatistics" ("TeachingTaskId");""",
"""CREATE INDEX IF NOT EXISTS "IX_TeachingTaskGradeStatistics_CourseId_AcademicTermId" ON "TeachingTaskGradeStatistics" ("CourseId", "AcademicTermId");""",
"""CREATE INDEX IF NOT EXISTS "IX_TeachingTaskGradeStatistics_AcademicTermId" ON "TeachingTaskGradeStatistics" ("AcademicTermId");""",
"""CREATE TABLE IF NOT EXISTS "TeachingTaskGradeScoreBands" ("Id" TEXT NOT NULL CONSTRAINT "PK_TeachingTaskGradeScoreBands" PRIMARY KEY, "TeachingTaskGradeStatisticId" TEXT NOT NULL, "Label" TEXT NOT NULL, "LowerBound" TEXT NOT NULL, "UpperBound" TEXT NULL, "StudentCount" INTEGER NOT NULL, "SortOrder" INTEGER NOT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, CONSTRAINT "FK_TeachingTaskGradeScoreBands_Statistics" FOREIGN KEY ("TeachingTaskGradeStatisticId") REFERENCES "TeachingTaskGradeStatistics" ("Id") ON DELETE CASCADE);""",
"""CREATE UNIQUE INDEX IF NOT EXISTS "IX_TeachingTaskGradeScoreBands_StatisticId_SortOrder" ON "TeachingTaskGradeScoreBands" ("TeachingTaskGradeStatisticId", "SortOrder");"""
];
private static readonly string[] ApprovalTableStatements =
[
"""CREATE TABLE "CourseExemptions" ("Id" TEXT NOT NULL CONSTRAINT "PK_CourseExemptions" PRIMARY KEY, "StudentId" TEXT NOT NULL, "TeachingTaskId" TEXT NOT NULL, "Reason" TEXT NOT NULL, "Status" INTEGER NOT NULL, "ReviewComment" TEXT NULL, "SubmittedAt" TEXT NOT NULL, "ReviewedAt" TEXT NULL, "ReviewedByUserId" TEXT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, CONSTRAINT "FK_CourseExemptions_Students" FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id") ON DELETE RESTRICT, CONSTRAINT "FK_CourseExemptions_TeachingTasks" FOREIGN KEY ("TeachingTaskId") REFERENCES "TeachingTasks" ("Id") ON DELETE RESTRICT);""",
@@ -2807,4 +2975,179 @@ public sealed class DevelopmentSqliteMigrator(
ADD COLUMN "Kind" INTEGER NOT NULL DEFAULT 1;
"""
];
private static readonly string[] SwaggerDocumentationSettingStatements =
[
"""
CREATE TABLE "SystemFeatureSettings" (
"Id" TEXT NOT NULL CONSTRAINT "PK_SystemFeatureSettings" PRIMARY KEY,
"Key" TEXT NOT NULL,
"IsEnabled" INTEGER NOT NULL,
"CreatedAt" TEXT NOT NULL,
"UpdatedAt" TEXT NOT NULL
);
""",
"""
CREATE UNIQUE INDEX "IX_SystemFeatureSettings_Key"
ON "SystemFeatureSettings" ("Key");
"""
];
private static readonly string[] CourseGradeStatisticsRefreshSettingsStatements =
[
"""CREATE TABLE IF NOT EXISTS "CourseGradeStatisticsRefreshSettings" ("Id" TEXT NOT NULL CONSTRAINT "PK_CourseGradeStatisticsRefreshSettings" PRIMARY KEY, "Key" TEXT NOT NULL, "IsEnabled" INTEGER NOT NULL, "IntervalSeconds" INTEGER NOT NULL, "BatchSize" INTEGER NOT NULL, "LastRunAt" TEXT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL);""",
"""CREATE UNIQUE INDEX IF NOT EXISTS "IX_CourseGradeStatisticsRefreshSettings_Key" ON "CourseGradeStatisticsRefreshSettings" ("Key");"""
];
private static readonly string[] ExperimentCourseGradesStatements =
[
"""
CREATE TABLE "ExperimentCourseGrades" (
"Id" TEXT NOT NULL CONSTRAINT "PK_ExperimentCourseGrades" PRIMARY KEY,
"TeachingTaskId" TEXT NOT NULL,
"StudentId" TEXT NOT NULL,
"WeightedAverageScore" TEXT NULL,
"TotalWeight" TEXT NOT NULL,
"PublishedProjectCount" INTEGER NOT NULL,
"RefreshedAt" TEXT NOT NULL,
"CreatedAt" TEXT NOT NULL,
"UpdatedAt" TEXT NOT NULL,
CONSTRAINT "FK_ExperimentCourseGrades_TeachingTasks_TeachingTaskId"
FOREIGN KEY ("TeachingTaskId") REFERENCES "TeachingTasks" ("Id") ON DELETE CASCADE,
CONSTRAINT "FK_ExperimentCourseGrades_Students_StudentId"
FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id") ON DELETE RESTRICT
);
""",
"""CREATE INDEX "IX_ExperimentCourseGrades_StudentId" ON "ExperimentCourseGrades" ("StudentId");""",
"""CREATE UNIQUE INDEX "IX_ExperimentCourseGrades_TeachingTaskId_StudentId" ON "ExperimentCourseGrades" ("TeachingTaskId", "StudentId");""",
"""
INSERT INTO "ExperimentCourseGrades"
("Id", "TeachingTaskId", "StudentId", "WeightedAverageScore",
"TotalWeight", "PublishedProjectCount", "RefreshedAt",
"CreatedAt", "UpdatedAt")
SELECT
lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-' ||
'4' || substr(lower(hex(randomblob(2))), 2) || '-' ||
substr('89ab', abs(random()) % 4 + 1, 1) ||
substr(lower(hex(randomblob(2))), 2) || '-' || lower(hex(randomblob(6))),
project."TeachingTaskId",
record."StudentId",
CASE
WHEN COUNT(*) = (
SELECT COUNT(*)
FROM "ExperimentGradeSheets" AS all_sheet
INNER JOIN "ExperimentProjects" AS all_project
ON all_project."Id" = all_sheet."ExperimentProjectId"
WHERE all_sheet."Status" = 4
AND all_project."TeachingTaskId" = project."TeachingTaskId")
AND SUM(CASE WHEN record."TotalScore" IS NULL THEN 1 ELSE 0 END) = 0
THEN ROUND(
SUM(record."TotalScore" * sheet."ContributionWeight") /
SUM(sheet."ContributionWeight"), 1)
ELSE NULL
END,
(
SELECT COALESCE(SUM(all_sheet."ContributionWeight"), 0)
FROM "ExperimentGradeSheets" AS all_sheet
INNER JOIN "ExperimentProjects" AS all_project
ON all_project."Id" = all_sheet."ExperimentProjectId"
WHERE all_sheet."Status" = 4
AND all_project."TeachingTaskId" = project."TeachingTaskId"),
(
SELECT COUNT(*)
FROM "ExperimentGradeSheets" AS all_sheet
INNER JOIN "ExperimentProjects" AS all_project
ON all_project."Id" = all_sheet."ExperimentProjectId"
WHERE all_sheet."Status" = 4
AND all_project."TeachingTaskId" = project."TeachingTaskId"),
strftime('%Y-%m-%d %H:%M:%f', 'now'),
strftime('%Y-%m-%d %H:%M:%f', 'now'),
strftime('%Y-%m-%d %H:%M:%f', 'now')
FROM "ExperimentGradeRecords" AS record
INNER JOIN "ExperimentGradeSheets" AS sheet
ON sheet."Id" = record."ExperimentGradeSheetId"
INNER JOIN "ExperimentProjects" AS project
ON project."Id" = sheet."ExperimentProjectId"
WHERE sheet."Status" = 4
GROUP BY project."TeachingTaskId", record."StudentId";
"""
];
private static readonly string[] ExperimentClassroomConstraintStatements =
[
"""
CREATE TABLE "TeachingTaskAllowedExperimentClassrooms" (
"TeachingTaskScheduleConstraintId" TEXT NOT NULL,
"ClassroomId" TEXT NOT NULL,
CONSTRAINT "PK_TeachingTaskAllowedExperimentClassrooms"
PRIMARY KEY ("TeachingTaskScheduleConstraintId", "ClassroomId"),
CONSTRAINT "FK_TeachingTaskAllowedExperimentClassrooms_Constraints"
FOREIGN KEY ("TeachingTaskScheduleConstraintId")
REFERENCES "TeachingTaskScheduleConstraints" ("Id") ON DELETE CASCADE,
CONSTRAINT "FK_TeachingTaskAllowedExperimentClassrooms_Classrooms"
FOREIGN KEY ("ClassroomId") REFERENCES "Classrooms" ("Id") ON DELETE RESTRICT
);
""",
"""
CREATE INDEX "IX_TeachingTaskAllowedExperimentClassrooms_ClassroomId"
ON "TeachingTaskAllowedExperimentClassrooms" ("ClassroomId");
"""
];
private static readonly string[] SeparateExperimentClassroomScopeStatements =
[
"""
ALTER TABLE "TeachingTaskScheduleConstraints"
ADD COLUMN "ExperimentRequiredCampusId" TEXT NULL;
""",
"""
ALTER TABLE "TeachingTaskScheduleConstraints"
ADD COLUMN "ExperimentRequiredBuildingId" TEXT NULL;
""",
"""
CREATE INDEX "IX_TeachingTaskScheduleConstraints_ExperimentRequiredCampusId"
ON "TeachingTaskScheduleConstraints" ("ExperimentRequiredCampusId");
""",
"""
CREATE INDEX "IX_TeachingTaskScheduleConstraints_ExperimentRequiredBuildingId"
ON "TeachingTaskScheduleConstraints" ("ExperimentRequiredBuildingId");
"""
];
private static readonly string[] ReusableCourseGroupsStatements =
[
"""
CREATE TABLE "CourseGroups" (
"Id" TEXT NOT NULL CONSTRAINT "PK_CourseGroups" PRIMARY KEY,
"Code" TEXT NOT NULL,
"Name" TEXT NOT NULL,
"Description" TEXT NULL,
"CreatedAt" TEXT NOT NULL,
"UpdatedAt" TEXT NOT NULL
);
""",
"""
CREATE UNIQUE INDEX "IX_CourseGroups_Code" ON "CourseGroups" ("Code");
""",
"""
CREATE TABLE "CourseGroupCourses" (
"Id" TEXT NOT NULL CONSTRAINT "PK_CourseGroupCourses" PRIMARY KEY,
"CourseGroupId" TEXT NOT NULL,
"CourseId" TEXT NOT NULL,
"CreatedAt" TEXT NOT NULL,
"UpdatedAt" TEXT NOT NULL,
CONSTRAINT "FK_CourseGroupCourses_CourseGroups_CourseGroupId"
FOREIGN KEY ("CourseGroupId") REFERENCES "CourseGroups" ("Id") ON DELETE CASCADE,
CONSTRAINT "FK_CourseGroupCourses_Courses_CourseId"
FOREIGN KEY ("CourseId") REFERENCES "Courses" ("Id") ON DELETE RESTRICT
);
""",
"""
CREATE UNIQUE INDEX "IX_CourseGroupCourses_CourseGroupId_CourseId"
ON "CourseGroupCourses" ("CourseGroupId", "CourseId");
""",
"""
CREATE INDEX "IX_CourseGroupCourses_CourseId" ON "CourseGroupCourses" ("CourseId");
"""
];
}
@@ -0,0 +1,97 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
/// <inheritdoc />
public partial class OtherExamResults : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "OtherExamBatches",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
Name = table.Column<string>(type: "varchar(150)", maxLength: 150, nullable: false),
Organizer = table.Column<string>(type: "varchar(150)", maxLength: 150, nullable: true),
ExamDate = table.Column<DateTime>(type: "date", nullable: false),
MetricKind = table.Column<int>(type: "int", nullable: false),
MaxScore = table.Column<decimal>(type: "decimal(8,2)", precision: 8, scale: 2, nullable: true),
LevelOptions = table.Column<string>(type: "varchar(500)", maxLength: 500, nullable: true),
Status = table.Column<int>(type: "int", nullable: false),
PublicationCount = table.Column<int>(type: "int", nullable: false),
PublishedAt = table.Column<DateTime>(type: "datetime(6)", nullable: true),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_OtherExamBatches", x => x.Id);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "OtherExamResults",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
OtherExamBatchId = table.Column<Guid>(type: "char(36)", nullable: false),
StudentId = table.Column<Guid>(type: "char(36)", nullable: false),
AttemptNumber = table.Column<int>(type: "int", nullable: false),
Score = table.Column<decimal>(type: "decimal(8,2)", precision: 8, scale: 2, nullable: true),
Level = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true),
IsPassed = table.Column<bool>(type: "tinyint(1)", nullable: true),
Notes = table.Column<string>(type: "varchar(500)", maxLength: 500, nullable: true),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_OtherExamResults", x => x.Id);
table.ForeignKey(
name: "FK_OtherExamResults_OtherExamBatches_OtherExamBatchId",
column: x => x.OtherExamBatchId,
principalTable: "OtherExamBatches",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_OtherExamResults_Students_StudentId",
column: x => x.StudentId,
principalTable: "Students",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_OtherExamBatches_Status_ExamDate",
table: "OtherExamBatches",
columns: new[] { "Status", "ExamDate" });
migrationBuilder.CreateIndex(
name: "IX_OtherExamResults_OtherExamBatchId_StudentId_AttemptNumber",
table: "OtherExamResults",
columns: new[] { "OtherExamBatchId", "StudentId", "AttemptNumber" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_OtherExamResults_StudentId_OtherExamBatchId",
table: "OtherExamResults",
columns: new[] { "StudentId", "OtherExamBatchId" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "OtherExamResults");
migrationBuilder.DropTable(
name: "OtherExamBatches");
}
}
}
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
/// <inheritdoc />
public partial class OtherExamIdentityAndImport : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "ExamCode",
table: "OtherExamBatches",
type: "varchar(60)",
maxLength: 60,
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "ExamCode",
table: "OtherExamBatches");
}
}
}
@@ -0,0 +1,113 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
/// <inheritdoc />
public partial class CourseGradeStatistics : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "CourseGradeStatistics",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
CourseId = table.Column<Guid>(type: "char(36)", nullable: false),
AcademicTermId = table.Column<Guid>(type: "char(36)", nullable: false),
Scope = table.Column<int>(type: "int", nullable: false),
ScopeEntityId = table.Column<Guid>(type: "char(36)", nullable: true),
StudentCount = table.Column<int>(type: "int", nullable: false),
PassedCount = table.Column<int>(type: "int", nullable: false),
Below60Count = table.Column<int>(type: "int", nullable: false),
From60To69Count = table.Column<int>(type: "int", nullable: false),
From70To79Count = table.Column<int>(type: "int", nullable: false),
From80To89Count = table.Column<int>(type: "int", nullable: false),
From90To100Count = table.Column<int>(type: "int", nullable: false),
HighestScore = table.Column<decimal>(type: "decimal(5,1)", precision: 5, scale: 1, nullable: false),
AverageScore = table.Column<decimal>(type: "decimal(5,1)", precision: 5, scale: 1, nullable: false),
LowestScore = table.Column<decimal>(type: "decimal(5,1)", precision: 5, scale: 1, nullable: false),
PassRate = table.Column<decimal>(type: "decimal(5,2)", precision: 5, scale: 2, nullable: false),
CalculatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_CourseGradeStatistics", x => x.Id);
table.ForeignKey(
name: "FK_CourseGradeStatistics_AcademicTerms_AcademicTermId",
column: x => x.AcademicTermId,
principalTable: "AcademicTerms",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_CourseGradeStatistics_Courses_CourseId",
column: x => x.CourseId,
principalTable: "Courses",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "CourseGradeStatisticsRefreshJobs",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
GradeSheetId = table.Column<Guid>(type: "char(36)", nullable: false),
Status = table.Column<int>(type: "int", nullable: false),
StartedAt = table.Column<DateTime>(type: "datetime(6)", nullable: true),
CompletedAt = table.Column<DateTime>(type: "datetime(6)", nullable: true),
ErrorMessage = table.Column<string>(type: "varchar(2000)", maxLength: 2000, nullable: true),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_CourseGradeStatisticsRefreshJobs", x => x.Id);
table.ForeignKey(
name: "FK_CourseGradeStatisticsRefreshJobs_GradeSheets_GradeSheetId",
column: x => x.GradeSheetId,
principalTable: "GradeSheets",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_CourseGradeStatistics_AcademicTermId_Scope_ScopeEntityId",
table: "CourseGradeStatistics",
columns: new[] { "AcademicTermId", "Scope", "ScopeEntityId" });
migrationBuilder.CreateIndex(
name: "UX_CourseGradeStatistics_Scope",
table: "CourseGradeStatistics",
columns: new[] { "CourseId", "AcademicTermId", "Scope", "ScopeEntityId" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_CourseGradeStatisticsRefreshJobs_GradeSheetId",
table: "CourseGradeStatisticsRefreshJobs",
column: "GradeSheetId");
migrationBuilder.CreateIndex(
name: "IX_CourseGradeStatisticsRefreshJobs_Status_CreatedAt",
table: "CourseGradeStatisticsRefreshJobs",
columns: new[] { "Status", "CreatedAt" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "CourseGradeStatistics");
migrationBuilder.DropTable(
name: "CourseGradeStatisticsRefreshJobs");
}
}
}
@@ -0,0 +1,132 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
/// <inheritdoc />
public partial class TeachingTaskGradeAnalytics : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "TeachingTaskGradeStatistics",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
GradeSheetId = table.Column<Guid>(type: "char(36)", nullable: false),
TeachingTaskId = table.Column<Guid>(type: "char(36)", nullable: false),
CourseId = table.Column<Guid>(type: "char(36)", nullable: false),
AcademicTermId = table.Column<Guid>(type: "char(36)", nullable: false),
StudentCount = table.Column<int>(type: "int", nullable: false),
PassedCount = table.Column<int>(type: "int", nullable: false),
ExcellentCount = table.Column<int>(type: "int", nullable: false),
HighestScore = table.Column<decimal>(type: "decimal(5,1)", precision: 5, scale: 1, nullable: false),
AverageScore = table.Column<decimal>(type: "decimal(5,1)", precision: 5, scale: 1, nullable: false),
MedianScore = table.Column<decimal>(type: "decimal(5,1)", precision: 5, scale: 1, nullable: false),
LowestScore = table.Column<decimal>(type: "decimal(5,1)", precision: 5, scale: 1, nullable: false),
StandardDeviation = table.Column<decimal>(type: "decimal(6,2)", precision: 6, scale: 2, nullable: false),
PassRate = table.Column<decimal>(type: "decimal(5,2)", precision: 5, scale: 2, nullable: false),
ExcellentRate = table.Column<decimal>(type: "decimal(5,2)", precision: 5, scale: 2, nullable: false),
CalculatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_TeachingTaskGradeStatistics", x => x.Id);
table.ForeignKey(
name: "FK_TeachingTaskGradeStatistics_AcademicTerms_AcademicTermId",
column: x => x.AcademicTermId,
principalTable: "AcademicTerms",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_TeachingTaskGradeStatistics_Courses_CourseId",
column: x => x.CourseId,
principalTable: "Courses",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_TeachingTaskGradeStatistics_GradeSheets_GradeSheetId",
column: x => x.GradeSheetId,
principalTable: "GradeSheets",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_TeachingTaskGradeStatistics_TeachingTasks_TeachingTaskId",
column: x => x.TeachingTaskId,
principalTable: "TeachingTasks",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "TeachingTaskGradeScoreBands",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
TeachingTaskGradeStatisticId = table.Column<Guid>(type: "char(36)", nullable: false),
Label = table.Column<string>(type: "varchar(30)", maxLength: 30, nullable: false),
LowerBound = table.Column<decimal>(type: "decimal(5,1)", precision: 5, scale: 1, nullable: false),
UpperBound = table.Column<decimal>(type: "decimal(5,1)", precision: 5, scale: 1, nullable: true),
StudentCount = table.Column<int>(type: "int", nullable: false),
SortOrder = table.Column<int>(type: "int", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_TeachingTaskGradeScoreBands", x => x.Id);
table.ForeignKey(
name: "FK_TeachingTaskGradeScoreBands_TeachingTaskGradeStatistics_Teac~",
column: x => x.TeachingTaskGradeStatisticId,
principalTable: "TeachingTaskGradeStatistics",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_TeachingTaskGradeScoreBands_TeachingTaskGradeStatisticId_Sor~",
table: "TeachingTaskGradeScoreBands",
columns: new[] { "TeachingTaskGradeStatisticId", "SortOrder" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_TeachingTaskGradeStatistics_AcademicTermId",
table: "TeachingTaskGradeStatistics",
column: "AcademicTermId");
migrationBuilder.CreateIndex(
name: "IX_TeachingTaskGradeStatistics_CourseId_AcademicTermId",
table: "TeachingTaskGradeStatistics",
columns: new[] { "CourseId", "AcademicTermId" });
migrationBuilder.CreateIndex(
name: "IX_TeachingTaskGradeStatistics_GradeSheetId",
table: "TeachingTaskGradeStatistics",
column: "GradeSheetId",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_TeachingTaskGradeStatistics_TeachingTaskId",
table: "TeachingTaskGradeStatistics",
column: "TeachingTaskId",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "TeachingTaskGradeScoreBands");
migrationBuilder.DropTable(
name: "TeachingTaskGradeStatistics");
}
}
}
@@ -0,0 +1,50 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
/// <inheritdoc />
public partial class BindCentralizedExperimentProjectsToSchedules : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<Guid>(
name: "ScheduleEntryId",
table: "ExperimentProjects",
type: "char(36)",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_ExperimentProjects_ScheduleEntryId",
table: "ExperimentProjects",
column: "ScheduleEntryId");
migrationBuilder.AddForeignKey(
name: "FK_ExperimentProjects_ScheduleEntries_ScheduleEntryId",
table: "ExperimentProjects",
column: "ScheduleEntryId",
principalTable: "ScheduleEntries",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_ExperimentProjects_ScheduleEntries_ScheduleEntryId",
table: "ExperimentProjects");
migrationBuilder.DropIndex(
name: "IX_ExperimentProjects_ScheduleEntryId",
table: "ExperimentProjects");
migrationBuilder.DropColumn(
name: "ScheduleEntryId",
table: "ExperimentProjects");
}
}
}
@@ -0,0 +1,42 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
/// <inheritdoc />
public partial class AddTeachingVenueNatures : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "TeachingVenueNature",
table: "Classrooms",
type: "int",
nullable: false,
defaultValue: 1);
migrationBuilder.Sql("""
UPDATE `Classrooms`
SET `TeachingVenueNature` = CASE
WHEN `RoomType` LIKE '%%' THEN 10
WHEN `RoomType` LIKE '%%' THEN 18
WHEN `RoomType` LIKE '%%' THEN 4
WHEN `RoomType` LIKE '%%' THEN 2
WHEN `RoomType` LIKE '%%' THEN 32
WHEN `RoomType` LIKE '%%' THEN 64
ELSE 1
END;
""");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "TeachingVenueNature",
table: "Classrooms");
}
}
}
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
/// <inheritdoc />
public partial class AddExperimentVenueNatureConstraints : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "AllowedExperimentVenueNatures",
table: "TeachingTaskScheduleConstraints",
type: "int",
nullable: false,
defaultValue: 0);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "AllowedExperimentVenueNatures",
table: "TeachingTaskScheduleConstraints");
}
}
}
@@ -0,0 +1,44 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
/// <inheritdoc />
public partial class SwaggerDocumentationSetting : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "SystemFeatureSettings",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
Key = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
IsEnabled = table.Column<bool>(type: "tinyint(1)", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_SystemFeatureSettings", x => x.Id);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_SystemFeatureSettings_Key",
table: "SystemFeatureSettings",
column: "Key",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "SystemFeatureSettings");
}
}
}
@@ -0,0 +1,52 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
/// <inheritdoc />
public partial class AddExperimentClassroomConstraints : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "TeachingTaskAllowedExperimentClassrooms",
columns: table => new
{
TeachingTaskScheduleConstraintId = table.Column<Guid>(type: "char(36)", nullable: false),
ClassroomId = table.Column<Guid>(type: "char(36)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_TeachingTaskAllowedExperimentClassrooms", x => new { x.TeachingTaskScheduleConstraintId, x.ClassroomId });
table.ForeignKey(
name: "FK_TeachingTaskAllowedExperimentClassrooms_Classrooms_Classroom~",
column: x => x.ClassroomId,
principalTable: "Classrooms",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_TeachingTaskAllowedExperimentClassrooms_TeachingTaskSchedule~",
column: x => x.TeachingTaskScheduleConstraintId,
principalTable: "TeachingTaskScheduleConstraints",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_TeachingTaskAllowedExperimentClassrooms_ClassroomId",
table: "TeachingTaskAllowedExperimentClassrooms",
column: "ClassroomId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "TeachingTaskAllowedExperimentClassrooms");
}
}
}
@@ -0,0 +1,81 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
/// <inheritdoc />
public partial class SeparateExperimentClassroomScope : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<Guid>(
name: "ExperimentRequiredBuildingId",
table: "TeachingTaskScheduleConstraints",
type: "char(36)",
nullable: true);
migrationBuilder.AddColumn<Guid>(
name: "ExperimentRequiredCampusId",
table: "TeachingTaskScheduleConstraints",
type: "char(36)",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_TeachingTaskScheduleConstraints_ExperimentRequiredBuildingId",
table: "TeachingTaskScheduleConstraints",
column: "ExperimentRequiredBuildingId");
migrationBuilder.CreateIndex(
name: "IX_TeachingTaskScheduleConstraints_ExperimentRequiredCampusId",
table: "TeachingTaskScheduleConstraints",
column: "ExperimentRequiredCampusId");
migrationBuilder.AddForeignKey(
name: "FK_TeachingTaskScheduleConstraints_Buildings_ExperimentRequired~",
table: "TeachingTaskScheduleConstraints",
column: "ExperimentRequiredBuildingId",
principalTable: "Buildings",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_TeachingTaskScheduleConstraints_Campuses_ExperimentRequiredC~",
table: "TeachingTaskScheduleConstraints",
column: "ExperimentRequiredCampusId",
principalTable: "Campuses",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_TeachingTaskScheduleConstraints_Buildings_ExperimentRequired~",
table: "TeachingTaskScheduleConstraints");
migrationBuilder.DropForeignKey(
name: "FK_TeachingTaskScheduleConstraints_Campuses_ExperimentRequiredC~",
table: "TeachingTaskScheduleConstraints");
migrationBuilder.DropIndex(
name: "IX_TeachingTaskScheduleConstraints_ExperimentRequiredBuildingId",
table: "TeachingTaskScheduleConstraints");
migrationBuilder.DropIndex(
name: "IX_TeachingTaskScheduleConstraints_ExperimentRequiredCampusId",
table: "TeachingTaskScheduleConstraints");
migrationBuilder.DropColumn(
name: "ExperimentRequiredBuildingId",
table: "TeachingTaskScheduleConstraints");
migrationBuilder.DropColumn(
name: "ExperimentRequiredCampusId",
table: "TeachingTaskScheduleConstraints");
}
}
}
@@ -0,0 +1,90 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
/// <inheritdoc />
public partial class PublishedTimetableOccurrences : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "PublishedScheduleOccurrences",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
SchedulePlanId = table.Column<Guid>(type: "char(36)", nullable: false),
AcademicTermId = table.Column<Guid>(type: "char(36)", nullable: false),
ScheduleEntryId = table.Column<Guid>(type: "char(36)", nullable: false),
TeachingTaskId = table.Column<Guid>(type: "char(36)", nullable: false),
ClassroomId = table.Column<Guid>(type: "char(36)", nullable: true),
Week = table.Column<int>(type: "int", nullable: false),
DayOfWeek = table.Column<int>(type: "int", nullable: false),
StartPeriod = table.Column<int>(type: "int", nullable: false),
PeriodCount = table.Column<int>(type: "int", nullable: false),
Kind = table.Column<int>(type: "int", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_PublishedScheduleOccurrences", x => x.Id);
table.ForeignKey(
name: "FK_PublishedScheduleOccurrences_Classrooms_ClassroomId",
column: x => x.ClassroomId,
principalTable: "Classrooms",
principalColumn: "Id",
onDelete: ReferentialAction.SetNull);
table.ForeignKey(
name: "FK_PublishedScheduleOccurrences_ScheduleEntries_ScheduleEntryId",
column: x => x.ScheduleEntryId,
principalTable: "ScheduleEntries",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_PublishedScheduleOccurrences_TeachingTasks_TeachingTaskId",
column: x => x.TeachingTaskId,
principalTable: "TeachingTasks",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_PublishedScheduleOccurrences_AcademicTermId_TeachingTaskId_W~",
table: "PublishedScheduleOccurrences",
columns: new[] { "AcademicTermId", "TeachingTaskId", "Week" });
migrationBuilder.CreateIndex(
name: "IX_PublishedScheduleOccurrences_ClassroomId",
table: "PublishedScheduleOccurrences",
column: "ClassroomId");
migrationBuilder.CreateIndex(
name: "IX_PublishedScheduleOccurrences_ScheduleEntryId_Week",
table: "PublishedScheduleOccurrences",
columns: new[] { "ScheduleEntryId", "Week" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_PublishedScheduleOccurrences_SchedulePlanId_ClassroomId_Week~",
table: "PublishedScheduleOccurrences",
columns: new[] { "SchedulePlanId", "ClassroomId", "Week", "DayOfWeek", "StartPeriod" });
migrationBuilder.CreateIndex(
name: "IX_PublishedScheduleOccurrences_TeachingTaskId",
table: "PublishedScheduleOccurrences",
column: "TeachingTaskId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "PublishedScheduleOccurrences");
}
}
}
@@ -0,0 +1,27 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
/// <inheritdoc />
public partial class OptimizePublishedTimetableOccurrenceLookup : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateIndex(
name: "IX_PublishedScheduleOccurrences_AcademicTermId_Week_DayOfWeek_S~",
table: "PublishedScheduleOccurrences",
columns: new[] { "AcademicTermId", "Week", "DayOfWeek", "StartPeriod", "ClassroomId" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_PublishedScheduleOccurrences_AcademicTermId_Week_DayOfWeek_S~",
table: "PublishedScheduleOccurrences");
}
}
}
@@ -0,0 +1,87 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
/// <inheritdoc />
public partial class AddReusableCourseGroups : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "CourseGroups",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
Code = table.Column<string>(type: "varchar(30)", maxLength: 30, nullable: false),
Name = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
Description = table.Column<string>(type: "varchar(500)", maxLength: 500, nullable: true),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_CourseGroups", x => x.Id);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "CourseGroupCourses",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
CourseGroupId = table.Column<Guid>(type: "char(36)", nullable: false),
CourseId = table.Column<Guid>(type: "char(36)", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_CourseGroupCourses", x => x.Id);
table.ForeignKey(
name: "FK_CourseGroupCourses_CourseGroups_CourseGroupId",
column: x => x.CourseGroupId,
principalTable: "CourseGroups",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_CourseGroupCourses_Courses_CourseId",
column: x => x.CourseId,
principalTable: "Courses",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_CourseGroupCourses_CourseGroupId_CourseId",
table: "CourseGroupCourses",
columns: new[] { "CourseGroupId", "CourseId" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_CourseGroupCourses_CourseId",
table: "CourseGroupCourses",
column: "CourseId");
migrationBuilder.CreateIndex(
name: "IX_CourseGroups_Code",
table: "CourseGroups",
column: "Code",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "CourseGroupCourses");
migrationBuilder.DropTable(
name: "CourseGroups");
}
}
}
@@ -0,0 +1,19 @@
// <auto-generated />
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql;
[DbContext(typeof(AppDbContext))]
[Migration("20260809112000_AllowAllScheduledExperimentLessons")]
partial class AllowAllScheduledExperimentLessons
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("ProductVersion", "10.0.10");
}
}
@@ -0,0 +1,45 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql;
public partial class AllowAllScheduledExperimentLessons : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
// MySQL 可能将旧唯一索引用于外键支撑。先提供同列的普通索引,
// 再替换业务唯一索引,避免线上迁移因外键依赖而中断。
migrationBuilder.CreateIndex(
name: "IX_ExperimentProjects_TeachingTaskId_Code_FkSupport",
table: "ExperimentProjects",
columns: new[] { "TeachingTaskId", "Code" });
migrationBuilder.DropIndex(
name: "IX_ExperimentProjects_TeachingTaskId_Code",
table: "ExperimentProjects");
migrationBuilder.CreateIndex(
name: "IX_ExperimentProjects_TeachingTaskId_Code_ScheduleEntryId",
table: "ExperimentProjects",
columns: new[] { "TeachingTaskId", "Code", "ScheduleEntryId" },
unique: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_ExperimentProjects_TeachingTaskId_Code_ScheduleEntryId",
table: "ExperimentProjects");
migrationBuilder.CreateIndex(
name: "IX_ExperimentProjects_TeachingTaskId_Code",
table: "ExperimentProjects",
columns: new[] { "TeachingTaskId", "Code" },
unique: true);
migrationBuilder.DropIndex(
name: "IX_ExperimentProjects_TeachingTaskId_Code_FkSupport",
table: "ExperimentProjects");
}
}
@@ -0,0 +1,19 @@
// <auto-generated />
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql;
[DbContext(typeof(AppDbContext))]
[Migration("20260809114000_SplitCentralizedExperimentProjectsByWeek")]
partial class SplitCentralizedExperimentProjectsByWeek
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("ProductVersion", "10.0.10");
}
}
@@ -0,0 +1,78 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql;
public partial class SplitCentralizedExperimentProjectsByWeek : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
ExecuteWhenMissing(
migrationBuilder,
"COLUMNS",
"COLUMN_NAME = 'ScheduleWeek'",
"ALTER TABLE `ExperimentProjects` ADD COLUMN `ScheduleWeek` int NULL");
ExecuteWhenPresent(
migrationBuilder,
"STATISTICS",
"INDEX_NAME = 'IX_ExperimentProjects_TeachingTaskId_Code_ScheduleEntryId'",
"DROP INDEX `IX_ExperimentProjects_TeachingTaskId_Code_ScheduleEntryId` ON `ExperimentProjects`");
ExecuteWhenMissing(
migrationBuilder,
"STATISTICS",
"INDEX_NAME = 'IX_ExpProj_Task_Code_Entry_Week'",
"CREATE UNIQUE INDEX `IX_ExpProj_Task_Code_Entry_Week` ON `ExperimentProjects` (`TeachingTaskId`, `Code`, `ScheduleEntryId`, `ScheduleWeek`)");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_ExpProj_Task_Code_Entry_Week",
table: "ExperimentProjects");
migrationBuilder.CreateIndex(
name: "IX_ExperimentProjects_TeachingTaskId_Code_ScheduleEntryId",
table: "ExperimentProjects",
columns: new[] { "TeachingTaskId", "Code", "ScheduleEntryId" },
unique: true);
migrationBuilder.DropColumn(
name: "ScheduleWeek",
table: "ExperimentProjects");
}
private static void ExecuteWhenMissing(
MigrationBuilder migrationBuilder,
string informationSchemaTable,
string condition,
string command)
{
ExecuteConditionally(migrationBuilder, informationSchemaTable, condition, command, "= 0");
}
private static void ExecuteWhenPresent(
MigrationBuilder migrationBuilder,
string informationSchemaTable,
string condition,
string command)
{
ExecuteConditionally(migrationBuilder, informationSchemaTable, condition, command, "> 0");
}
private static void ExecuteConditionally(
MigrationBuilder migrationBuilder,
string informationSchemaTable,
string condition,
string command,
string comparison)
{
migrationBuilder.Sql($"SET @jiaowu_exists = (SELECT COUNT(*) FROM `information_schema`.`{informationSchemaTable}` WHERE `TABLE_SCHEMA` = DATABASE() AND `TABLE_NAME` = 'ExperimentProjects' AND {condition})");
migrationBuilder.Sql($"SET @jiaowu_sql = IF(@jiaowu_exists {comparison}, '{command}', 'SELECT 1')");
migrationBuilder.Sql("PREPARE jiaowu_migration_statement FROM @jiaowu_sql");
migrationBuilder.Sql("EXECUTE jiaowu_migration_statement");
migrationBuilder.Sql("DEALLOCATE PREPARE jiaowu_migration_statement");
}
}
@@ -0,0 +1,29 @@
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql;
[DbContext(typeof(AppDbContext))]
[Migration("20260809121000_ExperimentPublishJobPayload")]
public partial class ExperimentPublishJobPayload : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "ProjectIdsJson",
table: "ExamPublishJobs",
type: "longtext",
maxLength: 5000,
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "ProjectIdsJson",
table: "ExamPublishJobs");
}
}
@@ -0,0 +1,48 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
/// <inheritdoc />
public partial class CourseGradeStatisticsRefreshSettings : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "CourseGradeStatisticsRefreshSettings",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
Key = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: false),
IsEnabled = table.Column<bool>(type: "tinyint(1)", nullable: false),
IntervalSeconds = table.Column<int>(type: "int", nullable: false),
BatchSize = table.Column<int>(type: "int", nullable: false),
LastRunAt = table.Column<DateTime>(type: "datetime(6)", nullable: true),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_CourseGradeStatisticsRefreshSettings", x => x.Id);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_CourseGradeStatisticsRefreshSettings_Key",
table: "CourseGradeStatisticsRefreshSettings",
column: "Key",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "CourseGradeStatisticsRefreshSettings");
}
}
}
@@ -0,0 +1,28 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
/// <inheritdoc />
public partial class ExamArrangementJobPayload : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "ProjectIdsJson",
table: "ExamArrangementJobs",
type: "longtext",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "ProjectIdsJson",
table: "ExamArrangementJobs");
}
}
}
@@ -0,0 +1,113 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
/// <inheritdoc />
public partial class PersistExperimentCourseGrades : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "ExperimentCourseGrades",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
TeachingTaskId = table.Column<Guid>(type: "char(36)", nullable: false),
StudentId = table.Column<Guid>(type: "char(36)", nullable: false),
WeightedAverageScore = table.Column<decimal>(type: "decimal(5,1)", precision: 5, scale: 1, nullable: true),
TotalWeight = table.Column<decimal>(type: "decimal(8,1)", precision: 8, scale: 1, nullable: false),
PublishedProjectCount = table.Column<int>(type: "int", nullable: false),
RefreshedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ExperimentCourseGrades", x => x.Id);
table.ForeignKey(
name: "FK_ExperimentCourseGrades_Students_StudentId",
column: x => x.StudentId,
principalTable: "Students",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_ExperimentCourseGrades_TeachingTasks_TeachingTaskId",
column: x => x.TeachingTaskId,
principalTable: "TeachingTasks",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_ExperimentCourseGrades_StudentId",
table: "ExperimentCourseGrades",
column: "StudentId");
migrationBuilder.CreateIndex(
name: "IX_ExperimentCourseGrades_TeachingTaskId_StudentId",
table: "ExperimentCourseGrades",
columns: new[] { "TeachingTaskId", "StudentId" },
unique: true);
migrationBuilder.Sql(
"""
INSERT INTO `ExperimentCourseGrades`
(`Id`, `TeachingTaskId`, `StudentId`, `WeightedAverageScore`,
`TotalWeight`, `PublishedProjectCount`, `RefreshedAt`,
`CreatedAt`, `UpdatedAt`)
SELECT
UUID(),
project.`TeachingTaskId`,
record.`StudentId`,
CASE
WHEN COUNT(*) = (
SELECT COUNT(*)
FROM `ExperimentGradeSheets` AS all_sheet
INNER JOIN `ExperimentProjects` AS all_project
ON all_project.`Id` = all_sheet.`ExperimentProjectId`
WHERE all_sheet.`Status` = 4
AND all_project.`TeachingTaskId` = project.`TeachingTaskId`)
AND SUM(CASE WHEN record.`TotalScore` IS NULL THEN 1 ELSE 0 END) = 0
THEN ROUND(
SUM(record.`TotalScore` * sheet.`ContributionWeight`) /
SUM(sheet.`ContributionWeight`), 1)
ELSE NULL
END,
(
SELECT COALESCE(SUM(all_sheet.`ContributionWeight`), 0)
FROM `ExperimentGradeSheets` AS all_sheet
INNER JOIN `ExperimentProjects` AS all_project
ON all_project.`Id` = all_sheet.`ExperimentProjectId`
WHERE all_sheet.`Status` = 4
AND all_project.`TeachingTaskId` = project.`TeachingTaskId`),
(
SELECT COUNT(*)
FROM `ExperimentGradeSheets` AS all_sheet
INNER JOIN `ExperimentProjects` AS all_project
ON all_project.`Id` = all_sheet.`ExperimentProjectId`
WHERE all_sheet.`Status` = 4
AND all_project.`TeachingTaskId` = project.`TeachingTaskId`),
UTC_TIMESTAMP(6), UTC_TIMESTAMP(6), UTC_TIMESTAMP(6)
FROM `ExperimentGradeRecords` AS record
INNER JOIN `ExperimentGradeSheets` AS sheet
ON sheet.`Id` = record.`ExperimentGradeSheetId`
INNER JOIN `ExperimentProjects` AS project
ON project.`Id` = sheet.`ExperimentProjectId`
WHERE sheet.`Status` = 4
GROUP BY project.`TeachingTaskId`, record.`StudentId`;
""");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ExperimentCourseGrades");
}
}
}
@@ -525,6 +525,9 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.Property<int>("SortOrder")
.HasColumnType("int");
b.Property<int>("TeachingVenueNature")
.HasColumnType("int");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
@@ -983,6 +986,217 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.ToTable("CourseExemptions");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.CourseGradeStatistic", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<Guid>("AcademicTermId")
.HasColumnType("char(36)");
b.Property<decimal>("AverageScore")
.HasPrecision(5, 1)
.HasColumnType("decimal(5,1)");
b.Property<int>("Below60Count")
.HasColumnType("int");
b.Property<DateTime>("CalculatedAt")
.HasColumnType("datetime(6)");
b.Property<Guid>("CourseId")
.HasColumnType("char(36)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<int>("From60To69Count")
.HasColumnType("int");
b.Property<int>("From70To79Count")
.HasColumnType("int");
b.Property<int>("From80To89Count")
.HasColumnType("int");
b.Property<int>("From90To100Count")
.HasColumnType("int");
b.Property<decimal>("HighestScore")
.HasPrecision(5, 1)
.HasColumnType("decimal(5,1)");
b.Property<decimal>("LowestScore")
.HasPrecision(5, 1)
.HasColumnType("decimal(5,1)");
b.Property<decimal>("PassRate")
.HasPrecision(5, 2)
.HasColumnType("decimal(5,2)");
b.Property<int>("PassedCount")
.HasColumnType("int");
b.Property<int>("Scope")
.HasColumnType("int");
b.Property<Guid?>("ScopeEntityId")
.HasColumnType("char(36)");
b.Property<int>("StudentCount")
.HasColumnType("int");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("AcademicTermId", "Scope", "ScopeEntityId");
b.HasIndex("CourseId", "AcademicTermId", "Scope", "ScopeEntityId")
.IsUnique()
.HasDatabaseName("UX_CourseGradeStatistics_Scope");
b.ToTable("CourseGradeStatistics");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.CourseGradeStatisticsRefreshJob", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTime?>("CompletedAt")
.HasColumnType("datetime(6)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("ErrorMessage")
.HasMaxLength(2000)
.HasColumnType("varchar(2000)");
b.Property<Guid>("GradeSheetId")
.HasColumnType("char(36)");
b.Property<DateTime?>("StartedAt")
.HasColumnType("datetime(6)");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("GradeSheetId");
b.HasIndex("Status", "CreatedAt");
b.ToTable("CourseGradeStatisticsRefreshJobs");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.CourseGradeStatisticsRefreshSetting", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<int>("BatchSize")
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<int>("IntervalSeconds")
.HasColumnType("int");
b.Property<bool>("IsEnabled")
.HasColumnType("tinyint(1)");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("varchar(50)");
b.Property<DateTime?>("LastRunAt")
.HasColumnType("datetime(6)");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("Key")
.IsUnique();
b.ToTable("CourseGradeStatisticsRefreshSettings");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.CourseGroup", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(30)
.HasColumnType("varchar(30)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Description")
.HasMaxLength(500)
.HasColumnType("varchar(500)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("Code")
.IsUnique();
b.ToTable("CourseGroups");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.CourseGroupCourse", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<Guid>("CourseGroupId")
.HasColumnType("char(36)");
b.Property<Guid>("CourseId")
.HasColumnType("char(36)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("CourseId");
b.HasIndex("CourseGroupId", "CourseId")
.IsUnique();
b.ToTable("CourseGroupCourses");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.CoursePrerequisite", b =>
{
b.Property<Guid>("Id")
@@ -1634,6 +1848,9 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.Property<int>("ProcessedSessions")
.HasColumnType("int");
b.Property<string>("ProjectIdsJson")
.HasColumnType("longtext");
b.Property<Guid?>("RequestedByUserId")
.HasColumnType("char(36)");
@@ -1736,6 +1953,9 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.Property<Guid>("PlanId")
.HasColumnType("char(36)");
b.Property<string>("ProjectIdsJson")
.HasColumnType("longtext");
b.Property<Guid?>("RequestedByUserId")
.HasColumnType("char(36)");
@@ -2043,6 +2263,48 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.ToTable("ExperimentBookings");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.ExperimentCourseGrade", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<int>("PublishedProjectCount")
.HasColumnType("int");
b.Property<DateTime>("RefreshedAt")
.HasColumnType("datetime(6)");
b.Property<Guid>("StudentId")
.HasColumnType("char(36)");
b.Property<Guid>("TeachingTaskId")
.HasColumnType("char(36)");
b.Property<decimal>("TotalWeight")
.HasPrecision(8, 1)
.HasColumnType("decimal(8,1)");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.Property<decimal?>("WeightedAverageScore")
.HasPrecision(5, 1)
.HasColumnType("decimal(5,1)");
b.HasKey("Id");
b.HasIndex("StudentId");
b.HasIndex("TeachingTaskId", "StudentId")
.IsUnique();
b.ToTable("ExperimentCourseGrades");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.ExperimentGradeItem", b =>
{
b.Property<Guid>("Id")
@@ -2252,6 +2514,12 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
.HasMaxLength(1000)
.HasColumnType("varchar(1000)");
b.Property<Guid?>("ScheduleEntryId")
.HasColumnType("char(36)");
b.Property<int?>("ScheduleWeek")
.HasColumnType("int");
b.Property<DateTime>("StartDate")
.HasColumnType("date");
@@ -2266,11 +2534,13 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.HasKey("Id");
b.HasIndex("TeachingTaskId", "Code")
.IsUnique();
b.HasIndex("ScheduleEntryId");
b.HasIndex("Status", "StartDate", "EndDate");
b.HasIndex("TeachingTaskId", "Code", "ScheduleEntryId", "ScheduleWeek")
.IsUnique();
b.ToTable("ExperimentProjects");
});
@@ -3278,6 +3548,167 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.ToTable("OfficialDocumentDownloads");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.OtherExamBatch", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("ExamCode")
.HasMaxLength(60)
.HasColumnType("varchar(60)");
b.Property<DateTime>("ExamDate")
.HasColumnType("date");
b.Property<string>("LevelOptions")
.HasMaxLength(500)
.HasColumnType("varchar(500)");
b.Property<decimal?>("MaxScore")
.HasPrecision(8, 2)
.HasColumnType("decimal(8,2)");
b.Property<int>("MetricKind")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(150)
.HasColumnType("varchar(150)");
b.Property<string>("Organizer")
.HasMaxLength(150)
.HasColumnType("varchar(150)");
b.Property<int>("PublicationCount")
.HasColumnType("int");
b.Property<DateTime?>("PublishedAt")
.HasColumnType("datetime(6)");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("Status", "ExamDate");
b.ToTable("OtherExamBatches");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.OtherExamResult", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<int>("AttemptNumber")
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<bool?>("IsPassed")
.HasColumnType("tinyint(1)");
b.Property<string>("Level")
.HasMaxLength(50)
.HasColumnType("varchar(50)");
b.Property<string>("Notes")
.HasMaxLength(500)
.HasColumnType("varchar(500)");
b.Property<Guid>("OtherExamBatchId")
.HasColumnType("char(36)");
b.Property<decimal?>("Score")
.HasPrecision(8, 2)
.HasColumnType("decimal(8,2)");
b.Property<Guid>("StudentId")
.HasColumnType("char(36)");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("StudentId", "OtherExamBatchId");
b.HasIndex("OtherExamBatchId", "StudentId", "AttemptNumber")
.IsUnique();
b.ToTable("OtherExamResults");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.PublishedScheduleOccurrence", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<Guid>("AcademicTermId")
.HasColumnType("char(36)");
b.Property<Guid?>("ClassroomId")
.HasColumnType("char(36)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<int>("DayOfWeek")
.HasColumnType("int");
b.Property<int>("Kind")
.HasColumnType("int");
b.Property<int>("PeriodCount")
.HasColumnType("int");
b.Property<Guid>("ScheduleEntryId")
.HasColumnType("char(36)");
b.Property<Guid>("SchedulePlanId")
.HasColumnType("char(36)");
b.Property<int>("StartPeriod")
.HasColumnType("int");
b.Property<Guid>("TeachingTaskId")
.HasColumnType("char(36)");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.Property<int>("Week")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ClassroomId");
b.HasIndex("TeachingTaskId");
b.HasIndex("ScheduleEntryId", "Week")
.IsUnique();
b.HasIndex("AcademicTermId", "TeachingTaskId", "Week");
b.HasIndex("AcademicTermId", "Week", "DayOfWeek", "StartPeriod", "ClassroomId");
b.HasIndex("SchedulePlanId", "ClassroomId", "Week", "DayOfWeek", "StartPeriod");
b.ToTable("PublishedScheduleOccurrences");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.ScheduleEntry", b =>
{
b.Property<Guid>("Id")
@@ -3881,6 +4312,21 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.ToTable("TeachingTaskAllowedClassrooms");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.TeachingTaskAllowedExperimentClassroom", b =>
{
b.Property<Guid>("TeachingTaskScheduleConstraintId")
.HasColumnType("char(36)");
b.Property<Guid>("ClassroomId")
.HasColumnType("char(36)");
b.HasKey("TeachingTaskScheduleConstraintId", "ClassroomId");
b.HasIndex("ClassroomId");
b.ToTable("TeachingTaskAllowedExperimentClassrooms");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.TeachingTaskClass", b =>
{
b.Property<Guid>("TeachingTaskId")
@@ -3896,6 +4342,127 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.ToTable("TeachingTaskClasses");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.TeachingTaskGradeScoreBand", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Label")
.IsRequired()
.HasMaxLength(30)
.HasColumnType("varchar(30)");
b.Property<decimal>("LowerBound")
.HasPrecision(5, 1)
.HasColumnType("decimal(5,1)");
b.Property<int>("SortOrder")
.HasColumnType("int");
b.Property<int>("StudentCount")
.HasColumnType("int");
b.Property<Guid>("TeachingTaskGradeStatisticId")
.HasColumnType("char(36)");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.Property<decimal?>("UpperBound")
.HasPrecision(5, 1)
.HasColumnType("decimal(5,1)");
b.HasKey("Id");
b.HasIndex("TeachingTaskGradeStatisticId", "SortOrder")
.IsUnique();
b.ToTable("TeachingTaskGradeScoreBands");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.TeachingTaskGradeStatistic", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<Guid>("AcademicTermId")
.HasColumnType("char(36)");
b.Property<decimal>("AverageScore")
.HasPrecision(5, 1)
.HasColumnType("decimal(5,1)");
b.Property<DateTime>("CalculatedAt")
.HasColumnType("datetime(6)");
b.Property<Guid>("CourseId")
.HasColumnType("char(36)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<int>("ExcellentCount")
.HasColumnType("int");
b.Property<decimal>("ExcellentRate")
.HasPrecision(5, 2)
.HasColumnType("decimal(5,2)");
b.Property<Guid>("GradeSheetId")
.HasColumnType("char(36)");
b.Property<decimal>("HighestScore")
.HasPrecision(5, 1)
.HasColumnType("decimal(5,1)");
b.Property<decimal>("LowestScore")
.HasPrecision(5, 1)
.HasColumnType("decimal(5,1)");
b.Property<decimal>("MedianScore")
.HasPrecision(5, 1)
.HasColumnType("decimal(5,1)");
b.Property<decimal>("PassRate")
.HasPrecision(5, 2)
.HasColumnType("decimal(5,2)");
b.Property<int>("PassedCount")
.HasColumnType("int");
b.Property<decimal>("StandardDeviation")
.HasPrecision(6, 2)
.HasColumnType("decimal(6,2)");
b.Property<int>("StudentCount")
.HasColumnType("int");
b.Property<Guid>("TeachingTaskId")
.HasColumnType("char(36)");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("AcademicTermId");
b.HasIndex("GradeSheetId")
.IsUnique();
b.HasIndex("TeachingTaskId")
.IsUnique();
b.HasIndex("CourseId", "AcademicTermId");
b.ToTable("TeachingTaskGradeStatistics");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.TeachingTaskScheduleConstraint", b =>
{
b.Property<Guid>("Id")
@@ -3906,12 +4473,21 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
.HasMaxLength(20)
.HasColumnType("varchar(20)");
b.Property<int>("AllowedExperimentVenueNatures")
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<int?>("EarliestPeriod")
.HasColumnType("int");
b.Property<Guid?>("ExperimentRequiredBuildingId")
.HasColumnType("char(36)");
b.Property<Guid?>("ExperimentRequiredCampusId")
.HasColumnType("char(36)");
b.Property<int?>("LatestPeriod")
.HasColumnType("int");
@@ -3932,6 +4508,10 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.HasKey("Id");
b.HasIndex("ExperimentRequiredBuildingId");
b.HasIndex("ExperimentRequiredCampusId");
b.HasIndex("RequiredBuildingId");
b.HasIndex("RequiredCampusId");
@@ -4433,6 +5013,34 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.ToTable("BackgroundJobOutboxMessages");
});
modelBuilder.Entity("Jiaowu.Api.Domain.System.SystemFeatureSetting", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<bool>("IsEnabled")
.HasColumnType("tinyint(1)");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("Key")
.IsUnique();
b.ToTable("SystemFeatureSettings");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
{
b.Property<int>("Id")
@@ -4770,6 +5378,49 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.Navigation("TeachingTask");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.CourseGradeStatistic", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.AcademicTerm", null)
.WithMany()
.HasForeignKey("AcademicTermId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Jiaowu.Api.Domain.Academic.Course", null)
.WithMany()
.HasForeignKey("CourseId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.CourseGradeStatisticsRefreshJob", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.GradeSheet", null)
.WithMany()
.HasForeignKey("GradeSheetId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.CourseGroupCourse", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.CourseGroup", "CourseGroup")
.WithMany("Courses")
.HasForeignKey("CourseGroupId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Jiaowu.Api.Domain.Academic.Course", "Course")
.WithMany()
.HasForeignKey("CourseId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Course");
b.Navigation("CourseGroup");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.CoursePrerequisite", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.Course", "Course")
@@ -5194,6 +5845,25 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.Navigation("Student");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.ExperimentCourseGrade", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.Student", "Student")
.WithMany()
.HasForeignKey("StudentId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Jiaowu.Api.Domain.Academic.TeachingTask", "TeachingTask")
.WithMany()
.HasForeignKey("TeachingTaskId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Student");
b.Navigation("TeachingTask");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.ExperimentGradeItem", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.ExperimentGradeSheet", "ExperimentGradeSheet")
@@ -5263,12 +5933,19 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.ExperimentProject", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.ScheduleEntry", "ScheduleEntry")
.WithMany()
.HasForeignKey("ScheduleEntryId")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("Jiaowu.Api.Domain.Academic.TeachingTask", "TeachingTask")
.WithMany()
.HasForeignKey("TeachingTaskId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("ScheduleEntry");
b.Navigation("TeachingTask");
});
@@ -5598,6 +6275,51 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.Navigation("OfficialDocument");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.OtherExamResult", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.OtherExamBatch", "OtherExamBatch")
.WithMany("Results")
.HasForeignKey("OtherExamBatchId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Jiaowu.Api.Domain.Academic.Student", "Student")
.WithMany()
.HasForeignKey("StudentId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("OtherExamBatch");
b.Navigation("Student");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.PublishedScheduleOccurrence", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.Classroom", "Classroom")
.WithMany()
.HasForeignKey("ClassroomId")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("Jiaowu.Api.Domain.Academic.ScheduleEntry", "ScheduleEntry")
.WithMany()
.HasForeignKey("ScheduleEntryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Jiaowu.Api.Domain.Academic.TeachingTask", "TeachingTask")
.WithMany()
.HasForeignKey("TeachingTaskId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Classroom");
b.Navigation("ScheduleEntry");
b.Navigation("TeachingTask");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.ScheduleEntry", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.Classroom", "Classroom")
@@ -5775,6 +6497,25 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.Navigation("TeachingTaskScheduleConstraint");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.TeachingTaskAllowedExperimentClassroom", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.Classroom", "Classroom")
.WithMany()
.HasForeignKey("ClassroomId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Jiaowu.Api.Domain.Academic.TeachingTaskScheduleConstraint", "TeachingTaskScheduleConstraint")
.WithMany("AllowedExperimentClassrooms")
.HasForeignKey("TeachingTaskScheduleConstraintId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Classroom");
b.Navigation("TeachingTaskScheduleConstraint");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.TeachingTaskClass", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.AdministrativeClass", "AdministrativeClass")
@@ -5794,8 +6535,60 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.Navigation("TeachingTask");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.TeachingTaskGradeScoreBand", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.TeachingTaskGradeStatistic", "TeachingTaskGradeStatistic")
.WithMany("ScoreBands")
.HasForeignKey("TeachingTaskGradeStatisticId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("TeachingTaskGradeStatistic");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.TeachingTaskGradeStatistic", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.AcademicTerm", null)
.WithMany()
.HasForeignKey("AcademicTermId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Jiaowu.Api.Domain.Academic.Course", null)
.WithMany()
.HasForeignKey("CourseId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Jiaowu.Api.Domain.Academic.GradeSheet", "GradeSheet")
.WithOne()
.HasForeignKey("Jiaowu.Api.Domain.Academic.TeachingTaskGradeStatistic", "GradeSheetId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Jiaowu.Api.Domain.Academic.TeachingTask", "TeachingTask")
.WithOne()
.HasForeignKey("Jiaowu.Api.Domain.Academic.TeachingTaskGradeStatistic", "TeachingTaskId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("GradeSheet");
b.Navigation("TeachingTask");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.TeachingTaskScheduleConstraint", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.Building", "ExperimentRequiredBuilding")
.WithMany()
.HasForeignKey("ExperimentRequiredBuildingId")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("Jiaowu.Api.Domain.Academic.Campus", "ExperimentRequiredCampus")
.WithMany()
.HasForeignKey("ExperimentRequiredCampusId")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("Jiaowu.Api.Domain.Academic.Building", "RequiredBuilding")
.WithMany()
.HasForeignKey("RequiredBuildingId")
@@ -5812,6 +6605,10 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("ExperimentRequiredBuilding");
b.Navigation("ExperimentRequiredCampus");
b.Navigation("RequiredBuilding");
b.Navigation("RequiredCampus");
@@ -5941,6 +6738,11 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.Navigation("RequiredByCourses");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.CourseGroup", b =>
{
b.Navigation("Courses");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.CourseSelectionOffering", b =>
{
b.Navigation("Enrollments");
@@ -6095,6 +6897,11 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.Navigation("Downloads");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.OtherExamBatch", b =>
{
b.Navigation("Results");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.SchedulePlan", b =>
{
b.Navigation("Entries");
@@ -6107,9 +6914,16 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.Navigation("Teachers");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.TeachingTaskGradeStatistic", b =>
{
b.Navigation("ScoreBands");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.TeachingTaskScheduleConstraint", b =>
{
b.Navigation("AllowedClassrooms");
b.Navigation("AllowedExperimentClassrooms");
});
#pragma warning restore 612, 618
}
@@ -44,6 +44,7 @@ public sealed class AutomaticScheduleGenerator(AppDbContext db)
var constraints = await db.TeachingTaskScheduleConstraints.AsNoTracking()
.WhereIn(taskIds, x => x.TeachingTaskId)
.Include(x => x.AllowedClassrooms)
.Include(x => x.AllowedExperimentClassrooms)
.ToDictionaryAsync(x => x.TeachingTaskId, cancellationToken);
var classrooms = await db.Classrooms.AsNoTracking()
.Where(x => x.IsEnabled)
@@ -253,8 +254,15 @@ public sealed class AutomaticScheduleGenerator(AppDbContext db)
x.TeachingTaskId == task.Id && x.DayOfWeek == day);
var dayLoad = entries.Count(x => x.DayOfWeek == day);
var roomWaste = room is null ? 0 : Math.Max(0, room.Capacity - task.Capacity);
var experimentGeneralClassroomPenalty =
kind == ScheduleEntryKind.Experiment &&
constraint?.AllowedExperimentVenueNatures == 0 &&
room?.TeachingVenueNature == TeachingVenueNature.GeneralClassroom
? 100_000
: 0;
var score = sameTaskDay * 1000 + dayLoad * 10 + start +
roomWaste / 10 + startWeek;
roomWaste / 10 + startWeek +
experimentGeneralClassroomPenalty;
candidates.Add((proposed, score));
}
}
@@ -279,6 +287,9 @@ public sealed class AutomaticScheduleGenerator(AppDbContext db)
var allowedRoomIds = constraint?.AllowedClassrooms
.Select(x => x.ClassroomId)
.ToHashSet() ?? [];
var allowedExperimentRoomIds = constraint?.AllowedExperimentClassrooms
.Select(x => x.ClassroomId)
.ToHashSet() ?? [];
var minimumCapacity = Math.Max(
task.Capacity,
task.Classes.Sum(x =>
@@ -286,20 +297,28 @@ public sealed class AutomaticScheduleGenerator(AppDbContext db)
student.Status == StudentStatus.Active) ?? 0));
return classrooms.Where(room =>
room.Capacity >= minimumCapacity &&
(constraint?.RequiredCampusId is not Guid requiredCampusId ||
(kind == ScheduleEntryKind.Experiment ||
constraint?.RequiredCampusId is not Guid requiredCampusId ||
room.Building!.CampusId == requiredCampusId) &&
(constraint?.RequiredBuildingId is not Guid requiredBuildingId ||
(kind == ScheduleEntryKind.Experiment ||
constraint?.RequiredBuildingId is not Guid requiredBuildingId ||
room.BuildingId == requiredBuildingId) &&
(allowedRoomIds.Count == 0 || allowedRoomIds.Contains(room.Id)) &&
(kind != ScheduleEntryKind.Experiment || IsExperimentRoom(room.RoomType)))
(kind != ScheduleEntryKind.Experiment ||
constraint?.ExperimentRequiredCampusId is not Guid experimentCampusId ||
room.Building!.CampusId == experimentCampusId) &&
(kind != ScheduleEntryKind.Experiment ||
constraint?.ExperimentRequiredBuildingId is not Guid experimentBuildingId ||
room.BuildingId == experimentBuildingId) &&
(kind == ScheduleEntryKind.Experiment ||
allowedRoomIds.Count == 0 || allowedRoomIds.Contains(room.Id)) &&
(kind != ScheduleEntryKind.Experiment || constraint is null ||
constraint.AllowedExperimentVenueNatures == 0 ||
(room.TeachingVenueNature & constraint.AllowedExperimentVenueNatures) != 0) &&
(kind != ScheduleEntryKind.Experiment || allowedExperimentRoomIds.Count == 0 ||
allowedExperimentRoomIds.Contains(room.Id)))
.ToList();
}
private static bool IsExperimentRoom(string roomType) =>
roomType.Contains("实验", StringComparison.OrdinalIgnoreCase) ||
roomType.Contains("实训", StringComparison.OrdinalIgnoreCase) ||
roomType.Contains("机房", StringComparison.OrdinalIgnoreCase) ||
roomType.Contains("语音", StringComparison.OrdinalIgnoreCase);
private static int[] ParseAllowedDays(string? value)
{
@@ -2,6 +2,7 @@ using System.Diagnostics.CodeAnalysis;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Infrastructure.Caching;
using Jiaowu.Api.Infrastructure.Persistence;
using Jiaowu.Api.Infrastructure.Timetables;
using Jiaowu.Api.Infrastructure.Teaching;
using Microsoft.EntityFrameworkCore;
@@ -73,6 +74,8 @@ public sealed class SchedulePublishJobProcessor(
foreach (var oldPlan in previous)
oldPlan.Status = SchedulePlanStatus.Archived;
await new PublishedTimetableProjectionService(db)
.RebuildAsync(publishPlan, stoppingToken);
publishPlan.Status = SchedulePlanStatus.Published;
publishPlan.PublishedAt = DateTime.UtcNow;
publishJob.Status = SchedulePublishJobStatus.Succeeded;
@@ -167,6 +170,7 @@ public sealed class SchedulePlanPublisher(AppDbContext db)
var constraints = await db.TeachingTaskScheduleConstraints.AsNoTracking()
.WhereIn(taskIds, x => x.TeachingTaskId)
.Include(x => x.AllowedClassrooms)
.Include(x => x.AllowedExperimentClassrooms)
.ToDictionaryAsync(x => x.TeachingTaskId, cancellationToken);
foreach (var entry in plan.Entries)
@@ -270,21 +274,40 @@ public sealed class SchedulePlanPublisher(AppDbContext db)
{
if (classroom is null || !classroom.IsEnabled)
Fail(entry, "所选教室不存在或已停用");
if (entry.Kind == ScheduleEntryKind.Experiment &&
!IsExperimentRoom(classroom.RoomType))
Fail(entry, $"实验课不能安排在“{classroom.RoomType}”类型的场地");
if (constraint?.RequiredCampusId is Guid campusId &&
if (entry.Kind != ScheduleEntryKind.Experiment &&
constraint?.RequiredCampusId is Guid campusId &&
classroom.Building!.CampusId != campusId)
Fail(entry, "所选教室不在指定校区");
if (constraint?.RequiredBuildingId is Guid buildingId &&
if (entry.Kind != ScheduleEntryKind.Experiment &&
constraint?.RequiredBuildingId is Guid buildingId &&
classroom.BuildingId != buildingId)
Fail(entry, "所选教室不在指定教学楼");
if (entry.Kind == ScheduleEntryKind.Experiment &&
constraint?.ExperimentRequiredCampusId is Guid experimentCampusId &&
classroom.Building!.CampusId != experimentCampusId)
Fail(entry, "所选场地不在实验课指定校区");
if (entry.Kind == ScheduleEntryKind.Experiment &&
constraint?.ExperimentRequiredBuildingId is Guid experimentBuildingId &&
classroom.BuildingId != experimentBuildingId)
Fail(entry, "所选场地不在实验课指定教学楼");
var allowedClassroomIds = constraint?.AllowedClassrooms
.Select(x => x.ClassroomId)
.ToHashSet() ?? [];
if (allowedClassroomIds.Count > 0 &&
if (entry.Kind != ScheduleEntryKind.Experiment && allowedClassroomIds.Count > 0 &&
!allowedClassroomIds.Contains(classroom.Id))
Fail(entry, "所选教室不在指定教室范围内");
var allowedExperimentClassroomIds = constraint?.AllowedExperimentClassrooms
.Select(x => x.ClassroomId)
.ToHashSet() ?? [];
if (entry.Kind == ScheduleEntryKind.Experiment &&
allowedExperimentClassroomIds.Count > 0 &&
!allowedExperimentClassroomIds.Contains(classroom.Id))
Fail(entry, "所选场地不在实验课指定场地范围内");
if (entry.Kind == ScheduleEntryKind.Experiment &&
constraint?.AllowedExperimentVenueNatures is { } allowedNatures &&
allowedNatures != 0 &&
(classroom.TeachingVenueNature & allowedNatures) == 0)
Fail(entry, "所选场地不在实验课允许的场地性质范围内");
}
var studentCount = task.Classes.Sum(x =>
@@ -305,12 +328,6 @@ public sealed class SchedulePlanPublisher(AppDbContext db)
.Select(int.Parse)
.ToHashSet();
private static bool IsExperimentRoom(string roomType) =>
roomType.Contains("实验", StringComparison.OrdinalIgnoreCase) ||
roomType.Contains("实训", StringComparison.OrdinalIgnoreCase) ||
roomType.Contains("机房", StringComparison.OrdinalIgnoreCase) ||
roomType.Contains("语音", StringComparison.OrdinalIgnoreCase);
[DoesNotReturn]
private static void Fail(ScheduleEntry entry, string message)
{
@@ -17,32 +17,33 @@ public sealed class ClassroomReservationAvailabilityService(AppDbContext db)
var occupiedIds = new HashSet<Guid>();
var (week, dayOfWeek) = ResolveTeachingWeek(term, reservationDate);
var scheduleEntries = await db.ScheduleEntries.AsNoTracking()
.Where(entry =>
entry.ClassroomId.HasValue &&
entry.SchedulePlan!.AcademicTermId == term.Id &&
entry.SchedulePlan.Status == SchedulePlanStatus.Published &&
entry.DayOfWeek == dayOfWeek &&
entry.StartWeek <= week &&
entry.EndWeek >= week &&
var hasProjection = await db.PublishedScheduleOccurrences.AsNoTracking()
.AnyAsync(entry => entry.AcademicTermId == term.Id, cancellationToken);
if (hasProjection)
{
var projectedRoomIds = await db.PublishedScheduleOccurrences.AsNoTracking()
.Where(entry => entry.AcademicTermId == term.Id && entry.Week == week &&
entry.DayOfWeek == dayOfWeek && entry.ClassroomId.HasValue &&
entry.StartPeriod < startPeriod + periodCount &&
startPeriod < entry.StartPeriod + entry.PeriodCount)
.Select(entry => new
.Select(entry => entry.ClassroomId!.Value)
.ToListAsync(cancellationToken);
occupiedIds.UnionWith(projectedRoomIds);
}
else
{
entry.ClassroomId,
entry.WeekPattern,
entry.StartPeriod,
entry.PeriodCount
})
var scheduleEntries = await db.ScheduleEntries.AsNoTracking()
.Where(entry => entry.ClassroomId.HasValue &&
entry.SchedulePlan!.AcademicTermId == term.Id &&
entry.SchedulePlan.Status == SchedulePlanStatus.Published &&
entry.DayOfWeek == dayOfWeek && entry.StartWeek <= week &&
entry.EndWeek >= week && entry.StartPeriod < startPeriod + periodCount &&
startPeriod < entry.StartPeriod + entry.PeriodCount)
.Select(entry => new { entry.ClassroomId, entry.WeekPattern, entry.StartPeriod, entry.PeriodCount })
.ToListAsync(cancellationToken);
foreach (var entry in scheduleEntries.Where(entry =>
FreeClassroomRules.MatchesWeek(entry.WeekPattern, week) &&
FreeClassroomRules.PeriodsOverlap(
startPeriod,
periodCount,
entry.StartPeriod,
entry.PeriodCount)))
{
FreeClassroomRules.PeriodsOverlap(startPeriod, periodCount, entry.StartPeriod, entry.PeriodCount)))
occupiedIds.Add(entry.ClassroomId!.Value);
}
@@ -0,0 +1,63 @@
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
namespace Jiaowu.Api.Infrastructure.Timetables;
public sealed class PublishedTimetableProjectionService(AppDbContext db)
{
private const int WriteBatchSize = 2_000;
public async Task RebuildPublishedPlansForTaskAsync(Guid teachingTaskId, CancellationToken cancellationToken)
{
var plans = await db.SchedulePlans
.Where(plan => plan.Status == SchedulePlanStatus.Published &&
plan.Entries.Any(entry => entry.TeachingTaskId == teachingTaskId))
.Include(plan => plan.Entries)
.ToListAsync(cancellationToken);
foreach (var plan in plans)
await RebuildAsync(plan, cancellationToken);
}
public async Task RebuildAsync(SchedulePlan plan, CancellationToken cancellationToken)
{
await db.PublishedScheduleOccurrences
.Where(x => x.SchedulePlanId == plan.Id)
.ExecuteDeleteAsync(cancellationToken);
var rows = new List<PublishedScheduleOccurrence>(WriteBatchSize);
foreach (var entry in plan.Entries)
for (var week = entry.StartWeek; week <= entry.EndWeek; week++)
{
if (entry.WeekPattern == WeekPattern.Odd && week % 2 == 0 ||
entry.WeekPattern == WeekPattern.Even && week % 2 != 0) continue;
rows.Add(new PublishedScheduleOccurrence
{
SchedulePlanId = plan.Id,
AcademicTermId = plan.AcademicTermId,
ScheduleEntryId = entry.Id,
TeachingTaskId = entry.TeachingTaskId,
ClassroomId = entry.ClassroomId,
Week = week,
DayOfWeek = entry.DayOfWeek,
StartPeriod = entry.StartPeriod,
PeriodCount = entry.PeriodCount,
Kind = entry.Kind
});
if (rows.Count == WriteBatchSize)
await WriteBatchAsync(rows, cancellationToken);
}
if (rows.Count > 0)
await WriteBatchAsync(rows, cancellationToken);
}
private async Task WriteBatchAsync(
List<PublishedScheduleOccurrence> rows,
CancellationToken cancellationToken)
{
db.PublishedScheduleOccurrences.AddRange(rows);
await db.SaveChangesAsync(cancellationToken);
foreach (var row in rows)
db.Entry(row).State = EntityState.Detached;
rows.Clear();
}
}
+23 -9
View File
@@ -1,8 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Import Project="..\..\versions.props" />
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Version>2.3.0-rc2</Version>
<Version>$(JiaowuBackendVersion)</Version>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<SpaRoot>$([System.IO.Path]::GetFullPath('$(MSBuildProjectDirectory)/../../web'))</SpaRoot>
@@ -18,32 +20,44 @@
Include="..\..\.env.example"
Link=".env.example"
CopyToPublishDirectory="PreserveNewest" />
<Content
Include="..\..\versions.props"
Link="versions.props"
CopyToOutputDirectory="PreserveNewest"
CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="ClosedXML" Version="0.105.0" />
<AssemblyMetadata
Include="SwaggerDocumentVersion"
Value="$(JiaowuSwaggerVersion)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="ClosedXML" Version="0.105.1" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.5.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.10" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="10.0.10" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.10" />
<PackageReference Include="Microsoft.Extensions.Caching.Hybrid" Version="10.1.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Hybrid" Version="10.8.0" />
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="10.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.10">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.10" />
<PackageReference Include="MySql.EntityFrameworkCore" Version="10.0.7" />
<PackageReference Include="MySql.EntityFrameworkCore" Version="10.0.9" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.17.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.17.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.17.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.17.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.17.0" />
<PackageReference Include="QRCoder" Version="1.8.0" />
<PackageReference Include="RabbitMQ.Client" Version="7.2.1" />
<PackageReference Include="SkiaSharp" Version="3.119.2" />
<PackageReference Include="SkiaSharp.NativeAssets.Linux.NoDependencies" Version="3.119.2" />
<PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="3.0.4" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
<PackageReference Include="RabbitMQ.Client" Version="7.2.2" />
<PackageReference Include="SkiaSharp" Version="4.151.1" />
<PackageReference Include="SkiaSharp.NativeAssets.Linux.NoDependencies" Version="4.151.1" />
<PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="3.0.5" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="10.2.3" />
</ItemGroup>
<Target
+50 -15
View File
@@ -1,7 +1,9 @@
using System.Text;
using System.Text.Json.Serialization;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Domain.System;
using Jiaowu.Api.Infrastructure.BackgroundJobs;
using Jiaowu.Api.Infrastructure.Grades;
using Jiaowu.Api.Infrastructure.Configuration;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Caching;
@@ -22,10 +24,11 @@ using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
using Swashbuckle.AspNetCore.SwaggerUI;
using System.Threading.RateLimiting;
EnvironmentFile.Load();
@@ -61,6 +64,13 @@ if (confirmProductionDemoData && !seedDemoData)
}
var builder = WebApplication.CreateBuilder(args);
var swaggerDocumentVersion = typeof(Program).Assembly
.GetCustomAttributes(
typeof(System.Reflection.AssemblyMetadataAttribute),
inherit: false)
.OfType<System.Reflection.AssemblyMetadataAttribute>()
.SingleOrDefault(x => x.Key == "SwaggerDocumentVersion")?.Value
?? "v1";
if (seedDemoData && builder.Environment.IsDevelopment())
{
@@ -223,6 +233,7 @@ if (backgroundJobOptions.PollIntervalMilliseconds is < 100 or > 30000 ||
backgroundJobOptions.ExamArrangementConcurrency is < 1 or > 16 ||
backgroundJobOptions.ExamSignInExportConcurrency is < 1 or > 16 ||
backgroundJobOptions.ExamPublishConcurrency is < 1 or > 16 ||
backgroundJobOptions.CourseGradeStatisticsRefreshConcurrency is < 1 or > 16 ||
backgroundJobOptions.ProcessingAttemptLimit is < 1 or > 100 ||
backgroundJobOptions.MaintenanceIntervalSeconds is < 10 or > 3600 ||
backgroundJobOptions.CompletedRetentionDays is < 1 or > 3650 ||
@@ -411,6 +422,7 @@ builder.Services.AddScoped<DatabaseInitializer>();
builder.Services.AddScoped<DemoDataSeeder>();
builder.Services.AddScoped<DevelopmentSqliteMigrator>();
builder.Services.AddScoped<TimetableDataService>();
builder.Services.AddScoped<PublishedTimetableProjectionService>();
builder.Services.AddScoped<AutomaticScheduleGenerator>();
builder.Services.AddScoped<PersonalCalendarService>();
builder.Services.AddScoped<ClassroomReservationAvailabilityService>();
@@ -425,6 +437,10 @@ builder.Services.AddScoped<MakeupExamAutoJobProcessor>();
builder.Services.AddScoped<ExamArrangementJobProcessor>();
builder.Services.AddScoped<ExamSignInExportJobProcessor>();
builder.Services.AddScoped<ExamPublishJobProcessor>();
builder.Services.AddScoped<CourseGradeStatisticsRefreshJobProcessor>();
builder.Services.AddScoped<CourseGradeStatisticsRefreshScheduler>();
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddHostedService<CourseGradeStatisticsRefreshWorker>();
builder.Services.AddSingleton<BackgroundJobTelemetry>();
builder.Services.AddScoped<BackgroundJobMonitoringService>();
builder.Services.AddScoped<OperationalHealthService>();
@@ -605,10 +621,10 @@ builder.Services.AddControllers()
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
options.SwaggerDoc(swaggerDocumentVersion, new OpenApiInfo
{
Title = "大学教务管理系统 API",
Version = "v1"
Version = swaggerDocumentVersion
});
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
@@ -618,17 +634,10 @@ builder.Services.AddSwaggerGen(options =>
BearerFormat = "JWT",
In = ParameterLocation.Header
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
options.AddSecurityRequirement(_ => new OpenApiSecurityRequirement
{
[
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
}
new OpenApiSecuritySchemeReference("Bearer", null, null)
] = []
});
});
@@ -637,11 +646,37 @@ var app = builder.Build();
app.UseExceptionHandler();
app.UseResponseCompression();
if (app.Environment.IsDevelopment())
app.Use(async (context, next) =>
{
app.UseSwagger();
app.UseSwaggerUI();
if (context.Request.Path.StartsWithSegments("/swagger"))
{
var isEnabled = await context.RequestServices
.GetRequiredService<AppDbContext>()
.SystemFeatureSettings
.AsNoTracking()
.Where(x => x.Key == SystemFeatureKeys.SwaggerDocumentation)
.Select(x => (bool?)x.IsEnabled)
.SingleOrDefaultAsync(context.RequestAborted) ?? false;
if (!isEnabled)
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
return;
}
}
await next();
});
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint(
$"/swagger/{swaggerDocumentVersion}/swagger.json",
$"大学教务管理系统 API {swaggerDocumentVersion}");
options.DocExpansion(DocExpansion.None);
options.DefaultModelsExpandDepth(-1);
options.DefaultModelExpandDepth(1);
options.EnableFilter();
});
app.UseDefaultFiles();
app.UseStaticFiles(new StaticFileOptions
+1
View File
@@ -56,6 +56,7 @@
"SchedulePublishConcurrency": 1,
"MakeupExamAutoConcurrency": 1,
"ExamArrangementConcurrency": 1,
"CourseGradeStatisticsRefreshConcurrency": 1,
"Exchange": "jiaowu.background-jobs",
"QueuePrefix": "jiaowu.background-jobs",
"UseQuorumQueues": true,
@@ -171,7 +171,8 @@ public sealed class AutomaticScheduleGeneratorTests
Name = "实验室 101",
Building = building,
Capacity = 40,
RoomType = "实验室"
RoomType = "实验室",
TeachingVenueNature = TeachingVenueNature.Laboratory
};
var course = new Course
{
@@ -0,0 +1,176 @@
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.System;
using Jiaowu.Api.Infrastructure.Grades;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
namespace Jiaowu.Api.Tests;
public sealed class CourseGradeStatisticsRefreshSchedulerTests
{
[Fact]
public async Task EnqueueDueAsync_UsesPersistentScheduleAndHonorsInterval()
{
await using var connection = new SqliteConnection("Data Source=:memory:");
await connection.OpenAsync();
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlite(connection)
.Options;
await using var db = new AppDbContext(options);
await db.Database.EnsureCreatedAsync();
var scheduler = new CourseGradeStatisticsRefreshScheduler(
db,
NullLogger<CourseGradeStatisticsRefreshScheduler>.Instance);
var now = new DateTime(2026, 8, 9, 12, 0, 0, DateTimeKind.Utc);
await scheduler.EnqueueDueAsync(now, CancellationToken.None);
var setting = Assert.Single(await db.CourseGradeStatisticsRefreshSettings.ToListAsync());
Assert.True(setting.IsEnabled);
Assert.Equal(now, setting.LastRunAt);
await scheduler.EnqueueDueAsync(now.AddMinutes(1), CancellationToken.None);
Assert.Equal(now, setting.LastRunAt);
}
[Fact]
public async Task EnqueueStaleAsync_GroupsByCourseTerm_AndSkipsActiveTarget()
{
await using var connection = new SqliteConnection("Data Source=:memory:");
await connection.OpenAsync();
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlite(connection)
.Options;
await using var db = new AppDbContext(options);
await db.Database.EnsureCreatedAsync();
var college = new College { Code = "SCHEDULE", Name = "定时任务学院" };
var major = new Major
{
Code = "SCHEDULE-M",
Name = "定时任务专业",
College = college,
DegreeType = "本科"
};
var administrativeClass = new AdministrativeClass
{
Code = "SCHEDULE-C",
Name = "定时任务一班",
Major = major,
Grade = 2026
};
var student = new Student
{
StudentNumber = "SCHEDULE-001",
Name = "定时任务学生",
AdministrativeClass = administrativeClass,
EnrollmentYear = 2026,
EnrollmentDate = new DateOnly(2026, 9, 1)
};
var course = new Course
{
Code = "SCHEDULE-COURSE",
Name = "定时任务课程",
College = college,
Credits = 2,
TotalHours = 32,
LectureHours = 32
};
var term = new AcademicTerm
{
Code = "2026-A",
Name = "2026-2027 学年第一学期",
AcademicYear = "2026-2027",
Season = TermSeason.Autumn,
StartDate = new DateOnly(2026, 9, 1),
EndDate = new DateOnly(2027, 1, 15)
};
var firstTask = new TeachingTask
{
TaskNumber = "SCHEDULE-T1",
Name = "定时任务教学班一",
Course = course,
AcademicTerm = term,
Capacity = 30
};
var secondTask = new TeachingTask
{
TaskNumber = "SCHEDULE-T2",
Name = "定时任务教学班二",
Course = course,
AcademicTerm = term,
Capacity = 30
};
var firstSheet = PublishedSheet(firstTask, student, 80m);
var secondSheet = PublishedSheet(secondTask, student, 90m);
db.GradeSheets.AddRange(firstSheet, secondSheet);
await db.SaveChangesAsync();
var scheduler = new CourseGradeStatisticsRefreshScheduler(
db,
NullLogger<CourseGradeStatisticsRefreshScheduler>.Instance);
var queued = await scheduler.EnqueueStaleAsync(100, CancellationToken.None);
var queuedAgain = await scheduler.EnqueueStaleAsync(100, CancellationToken.None);
Assert.Equal(1, queued);
Assert.Equal(0, queuedAgain);
var job = Assert.Single(await db.CourseGradeStatisticsRefreshJobs.ToListAsync());
var outbox = Assert.Single(await db.BackgroundJobOutboxMessages.ToListAsync());
Assert.Equal(BackgroundJobKind.CourseGradeStatisticsRefresh, outbox.JobKind);
job.Status = CourseGradeStatisticsRefreshJobStatus.Succeeded;
db.TeachingTaskGradeStatistics.AddRange(
FreshStatistic(firstSheet, course, term),
FreshStatistic(secondSheet, course, term));
await db.SaveChangesAsync();
var queuedAfterFreshStatistics = await scheduler.EnqueueStaleAsync(
100,
CancellationToken.None);
Assert.Equal(0, queuedAfterFreshStatistics);
Assert.Single(await db.CourseGradeStatisticsRefreshJobs.ToListAsync());
}
private static GradeSheet PublishedSheet(
TeachingTask task,
Student student,
decimal score)
{
var sheet = new GradeSheet
{
TeachingTask = task,
Status = GradeSheetStatus.Published,
PublishedAt = DateTime.UtcNow
};
sheet.Records.Add(new GradeRecord
{
GradeSheet = sheet,
Student = student,
TotalScore = score,
GradePoint = 3m
});
return sheet;
}
private static TeachingTaskGradeStatistic FreshStatistic(
GradeSheet sheet,
Course course,
AcademicTerm term) => new()
{
GradeSheetId = sheet.Id,
TeachingTaskId = sheet.TeachingTaskId,
CourseId = course.Id,
AcademicTermId = term.Id,
StudentCount = 1,
PassedCount = 1,
HighestScore = 80m,
AverageScore = 80m,
MedianScore = 80m,
LowestScore = 80m,
PassRate = 100m,
CalculatedAt = DateTime.UtcNow.AddMinutes(1)
};
}
@@ -205,6 +205,79 @@ public sealed class CourseSelectionsControllerTests
x.Grade == 2026));
}
[Fact]
public async Task Student_options_include_an_administrator_assigned_offering_outside_the_students_class_scope()
{
await using var connection = new SqliteConnection("Data Source=:memory:");
await connection.OpenAsync();
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlite(connection)
.Options;
await using var db = new AppDbContext(options);
await db.Database.EnsureCreatedAsync();
var data = await SeedFullOfferingAsync(db);
var originalClass = await db.AdministrativeClasses.SingleAsync();
var otherClass = new AdministrativeClass
{
Code = "CS2026-02",
Name = "计科 2026-2 班",
MajorId = originalClass.MajorId,
Grade = 2026
};
var taskId = await db.CourseSelectionOfferings
.Where(x => x.Id == data.OfferingId)
.Select(x => x.TeachingTaskId)
.SingleAsync();
var task = await db.TeachingTasks
.Include(x => x.Classes)
.SingleAsync(x => x.Id == taskId);
task.Classes.Clear();
task.Classes.Add(new TeachingTaskClass { AdministrativeClassId = otherClass.Id });
task.SchedulingMode = TeachingTaskSchedulingMode.Standard;
var termId = await db.CourseSelectionRounds
.Where(x => x.Id == data.RoundId)
.Select(x => x.AcademicTermId)
.SingleAsync();
var plan = new SchedulePlan
{
AcademicTermId = termId,
Name = "正式课表",
Version = "V1",
Status = SchedulePlanStatus.Published,
PublishedAt = DateTime.UtcNow
};
db.AddRange(otherClass, plan);
await db.SaveChangesAsync();
db.ScheduleEntries.Add(new ScheduleEntry
{
SchedulePlanId = plan.Id,
TeachingTaskId = task.Id,
DayOfWeek = 1,
StartPeriod = 1,
PeriodCount = 2,
StartWeek = 1,
EndWeek = 16,
WeekPattern = WeekPattern.All
});
await db.SaveChangesAsync();
db.ChangeTracker.Clear();
var controller = new CourseSelectionsController(
db,
new StudentDataScope(data.EnrolledUserId));
var result = Assert.IsType<OkObjectResult>(await controller.GetStudentOptions(
data.RoundId,
CancellationToken.None));
var offerings = ReadProperty<IEnumerable<StudentOfferingDto>>(
result.Value, "Offerings");
var assignedOffering = Assert.Single(offerings);
Assert.Equal(data.OfferingId, assignedOffering.Id);
Assert.Equal(CourseEnrollmentStatus.Enrolled, assignedOffering.EnrollmentStatus);
Assert.Single(assignedOffering.Schedules);
}
private static async Task<SeededSelection> SeedFullOfferingAsync(AppDbContext db)
{
var college = new College { Code = "CS", Name = "计算机学院" };
@@ -358,6 +431,14 @@ public sealed class CourseSelectionsControllerTests
return Assert.IsType<int>(property.GetValue(value));
}
private static T ReadProperty<T>(object? value, string propertyName)
{
Assert.NotNull(value);
var property = value.GetType().GetProperty(propertyName);
Assert.NotNull(property);
return Assert.IsAssignableFrom<T>(property.GetValue(value));
}
private static Student CreateStudent(
string number,
string name,
@@ -2,6 +2,7 @@ using Jiaowu.Api.Controllers;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Grades;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.Sqlite;
@@ -11,6 +12,160 @@ namespace Jiaowu.Api.Tests;
public sealed class ExperimentGradesControllerTests
{
[Fact]
public async Task AssignedTeacher_CanSubmitExperimentGradeSheet()
{
await using var fixture = await ExperimentGradeFixture.CreateAsync();
var project = new ExperimentProject
{
TeachingTaskId = fixture.Task.Id,
Code = "LAB-TEACHER",
Name = "教师提交实验",
ArrangementMode = ExperimentArrangementMode.Centralized,
StartDate = fixture.Term.StartDate,
EndDate = fixture.Term.EndDate,
Status = ExperimentProjectStatus.Published,
PublishedAt = DateTime.UtcNow
};
fixture.Db.ExperimentProjects.Add(project);
await fixture.Db.SaveChangesAsync();
var admin = fixture.ExperimentGrades(fixture.AdminScope);
await admin.CreateSheet(
new ExperimentGradeSheetRequest(
project.Id,
1,
60,
[new ExperimentGradeItemRequest(
"操作",
ExperimentGradeItemKind.Operation,
100)]),
CancellationToken.None);
var sheet = await fixture.Db.ExperimentGradeSheets
.Include(x => x.Items)
.Include(x => x.Records)
.ThenInclude(x => x.ItemScores)
.SingleAsync();
var record = Assert.Single(sheet.Records);
var item = Assert.Single(sheet.Items);
var teacher = fixture.ExperimentGrades(fixture.TeacherScope);
Assert.IsType<NoContentResult>(await teacher.UpdateRecords(
sheet.Id,
new ExperimentGradeRecordsRequest(
[
new ExperimentGradeRecordRequest(
record.Id,
ExperimentParticipationStatus.Completed,
false,
1,
null,
null,
false,
null,
[new ExperimentGradeItemScoreRequest(item.Id, 85, null)])
]),
CancellationToken.None));
fixture.Db.ChangeTracker.Clear();
Assert.IsType<NoContentResult>(await teacher.Submit(
sheet.Id,
CancellationToken.None));
}
[Fact]
public async Task ManagementList_IsPagedFilteredAndCollegeScoped()
{
await using var fixture = await ExperimentGradeFixture.CreateAsync();
var collegeId = await fixture.Db.Courses
.Where(x => x.Id == fixture.Task.CourseId)
.Select(x => x.CollegeId)
.SingleAsync();
for (var index = 1; index <= 12; index++)
{
fixture.Db.ExperimentProjects.Add(new ExperimentProject
{
TeachingTaskId = fixture.Task.Id,
Code = $"LAB-{index:00}",
Name = $"分页实验 {index:00}",
ArrangementMode = ExperimentArrangementMode.Centralized,
StartDate = fixture.Term.StartDate,
EndDate = fixture.Term.EndDate,
Status = ExperimentProjectStatus.Published,
PublishedAt = DateTime.UtcNow
});
}
var otherCollege = new College { Code = "OTHER", Name = "其他学院" };
var otherCourse = new Course
{
CollegeId = otherCollege.Id,
Code = "OTHER-LAB",
Name = "其他学院实验",
Credits = 1,
TotalHours = 16,
PracticeHours = 16,
Nature = CourseNature.Practice,
AssessmentMethod = AssessmentMethod.Assessment
};
var otherTask = new TeachingTask
{
AcademicTermId = fixture.Term.Id,
CourseId = otherCourse.Id,
TaskNumber = "OTHER-LAB-01",
Name = "其他学院实验班",
Capacity = 20,
Status = TeachingTaskStatus.Published
};
var otherProject = new ExperimentProject
{
TeachingTaskId = otherTask.Id,
Code = "FOREIGN-LAB",
Name = "不可见实验",
ArrangementMode = ExperimentArrangementMode.Centralized,
StartDate = fixture.Term.StartDate,
EndDate = fixture.Term.EndDate,
Status = ExperimentProjectStatus.Published,
PublishedAt = DateTime.UtcNow
};
fixture.Db.AddRange(otherCollege, otherCourse, otherTask, otherProject);
await fixture.Db.SaveChangesAsync();
fixture.Db.ChangeTracker.Clear();
var collegeScope = new FixedScope(new CurrentUserScope(
Guid.NewGuid(),
"学院管理员",
collegeId,
DataScope.College,
new HashSet<string>([SystemRoles.CollegeAdmin])));
var controller = fixture.ExperimentGrades(collegeScope);
var page = Assert.IsType<OkObjectResult>(await controller.GetManagement(
null,
null,
null,
null,
1,
10,
CancellationToken.None));
Assert.Equal(12, Property<int>(page.Value, "Total"));
Assert.Equal(10, Property<System.Collections.IEnumerable>(
page.Value,
"Items").Cast<object>().Count());
var filtered = Assert.IsType<OkObjectResult>(await controller.GetManagement(
null,
null,
null,
"LAB-12",
1,
10,
CancellationToken.None));
Assert.Equal(1, Property<int>(filtered.Value, "Total"));
}
private static T Property<T>(object? value, string name) =>
Assert.IsAssignableFrom<T>(
value!.GetType().GetProperty(name)!.GetValue(value));
[Fact]
public async Task IndependentExperimentGrade_CanPublishAndImportAsCourseSnapshot()
{
@@ -108,7 +263,17 @@ public sealed class ExperimentGradesControllerTests
var studentResult = await fixture
.ExperimentGrades(fixture.StudentScope)
.GetMine(CancellationToken.None);
Assert.IsType<OkObjectResult>(studentResult);
var studentResultOk = Assert.IsType<OkObjectResult>(studentResult);
var studentCourse = Assert.Single(
Assert.IsAssignableFrom<System.Collections.IEnumerable>(
studentResultOk.Value).Cast<object>());
Assert.Equal(85m, Property<decimal>(
studentCourse,
"ExperimentCourseScore"));
var persistedExperimentCourseGrade = await fixture.Db
.ExperimentCourseGrades.SingleAsync();
Assert.Equal(85m, persistedExperimentCourseGrade.WeightedAverageScore);
Assert.Equal(1, persistedExperimentCourseGrade.PublishedProjectCount);
var courseSheet = new GradeSheet
{
@@ -176,6 +341,83 @@ public sealed class ExperimentGradesControllerTests
Assert.IsType<ConflictObjectResult>(manualOverride);
}
[Fact]
public async Task ExperimentCourseGrade_IsPersistedAsWeightedAverage()
{
await using var fixture = await ExperimentGradeFixture.CreateAsync();
var firstProject = new ExperimentProject
{
TeachingTaskId = fixture.Task.Id,
Code = "LAB-W1",
Name = "低权重实验",
ArrangementMode = ExperimentArrangementMode.Centralized,
StartDate = fixture.Term.StartDate,
EndDate = fixture.Term.EndDate,
Status = ExperimentProjectStatus.Published,
GradeSheet = new ExperimentGradeSheet
{
ContributionWeight = 1,
Status = ExperimentGradeSheetStatus.Published,
Records =
[
new ExperimentGradeRecord
{
StudentId = fixture.Student.Id,
ParticipationStatus = ExperimentParticipationStatus.Completed,
TotalScore = 80,
IsPassed = true
}
]
}
};
var secondProject = new ExperimentProject
{
TeachingTaskId = fixture.Task.Id,
Code = "LAB-W2",
Name = "高权重实验",
ArrangementMode = ExperimentArrangementMode.Centralized,
StartDate = fixture.Term.StartDate,
EndDate = fixture.Term.EndDate,
Status = ExperimentProjectStatus.Published,
GradeSheet = new ExperimentGradeSheet
{
ContributionWeight = 3,
Status = ExperimentGradeSheetStatus.Published,
Records =
[
new ExperimentGradeRecord
{
StudentId = fixture.Student.Id,
ParticipationStatus = ExperimentParticipationStatus.Completed,
TotalScore = 90,
IsPassed = true
}
]
}
};
fixture.Db.AddRange(firstProject, secondProject);
await fixture.Db.SaveChangesAsync();
await ExperimentGradeAggregationService.RefreshTeachingTaskAsync(
fixture.Db,
fixture.Task.Id,
CancellationToken.None);
var persisted = await fixture.Db.ExperimentCourseGrades.SingleAsync();
Assert.Equal(87.5m, persisted.WeightedAverageScore);
Assert.Equal(4m, persisted.TotalWeight);
Assert.Equal(2, persisted.PublishedProjectCount);
firstProject.GradeSheet!.Records.Single().TotalScore = 0;
await fixture.Db.SaveChangesAsync();
var referenced = await ExperimentGradeAggregationService.CalculateAsync(
fixture.Db,
fixture.Task.Id,
[fixture.Student.Id],
CancellationToken.None);
Assert.Equal(87.5m, referenced.Scores[fixture.Student.Id]);
}
[Fact]
public async Task SelfScheduledSheet_SyncsOnlyActiveBookings()
{
@@ -260,6 +502,7 @@ public sealed class ExperimentGradesControllerTests
Student student,
Classroom classroom,
ICurrentUserDataScope adminScope,
ICurrentUserDataScope teacherScope,
ICurrentUserDataScope studentScope)
{
Connection = connection;
@@ -269,6 +512,7 @@ public sealed class ExperimentGradesControllerTests
Student = student;
Classroom = classroom;
AdminScope = adminScope;
TeacherScope = teacherScope;
StudentScope = studentScope;
}
@@ -279,6 +523,7 @@ public sealed class ExperimentGradesControllerTests
public Student Student { get; }
public Classroom Classroom { get; }
public ICurrentUserDataScope AdminScope { get; }
public ICurrentUserDataScope TeacherScope { get; }
public ICurrentUserDataScope StudentScope { get; }
public static async Task<ExperimentGradeFixture> CreateAsync()
@@ -410,6 +655,7 @@ public sealed class ExperimentGradesControllerTests
student,
classroom,
Scope(admin, SystemRoles.SuperAdmin, DataScope.All),
Scope(teacherUser, SystemRoles.Teacher, DataScope.Self),
Scope(studentUser, SystemRoles.Student, DataScope.Self));
}
@@ -20,7 +20,7 @@ public sealed class ExperimentsControllerTests
var result = await controller.CreateProjects(
fixture.BatchProjectRequest(
ExperimentArrangementMode.Centralized),
ExperimentArrangementMode.SelfScheduled),
CancellationToken.None);
Assert.IsType<CreatedResult>(result);
@@ -37,6 +37,53 @@ public sealed class ExperimentsControllerTests
});
}
[Fact]
public async Task CentralizedBatchProjects_CreatesOneProjectForEveryScheduledExperimentLesson()
{
await using var fixture = await ExperimentFixture.CreateAsync();
fixture.Db.ScheduleEntries.Add(new ScheduleEntry
{
SchedulePlanId = fixture.ScheduleEntry.SchedulePlanId,
TeachingTaskId = fixture.Task.Id,
Kind = ScheduleEntryKind.Experiment,
ClassroomId = fixture.SecondClassroom.Id,
DayOfWeek = 3,
StartPeriod = 5,
PeriodCount = 2,
StartWeek = 1,
EndWeek = 8,
WeekPattern = WeekPattern.All
});
await fixture.Db.SaveChangesAsync();
var result = await fixture.Controller(fixture.ManagerScope).CreateProjects(
new ExperimentProjectBatchRequest(
[fixture.Task.Id],
"LAB-ALL",
"全部课表实验",
ExperimentArrangementMode.Centralized,
null,
null,
fixture.Term.StartDate,
fixture.Term.StartDate.AddDays(14)),
CancellationToken.None);
Assert.IsType<CreatedResult>(result);
var projects = await fixture.Db.ExperimentProjects
.Where(x => x.Code == "LAB-ALL")
.OrderBy(x => x.ScheduleEntryId)
.ToListAsync();
Assert.Equal(16, projects.Count);
Assert.All(projects, project =>
{
Assert.Equal(fixture.Task.Id, project.TeachingTaskId);
Assert.Equal(ExperimentArrangementMode.Centralized, project.ArrangementMode);
Assert.NotNull(project.ScheduleEntryId);
});
Assert.Equal(2, projects.Select(x => x.ScheduleEntryId).Distinct().Count());
Assert.Equal(8, projects.Select(x => x.ScheduleWeek).Distinct().Count());
}
[Fact]
public async Task BatchSessions_RollsBackAllRowsWhenOneConflicts()
{
@@ -119,7 +166,7 @@ public sealed class ExperimentsControllerTests
}
[Fact]
public async Task CentralizedProject_PublishesAndUsesTeachingTaskRoster()
public async Task CentralizedProject_PublishesWhenBoundToPublishedExperimentSchedule()
{
await using var fixture = await ExperimentFixture.CreateAsync();
var controller = fixture.Controller(fixture.ManagerScope);
@@ -133,10 +180,7 @@ public sealed class ExperimentsControllerTests
project.Id,
fixture.SessionRequest(1, 2, 10),
CancellationToken.None);
Assert.IsType<CreatedResult>(sessionResult);
Assert.Equal(
1,
(await fixture.Db.ExperimentSessions.SingleAsync()).Capacity);
Assert.IsType<ConflictObjectResult>(sessionResult);
var published = await controller.PublishProject(
project.Id,
@@ -146,13 +190,7 @@ public sealed class ExperimentsControllerTests
ExperimentProjectStatus.Published,
(await fixture.Db.ExperimentProjects.SingleAsync()).Status);
var session = await fixture.Db.ExperimentSessions.SingleAsync();
var participants = await controller.GetParticipants(
session.Id,
CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(participants);
var rows = Assert.IsAssignableFrom<IEnumerable<object>>(ok.Value);
Assert.Single(rows);
Assert.Empty(await fixture.Db.ExperimentSessions.ToListAsync());
}
[Fact]
@@ -333,11 +371,10 @@ public sealed class ExperimentsControllerTests
CancellationToken.None);
Assert.NotNull(timetable);
Assert.Equal(2, timetable.ExperimentEntries.Count);
Assert.Contains(
timetable.ExperimentEntries,
x => x.ExperimentArrangementMode ==
ExperimentArrangementMode.Centralized);
Assert.Single(timetable.ExperimentEntries);
Assert.Equal(
ExperimentArrangementMode.SelfScheduled,
timetable.ExperimentEntries[0].ExperimentArrangementMode);
Assert.Contains(
timetable.ExperimentEntries,
x => x.Id == selfSession.Id &&
@@ -380,10 +417,7 @@ public sealed class ExperimentsControllerTests
CancellationToken.None);
Assert.NotNull(timetable);
Assert.Single(timetable.ExperimentEntries);
Assert.Equal(
ExperimentArrangementMode.Centralized,
timetable.ExperimentEntries[0].ExperimentArrangementMode);
Assert.Empty(timetable.ExperimentEntries);
}
private sealed class ExperimentFixture : IAsyncDisposable
@@ -395,6 +429,7 @@ public sealed class ExperimentsControllerTests
TeachingTask task,
Classroom classroom,
Classroom secondClassroom,
ScheduleEntry scheduleEntry,
ICurrentUserDataScope managerScope,
ICurrentUserDataScope studentScope)
{
@@ -404,6 +439,7 @@ public sealed class ExperimentsControllerTests
Task = task;
Classroom = classroom;
SecondClassroom = secondClassroom;
ScheduleEntry = scheduleEntry;
ManagerScope = managerScope;
StudentScope = studentScope;
}
@@ -414,6 +450,7 @@ public sealed class ExperimentsControllerTests
public TeachingTask Task { get; }
public Classroom Classroom { get; }
public Classroom SecondClassroom { get; }
public ScheduleEntry ScheduleEntry { get; }
public ICurrentUserDataScope ManagerScope { get; }
public ICurrentUserDataScope StudentScope { get; }
@@ -441,14 +478,16 @@ public sealed class ExperimentsControllerTests
Code = "LAB101",
Name = "实验室 101",
BuildingId = building.Id,
Capacity = 40
Capacity = 40,
TeachingVenueNature = TeachingVenueNature.Laboratory
};
var secondClassroom = new Classroom
{
Code = "LAB102",
Name = "实验室 102",
BuildingId = building.Id,
Capacity = 40
Capacity = 40,
TeachingVenueNature = TeachingVenueNature.Laboratory
};
var college = new College { Code = "CS", Name = "计算机学院" };
manager.CollegeId = college.Id;
@@ -564,6 +603,27 @@ public sealed class ExperimentsControllerTests
});
}
await db.SaveChangesAsync();
var scheduleEntry = new ScheduleEntry
{
SchedulePlan = new SchedulePlan
{
AcademicTermId = term.Id,
Name = "已发布实验课表",
Version = "LAB-1",
Status = SchedulePlanStatus.Published
},
TeachingTaskId = task.Id,
Kind = ScheduleEntryKind.Experiment,
ClassroomId = classroom.Id,
DayOfWeek = 1,
StartPeriod = 10,
PeriodCount = 2,
StartWeek = 1,
EndWeek = 8,
WeekPattern = WeekPattern.All
};
db.ScheduleEntries.Add(scheduleEntry);
await db.SaveChangesAsync();
return new ExperimentFixture(
connection,
@@ -572,6 +632,7 @@ public sealed class ExperimentsControllerTests
task,
classroom,
secondClassroom,
scheduleEntry,
Scope(
manager,
SystemRoles.CollegeAdmin,
@@ -600,7 +661,8 @@ public sealed class ExperimentsControllerTests
"完成规定实验项目。",
"携带校园卡。",
Term.StartDate,
Term.StartDate.AddDays(14));
Term.StartDate.AddDays(14),
mode == ExperimentArrangementMode.Centralized ? ScheduleEntry.Id : null);
public ExperimentProjectBatchRequest BatchProjectRequest(
ExperimentArrangementMode mode) =>
@@ -0,0 +1,44 @@
using DocumentFormat.OpenXml.Packaging;
using Jiaowu.Api.Controllers;
using Jiaowu.Api.Infrastructure.Grades;
namespace Jiaowu.Api.Tests;
public sealed class GradeAnalysisWordReportGeneratorTests
{
[Fact]
public void Generate_CreatesReadableDocxWithAnalysisSectionsAndCharts()
{
var now = new DateTime(2026, 8, 9, 10, 30, 0, DateTimeKind.Local);
var summary = new GradeAnalyticsController.TeachingClassMetrics(
10, 9, 2, 98m, 78.5m, 80m, 52m, 12.34m, 90m, 20m, now,
[
new("059", 0, 60, 1),
new("6069", 60, 70, 2),
new("7079", 70, 80, 2),
new("8089", 80, 90, 3),
new("90100", 90, null, 2)
]);
var report = new GradeAnalyticsController.TeachingClassAnalysisReport(
false, Guid.NewGuid(), Guid.NewGuid(), "TASK-01", "计算机一班",
"CS101", "程序设计", "2026-2027 学年第一学期", summary,
[new(Guid.NewGuid(), Guid.NewGuid(), "TASK-01", "计算机一班", "张老师", "计科一班", 10, 98m, 78.5m, 80m, 52m, 12.34m, 90m, 20m, true)],
[new("全校", "全校同课程", 100, 100m, 76m, 45m, 88m)],
[new(Guid.NewGuid(), "2026-2027 学年第一学期", 100, 76m, 88m, 18m, new(10, 78.5m, 90m, 20m))],
new(2.5m, 2m, 76m, 88m));
var bytes = GradeAnalysisWordReportGenerator.Generate(report, now);
Assert.True(bytes.Length > 10_000);
using var stream = new MemoryStream(bytes);
using var document = WordprocessingDocument.Open(stream, false);
var text = document.MainDocumentPart!.Document.InnerText;
Assert.Contains("成绩分析报告", text);
Assert.Contains("同课程教学班对比", text);
Assert.Contains("各范围基准", text);
Assert.Contains("历年成绩趋势", text);
Assert.Equal(3, document.MainDocumentPart.ImageParts.Count());
Assert.Equal(2, document.MainDocumentPart.HeaderParts.Count());
Assert.Equal(2, document.MainDocumentPart.FooterParts.Count());
}
}
@@ -10,10 +10,10 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="xunit" Version="2.5.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3" />
<PackageReference Include="coverlet.collector" Version="10.0.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.8.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5" />
</ItemGroup>
<ItemGroup>
@@ -235,6 +235,39 @@ public sealed class MySqlMigrationTests
StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void MySql_experiment_batch_project_query_is_translatable()
{
using var db = new AppDbContext(CreateMySqlOptions());
var projectIds = new[]
{
Guid.Parse("11111111-1111-1111-1111-111111111111"),
Guid.Parse("22222222-2222-2222-2222-222222222222")
};
var accessibleTaskIds = db.TeachingTasks.Select(x => x.Id);
var sql = db.ExperimentProjects
.Where(x => accessibleTaskIds.Contains(x.TeachingTaskId))
.Include(x => x.TeachingTask)
.ThenInclude(x => x!.AcademicTerm)
.WhereIn(projectIds, x => x.Id)
.ToQueryString();
Assert.Contains(
"ExperimentProjects",
sql,
StringComparison.OrdinalIgnoreCase);
Assert.Contains(" IN (", sql, StringComparison.OrdinalIgnoreCase);
Assert.Contains(
projectIds[0].ToString(),
sql,
StringComparison.OrdinalIgnoreCase);
Assert.Contains(
projectIds[1].ToString(),
sql,
StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void MySql_index_names_fit_the_server_identifier_limit()
{
@@ -33,6 +33,39 @@ public sealed class OperationsControllerTests
Assert.Equal(SystemRoles.SuperAdmin, authorize.Roles);
}
[Fact]
public async Task Swagger_documentation_is_closed_by_default_and_can_be_enabled()
{
var root = CreateTemporaryRoot();
try
{
await using var fixture = await OperationsFixture.CreateAsync(root);
var initial = await fixture.Controller.GetSwaggerSettings(
CancellationToken.None);
var initialSettings = Assert.IsType<SwaggerDocumentationSettings>(
Assert.IsType<OkObjectResult>(initial.Result).Value);
Assert.False(initialSettings.IsEnabled);
var updated = await fixture.Controller.UpdateSwaggerSettings(
new UpdateSwaggerDocumentationSettings(true),
CancellationToken.None);
var updatedSettings = Assert.IsType<SwaggerDocumentationSettings>(
Assert.IsType<OkObjectResult>(updated.Result).Value);
Assert.True(updatedSettings.IsEnabled);
var persisted = await fixture.Controller.GetSwaggerSettings(
CancellationToken.None);
var persistedSettings = Assert.IsType<SwaggerDocumentationSettings>(
Assert.IsType<OkObjectResult>(persisted.Result).Value);
Assert.True(persistedSettings.IsEnabled);
}
finally
{
DeleteTemporaryRoot(root);
}
}
[Fact]
public async Task Audit_and_failed_job_queries_return_operational_records()
{
@@ -85,13 +85,19 @@ public sealed class ScheduleSettingsControllerTests
[classroom.Id],
false,
null,
null),
null,
UpdateExperimentClassroomScope: true,
AllowedExperimentVenueNatures: TeachingVenueNature.Laboratory,
AllowedExperimentClassroomIds: [classroom.Id],
ExperimentRequiredCampusId: campus.Id,
ExperimentRequiredBuildingId: building.Id),
CancellationToken.None);
Assert.IsType<OkObjectResult>(result);
db.ChangeTracker.Clear();
var constraints = await db.TeachingTaskScheduleConstraints
.Include(item => item.AllowedClassrooms)
.Include(item => item.AllowedExperimentClassrooms)
.OrderBy(item => item.TeachingTaskId)
.ToListAsync();
Assert.Equal(2, constraints.Count);
@@ -103,6 +109,11 @@ public sealed class ScheduleSettingsControllerTests
Assert.Equal(
classroom.Id,
Assert.Single(constraint.AllowedClassrooms).ClassroomId);
Assert.Equal(campus.Id, constraint.ExperimentRequiredCampusId);
Assert.Equal(building.Id, constraint.ExperimentRequiredBuildingId);
Assert.Equal(
classroom.Id,
Assert.Single(constraint.AllowedExperimentClassrooms).ClassroomId);
});
}
@@ -46,7 +46,8 @@ public sealed class SchedulesControllerTests
Name = "实验室 201",
Building = building,
Capacity = 40,
RoomType = "实验室"
RoomType = "实验室",
TeachingVenueNature = TeachingVenueNature.Laboratory
};
var course = new Course
{
@@ -227,6 +227,7 @@ public sealed class TeachingWorkflowRosterTests
Assert.IsType<CreatedResult>(attendanceResult);
Assert.Equal(1, await db.AttendanceRecords.CountAsync());
db.ChangeTracker.Clear();
var grades = new GradesController(db, scope);
var gradeResult = await grades.CreateSheet(
new GradeSheetRequest(task.Id, 40, 60, []),
@@ -234,6 +235,51 @@ public sealed class TeachingWorkflowRosterTests
Assert.IsType<CreatedResult>(gradeResult);
Assert.Equal(1, await db.GradeRecords.CountAsync());
var makeupPlan = new MakeupExamPlan
{
AcademicTermId = term.Id,
Name = "补考成绩录入测试",
Status = MakeupExamPlanStatus.Published,
PublishedAt = DateTime.UtcNow
};
var makeupSession = new MakeupExamSession
{
MakeupExamPlanId = makeupPlan.Id,
TeachingTaskId = task.Id,
ExamDate = new DateOnly(2027, 2, 20),
StartPeriod = 1,
PeriodCount = 2,
StartsAt = new DateTime(2027, 2, 20, 8, 0, 0, DateTimeKind.Utc),
EndsAt = new DateTime(2027, 2, 20, 9, 50, 0, DateTimeKind.Utc),
Enrollments =
[
new MakeupExamEnrollment
{
StudentId = student.Id,
Reason = MakeupReason.Failed
}
]
};
makeupPlan.Sessions.Add(makeupSession);
db.MakeupExamPlans.Add(makeupPlan);
await db.SaveChangesAsync();
db.ChangeTracker.Clear();
var makeup = new MakeupExamsController(
db,
scope,
new MakeupExamEligibilityService(db));
Assert.IsType<NoContentResult>(await makeup.RecordScores(
makeupSession.Id,
[new RecordMakeupScoreRequest(student.Id, 75)],
CancellationToken.None));
Assert.Equal(
75,
await db.MakeupExamEnrollments
.Where(x => x.MakeupExamSessionId == makeupSession.Id)
.Select(x => x.MakeupScore)
.SingleAsync());
var selections = new CourseSelectionsController(db, scope);
Assert.Single(ReadItems(await selections.GetMyTeachingTasks(
term.Id,
@@ -0,0 +1,78 @@
using System.Collections;
using Jiaowu.Api.Controllers;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace Jiaowu.Api.Tests;
public sealed class WarningRulePersistenceTests
{
[Fact]
public async Task SaveRules_PersistsAutoCheck_AndReturnsNumericType()
{
await using var connection = new SqliteConnection("Data Source=:memory:");
await connection.OpenAsync();
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlite(connection)
.Options;
await using var db = new AppDbContext(options);
await db.Database.EnsureCreatedAsync();
var term = new AcademicTerm
{
Code = "WARN-TERM",
Name = "预警测试学期",
AcademicYear = "2026-2027",
Season = TermSeason.Autumn,
StartDate = new DateOnly(2026, 9, 1),
EndDate = new DateOnly(2027, 1, 15)
};
db.AcademicTerms.Add(term);
await db.SaveChangesAsync();
var controller = new WarningsController(db, new AllDataScope());
var saveResult = await controller.SaveRules(term.Id,
[
new WarningRuleDto(
WarningType.FailedCredits,
"不及格学分",
2m,
true,
true,
true,
null,
true,
1,
9,
30)
], CancellationToken.None);
Assert.IsType<NoContentResult>(saveResult);
db.ChangeTracker.Clear();
var persisted = Assert.Single(await db.WarningRules.AsNoTracking().ToListAsync());
Assert.True(persisted.AutoCheckEnabled);
Assert.Equal(1, persisted.CheckDayOfWeek);
Assert.Equal(9, persisted.CheckHour);
Assert.Equal(30, persisted.CheckMinute);
var getResult = await controller.GetRules(term.Id, CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(getResult);
var row = Assert.Single(Assert.IsAssignableFrom<IEnumerable>(ok.Value).Cast<object>());
var type = row.GetType().GetProperty("Type")?.GetValue(row);
Assert.Equal(1, Assert.IsType<int>(type));
}
private sealed class AllDataScope : ICurrentUserDataScope
{
public CurrentUserScope Current { get; } = new(
Guid.NewGuid(),
"测试管理员",
null,
DataScope.All,
new HashSet<string>([SystemRoles.SuperAdmin]));
}
}

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