修改培养方案

This commit is contained in:
2026-08-09 17:59:10 +08:00 Unverified
parent ae24371d7f
commit 25a1480739
11 changed files with 7483 additions and 9 deletions
@@ -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);
@@ -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);
@@ -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,
@@ -51,7 +51,8 @@ public static class GradeAnalysisWordReportGenerator
DateTime generatedAt,
HeaderFooterIds headerFooterIds)
{
var body = mainPart.Document.Body!;
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));
@@ -467,9 +468,10 @@ public static class GradeAnalysisWordReportGenerator
{
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 path = new SKPath();
path.MoveTo(points[0]);
foreach (var point in points.Skip(1)) path.LineTo(point);
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++)
{
@@ -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>();
@@ -540,6 +542,27 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
.HasForeignKey(x => x.ClassroomId)
.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 });
@@ -96,6 +96,8 @@ public sealed class DevelopmentSqliteMigrator(
"20260809_50_experiment_classroom_constraints";
private const string SeparateExperimentClassroomScopeMigration =
"20260809_51_separate_experiment_classroom_scope";
private const string ReusableCourseGroupsMigration =
"20260809_52_reusable_course_groups";
public async Task MigrateAsync(CancellationToken cancellationToken = default)
{
@@ -701,6 +703,14 @@ public sealed class DevelopmentSqliteMigrator(
? []
: 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);
}
private async Task ApplyMigrationAsync(
@@ -3003,4 +3013,41 @@ public sealed class DevelopmentSqliteMigrator(
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,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");
}
}
}
@@ -1098,6 +1098,68 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.ToTable("CourseGradeStatisticsRefreshJobs");
});
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")
@@ -5252,6 +5314,25 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
.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")
@@ -6550,6 +6631,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");