修改培养方案

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");
+15
View File
@@ -433,6 +433,8 @@ button { cursor: pointer; }
.module-toolbar span { margin-top: 4px; color: var(--muted); font-size: 10px; }
.curriculum-view-actions { display: flex; align-items: center; gap: 10px; }
.curriculum-view-actions .el-button + .el-button { margin-left: 0; }
.page-intro-actions { display: flex; flex-wrap: wrap; gap: 8px; }
.page-intro-actions .el-button + .el-button { margin-left: 0; }
.curriculum-module { margin-top: 12px; border: 1px solid var(--line); }
.curriculum-module > header { min-height: 72px; padding: 13px 16px; display: flex; align-items: center; gap: 18px; background: #f8fafb; border-bottom: 1px solid var(--line); }
.curriculum-module > header > div:first-child { min-width: 160px; }
@@ -459,6 +461,16 @@ button { cursor: pointer; }
.semester-courses li > strong { flex: none; font: 700 15px/1 Consolas, monospace; }
.semester-courses li > strong small { margin-left: 3px; font: 400 9px/1 inherit; }
.semester-empty { margin: 0; padding: 25px 16px; color: var(--muted); font-size: 11px; text-align: center; }
.course-group-manager { min-height: 420px; display: grid; grid-template-columns: 230px minmax(0, 1fr); border: 1px solid var(--line); }
.course-group-manager > aside { padding: 12px; display: grid; align-content: start; gap: 6px; border-right: 1px solid var(--line); background: #fafbfc; }
.course-group-manager > aside > button:not(.el-button) { padding: 11px; display: grid; gap: 4px; text-align: left; border: 1px solid transparent; background: transparent; }
.course-group-manager > aside > button.active { border-color: #b8d9d5; background: #edf8f6; }
.course-group-manager > aside span { color: var(--teal); font: 700 9px/1 Consolas, monospace; }
.course-group-manager > aside b { font-size: 13px; }
.course-group-manager > aside small { color: var(--muted); font-size: 10px; }
.course-group-manager > main { min-width: 0; padding: 16px; }
.course-group-actions { margin: 0 0 18px; }
.course-group-add { margin: 18px 0 10px; display: grid; grid-template-columns: auto minmax(200px, 1fr) auto; align-items: center; gap: 10px; }
.task-summary { min-height: 82px; padding: 15px 22px; display: flex; align-items: center; gap: 28px; color: white; background: linear-gradient(108deg, #17295a, #263f80); }
.task-summary > div { min-width: 170px; display: flex; align-items: baseline; gap: 8px; }
.task-summary span, .task-summary small { color: #b8c1de; font-size: 10px; }
@@ -1303,6 +1315,9 @@ button { cursor: pointer; }
.module-toolbar { align-items: flex-start; flex-direction: column; gap: 12px; }
.curriculum-view-actions { width: 100%; justify-content: space-between; }
.semester-view { grid-template-columns: 1fr; }
.course-group-manager { grid-template-columns: 1fr; }
.course-group-manager > aside { max-height: 220px; overflow-y: auto; border-right: none; border-bottom: 1px solid var(--line); }
.course-group-add { grid-template-columns: 1fr; align-items: stretch; }
.task-summary { align-items: flex-start; flex-direction: column; gap: 12px; }
.task-summary > div { width: 100%; }
.task-summary p { padding: 12px 0 0; border-left: none; border-top: 1px solid rgba(255,255,255,.16); line-height: 1.6; }
+167 -4
View File
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { CopyDocument, Plus, Promotion, Refresh, Search } from '@element-plus/icons-vue'
import { Collection, CopyDocument, Plus, Promotion, Refresh, Search } from '@element-plus/icons-vue'
import http, { apiErrorMessage } from '../api/http'
import { useAuthStore } from '../stores/auth'
@@ -14,16 +14,20 @@ const colleges = ref<any[]>([])
const majors = ref<any[]>([])
const grades = ref<number[]>([])
const courses = ref<any[]>([])
const courseGroups = ref<any[]>([])
const planDialog = ref(false)
const moduleDialog = ref(false)
const courseDialog = ref(false)
const cloneDialog = ref(false)
const courseGroupDialog = ref(false)
const courseGroupImportDialog = ref(false)
const detailView = ref<'structure' | 'semester'>('structure')
const editingPlanId = ref('')
const editingPlanStatus = ref('')
const editingModuleId = ref('')
const editingCourseId = ref('')
const activeModuleId = ref('')
const activeCourseGroupId = ref('')
const query = reactive({
page: 1,
pageSize: 20,
@@ -37,6 +41,9 @@ const planForm = reactive<Record<string, any>>({})
const moduleForm = reactive<Record<string, any>>({})
const courseForm = reactive<Record<string, any>>({})
const cloneForm = reactive<Record<string, any>>({})
const courseGroupForm = reactive<Record<string, any>>({})
const courseGroupCourseForm = reactive<Record<string, any>>({})
const courseGroupImportForm = reactive<Record<string, any>>({})
const statusLabels: Record<string, string> = {
Draft: '草稿',
@@ -48,6 +55,9 @@ const courseTypeLabels: Record<string, string> = {
Elective: '组内选修',
}
const isCollegeAdmin = computed(() => auth.user?.roles.includes('CollegeAdmin') ?? false)
const canManageCourseGroups = computed(() =>
auth.user?.roles.some((role) => role === 'SuperAdmin' || role === 'AcademicAdmin') ?? false,
)
const availableMajors = computed(() => majors.value)
const filteredMajors = computed(() =>
query.collegeId
@@ -69,6 +79,12 @@ const isDraft = computed(() => selected.value?.status === 'Draft')
const isPublished = computed(() => selected.value?.status === 'Published')
const canEdit = computed(() => isDraft.value || isPublished.value)
const isEditingPublished = computed(() => editingPlanStatus.value === 'Published')
const activeCourseGroup = computed(() =>
courseGroups.value.find((group) => group.id === activeCourseGroupId.value) ?? null,
)
const importingCourseGroup = computed(() =>
courseGroups.value.find((group) => group.id === courseGroupImportForm.courseGroupId) ?? null,
)
const configuredCredits = computed(() =>
selected.value?.modules.reduce(
(sum: number, module: any) => sum + Number(module.requiredCredits),
@@ -141,6 +157,97 @@ async function loadDetail(id: string) {
}
}
async function loadCourseGroups() {
try {
courseGroups.value = (await http.get('/course-groups')).data
} catch (error) {
ElMessage.error(apiErrorMessage(error))
}
}
function openCourseGroups() {
courseGroupDialog.value = true
openCourseGroup(activeCourseGroupId.value || undefined)
}
function openCourseGroup(id?: string) {
activeCourseGroupId.value = id ?? ''
const group = courseGroups.value.find((item) => item.id === id)
Object.assign(courseGroupForm, {
code: group?.code ?? '', name: group?.name ?? '', description: group?.description ?? '',
})
courseGroupCourseForm.courseId = undefined
}
async function saveCourseGroup() {
if (!courseGroupForm.code?.trim() || !courseGroupForm.name?.trim()) {
ElMessage.warning('请填写课程组编码和名称。')
return
}
try {
if (activeCourseGroupId.value) {
await http.put(`/course-groups/${activeCourseGroupId.value}`, courseGroupForm)
} else {
const { data } = await http.post('/course-groups', courseGroupForm)
activeCourseGroupId.value = data.id
}
await loadCourseGroups()
openCourseGroup(activeCourseGroupId.value)
ElMessage.success('课程组已保存')
} catch (error) { ElMessage.error(apiErrorMessage(error)) }
}
async function deleteCourseGroup() {
if (!activeCourseGroup.value) return
try {
await ElMessageBox.confirm(`确定删除课程组“${activeCourseGroup.value.name}”吗?`, '删除课程组', { type: 'warning' })
await http.delete(`/course-groups/${activeCourseGroupId.value}`)
await loadCourseGroups()
openCourseGroup()
} catch (error: any) {
if (error !== 'cancel' && error !== 'close') ElMessage.error(apiErrorMessage(error))
}
}
async function addCourseToGroup() {
if (!activeCourseGroupId.value || !courseGroupCourseForm.courseId) return
try {
await http.post(`/course-groups/${activeCourseGroupId.value}/courses`, courseGroupCourseForm)
await loadCourseGroups()
openCourseGroup(activeCourseGroupId.value)
} catch (error) { ElMessage.error(apiErrorMessage(error)) }
}
async function removeCourseFromGroup(courseId: string) {
try {
await http.delete(`/course-groups/${activeCourseGroupId.value}/courses/${courseId}`)
await loadCourseGroups()
openCourseGroup(activeCourseGroupId.value)
} catch (error) { ElMessage.error(apiErrorMessage(error)) }
}
function openCourseGroupImport(moduleId: string) {
activeModuleId.value = moduleId
Object.assign(courseGroupImportForm, {
courseGroupId: courseGroups.value[0]?.id, recommendedSemester: 1, type: 'Elective', notes: '',
})
courseGroupImportDialog.value = true
}
async function importCourseGroup() {
if (!courseGroupImportForm.courseGroupId) {
ElMessage.warning('请选择课程组。')
return
}
if (!await confirmPublishedChange('课程组导入')) return
try {
await http.post(`/curriculum-plans/${selected.value.id}/modules/${activeModuleId.value}/course-groups/${courseGroupImportForm.courseGroupId}`, courseGroupImportForm)
courseGroupImportDialog.value = false
await loadDetail(selected.value.id)
ElMessage.success('课程组已导入,可按本方案需要继续逐门调整。')
} catch (error) { ElMessage.error(apiErrorMessage(error)) }
}
function resetFilters() {
Object.assign(query, {
page: 1,
@@ -356,6 +463,7 @@ onMounted(async () => {
const [optionRes, courseRes] = await Promise.all([
http.get('/curriculum-plans/filter-options'),
http.get('/courses/options'),
loadCourseGroups(),
])
colleges.value = optionRes.data.colleges
majors.value = optionRes.data.majors
@@ -376,7 +484,10 @@ onMounted(async () => {
<h2>培养方案</h2>
<p>由学院按专业和入学年级维护课程结构已发布方案可受控调整修改结果即时生效</p>
</div>
<div class="page-intro-actions">
<el-button v-if="canManageCourseGroups" :icon="Collection" @click="openCourseGroups">课程组</el-button>
<el-button type="primary" :icon="Plus" @click="openPlan()">新建方案</el-button>
</div>
</section>
<section class="maintenance-scope" aria-label="培养方案维护范围">
@@ -455,7 +566,7 @@ onMounted(async () => {
</div>
<div class="plan-actions">
<el-button v-if="canEdit" @click="openPlan(selected)">编辑</el-button>
<el-button :icon="CopyDocument" @click="openClone">复制版本</el-button>
<el-button :icon="CopyDocument" @click="openClone">修订并创建草稿</el-button>
<el-button v-if="isDraft" type="success" :icon="Promotion" @click="publishPlan">发布</el-button>
<el-button v-if="isDraft" type="danger" plain @click="deletePlan">删除</el-button>
</div>
@@ -509,6 +620,7 @@ onMounted(async () => {
<div v-if="canEdit">
<el-button link type="primary" @click="openModule(module)">编辑</el-button>
<el-button link type="danger" @click="deleteModule(module)">删除</el-button>
<el-button size="small" @click="openCourseGroupImport(module.id)">从课程组添加</el-button>
<el-button size="small" :icon="Plus" @click="openCourse(module.id)">添加课程</el-button>
</div>
</header>
@@ -593,7 +705,8 @@ onMounted(async () => {
<template #footer><el-button @click="planDialog = false">取消</el-button><el-button type="primary" @click="savePlan">保存</el-button></template>
</el-dialog>
<el-dialog v-model="cloneDialog" title="复制为新版本" width="520px">
<el-dialog v-model="cloneDialog" title="修订培养方案并创建草稿" width="520px">
<p class="form-help">将完整复制当前方案为独立草稿修订后的课程模块和课程组导入内容均可单独调整不影响原版本</p>
<el-form label-position="top">
<el-form-item label="方案名称" required><el-input v-model="cloneForm.name" /></el-form-item>
<div class="form-grid">
@@ -601,7 +714,7 @@ onMounted(async () => {
<el-form-item label="适用入学年级" required><el-input-number v-model="cloneForm.effectiveGrade" :min="2000" :max="2200" /></el-form-item>
</div>
</el-form>
<template #footer><el-button @click="cloneDialog = false">取消</el-button><el-button type="primary" @click="clonePlan">复制</el-button></template>
<template #footer><el-button @click="cloneDialog = false">取消</el-button><el-button type="primary" @click="clonePlan">创建修订草稿</el-button></template>
</el-dialog>
<el-dialog v-model="moduleDialog" :title="editingModuleId ? '编辑课程模块' : '新增课程模块'" width="520px">
@@ -638,5 +751,55 @@ onMounted(async () => {
</el-form>
<template #footer><el-button @click="courseDialog = false">取消</el-button><el-button type="primary" @click="saveCourse">保存</el-button></template>
</el-dialog>
<el-dialog v-model="courseGroupImportDialog" title="从课程组添加课程" width="560px">
<el-alert type="info" :closable="false" show-icon title="导入后课程会复制到当前方案,可逐门修改建议学期、修读规则和备注,不影响公共课程组。" />
<el-form label-position="top">
<el-form-item label="课程组" required>
<el-select v-model="courseGroupImportForm.courseGroupId" filterable>
<el-option v-for="group in courseGroups" :key="group.id" :label="`${group.code} · ${group.name}${group.courseCount} 门)`" :value="group.id" />
</el-select>
</el-form-item>
<p v-if="importingCourseGroup" class="form-help">将导入{{ importingCourseGroup.courses.map((course: any) => course.courseName).join('、') }}</p>
<div class="form-grid">
<el-form-item label="修读规则"><el-select v-model="courseGroupImportForm.type"><el-option v-for="(label, value) in courseTypeLabels" :key="value" :label="label" :value="value" /></el-select></el-form-item>
<el-form-item label="建议学期"><el-input-number v-model="courseGroupImportForm.recommendedSemester" :min="1" :max="selected?.schoolingYears * 2" /></el-form-item>
</div>
<el-form-item label="统一备注"><el-input v-model="courseGroupImportForm.notes" type="textarea" :rows="2" /></el-form-item>
</el-form>
<template #footer><el-button @click="courseGroupImportDialog = false">取消</el-button><el-button type="primary" @click="importCourseGroup">导入课程组</el-button></template>
</el-dialog>
<el-dialog v-model="courseGroupDialog" title="公共课程组" width="920px">
<div class="course-group-manager">
<aside>
<el-button type="primary" :icon="Plus" @click="openCourseGroup()">新建课程组</el-button>
<button v-for="group in courseGroups" :key="group.id" type="button" :class="{ active: activeCourseGroupId === group.id }" @click="openCourseGroup(group.id)">
<span>{{ group.code }}</span><b>{{ group.name }}</b><small>{{ group.courseCount }} 门课程</small>
</button>
</aside>
<main>
<el-form label-position="top">
<div class="form-grid">
<el-form-item label="课程组编码" required><el-input v-model="courseGroupForm.code" /></el-form-item>
<el-form-item label="课程组名称" required><el-input v-model="courseGroupForm.name" /></el-form-item>
</div>
<el-form-item label="说明"><el-input v-model="courseGroupForm.description" type="textarea" :rows="2" /></el-form-item>
</el-form>
<div class="course-group-actions"><el-button type="primary" @click="saveCourseGroup">保存课程组</el-button><el-button v-if="activeCourseGroup" type="danger" plain @click="deleteCourseGroup">删除</el-button></div>
<div v-if="activeCourseGroup" class="course-group-add">
<b>组内课程</b>
<el-select v-model="courseGroupCourseForm.courseId" filterable placeholder="选择课程加入课程组"><el-option v-for="course in courses" :key="course.id" :label="`${course.code} · ${course.name}`" :value="course.id" /></el-select>
<el-button type="primary" @click="addCourseToGroup">加入</el-button>
</div>
<el-table v-if="activeCourseGroup" :data="activeCourseGroup.courses">
<el-table-column prop="courseCode" label="课程编码" width="120" />
<el-table-column prop="courseName" label="课程名称" />
<el-table-column prop="credits" label="学分" width="80" />
<el-table-column label="操作" width="80"><template #default="{ row }"><el-button link type="danger" @click="removeCourseFromGroup(row.courseId)">移除</el-button></template></el-table-column>
</el-table>
</main>
</div>
</el-dialog>
</div>
</template>