diff --git a/src/Jiaowu.Api/Controllers/WarningsController.cs b/src/Jiaowu.Api/Controllers/WarningsController.cs new file mode 100644 index 0000000..84daebc --- /dev/null +++ b/src/Jiaowu.Api/Controllers/WarningsController.cs @@ -0,0 +1,216 @@ +using System.ComponentModel.DataAnnotations; +using Jiaowu.Api.Domain.Academic; +using Jiaowu.Api.Domain.Identity; +using Jiaowu.Api.Infrastructure.Auth; +using Jiaowu.Api.Infrastructure.Persistence; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; + +namespace Jiaowu.Api.Controllers; + +[ApiController] +[Authorize] +[Route("api/warnings")] +public sealed class WarningsController(AppDbContext db, ICurrentUserDataScope scope) : ControllerBase +{ + private const string Managers = SystemRoles.SuperAdmin + "," + SystemRoles.AcademicAdmin; + + // ═══════════ Rules (admin) ═══════════ + [HttpGet("rules")] + [Authorize(Roles = Managers)] + public async Task 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 }) + .ToListAsync(ct)); + + [HttpPut("rules")] + [Authorize(Roles = Managers)] + public async Task SaveRules(Guid academicTermId, List rules, CancellationToken ct) + { + var existing = await db.WarningRules.Where(x => x.AcademicTermId == academicTermId).ToListAsync(ct); + db.WarningRules.RemoveRange(existing); + foreach (var r in rules) + { + db.WarningRules.Add(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() + }); + } + await db.SaveChangesAsync(ct); + return NoContent(); + } + + // ═══════════ Detection + Records ═══════════ + [HttpPost("detect")] + [Authorize(Roles = Managers)] + public async Task DetectWarnings(Guid academicTermId, CancellationToken ct) + { + var rules = await db.WarningRules.Where(x => x.AcademicTermId == academicTermId && x.IsEnabled).ToListAsync(ct); + if (rules.Count == 0) return Ok(new { Generated = 0, Message = "当前学期无启用的预警规则。" }); + + var studentInfos = await db.Students.Where(x => x.Status == StudentStatus.Active).Select(x => new StudentInfo(x.Id, x.UserId, x.Name, x.AdministrativeClassId)).ToListAsync(ct); + var generated = new List(); + + foreach (var rule in rules) + { + switch (rule.Type) + { + case WarningType.FailedCredits: + generated.AddRange(await DetectFailedCredits(rule, academicTermId, studentInfos, ct)); + break; + case WarningType.LowGPA: + generated.AddRange(await DetectLowGPA(rule, academicTermId, studentInfos, ct)); + break; + case WarningType.Absenteeism: + generated.AddRange(await DetectAbsenteeism(rule, academicTermId, studentInfos, ct)); + break; + case WarningType.GraduationDelay: + generated.AddRange(await DetectGraduationDelay(rule, academicTermId, studentInfos, ct)); + break; + } + } + + if (generated.Count > 0) + { + db.WarningRecords.AddRange(generated); + await db.SaveChangesAsync(ct); + + foreach (var w in generated) + { + var si = studentInfos.First(s => s.Id == w.StudentId); + var r = rules.First(r => r.Type == w.Type); + if (r.NotifyStudent && si.UserId.HasValue) + await NotificationService.SendAsync(db, si.UserId.Value, "学业预警", w.Detail, "/warnings", cancellationToken: ct); + if (r.NotifyCounselor) + { + var counselorId = await db.AdministrativeClasses.Where(c => c.Id == si.ClassId && c.CounselorUserId != null).Select(c => c.CounselorUserId!.Value).FirstOrDefaultAsync(ct); + if (counselorId != default) + await NotificationService.SendAsync(db, counselorId, "学生学业预警", $"{si.Name}:{w.Detail}", "/warnings", cancellationToken: ct); + } + } + } + + return Ok(new { Generated = generated.Count }); + } + + [HttpGet("records")] + [Authorize(Roles = Managers + "," + SystemRoles.Counselor)] + public async Task GetRecords(Guid? academicTermId, WarningType? type, CancellationToken ct) + { + var q = db.WarningRecords.AsNoTracking().AsQueryable(); + if (scope.Current.Scope == DataScope.College || scope.Current.IsInRole(SystemRoles.Counselor)) + { + var classIds = await db.AdministrativeClasses.Where(c => c.CounselorUserId == scope.Current.UserId).Select(c => c.Id).ToListAsync(ct); + if (classIds.Count > 0) + q = q.Where(x => classIds.Contains(x.Student!.AdministrativeClassId)); + else if (scope.Current.RestrictedCollegeId.HasValue) + q = q.Where(x => x.Student!.AdministrativeClass!.Major!.CollegeId == scope.Current.RestrictedCollegeId); + } + 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)); + } + + // ═══════════ Student ═══════════ + [HttpGet("my-warnings")] + [Authorize(Roles = SystemRoles.Student)] + public async Task GetMyWarnings(CancellationToken ct) + { + 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 }) + .ToListAsync(ct)); + } + + [HttpPost("{id:guid}/acknowledge")] + [Authorize(Roles = SystemRoles.Student)] + public async Task Acknowledge(Guid id, [FromBody] AckBody body, CancellationToken ct) + { + var sid = await GetStudentIdAsync(ct); + if (sid is null) return StudentNotFound(); + var w = await db.WarningRecords.FirstOrDefaultAsync(x => x.Id == id && x.StudentId == sid, ct); + if (w is null) return NotFound(); + if (w.Status != WarningStatus.Active) return ConflictProblem("该预警已处理。"); + w.Status = WarningStatus.Acknowledged; + w.AcknowledgedAt = DateTime.UtcNow; + w.AcknowledgeComment = body.Comment?.Trim(); + await db.SaveChangesAsync(ct); + return NoContent(); + } + + // ═══════════ Detection logic ═══════════ + private async Task> DetectFailedCredits(WarningRule rule, Guid termId, List students, CancellationToken ct) + { + var records = new List(); + foreach (var s in students) + { + var failed = await db.GradeRecords.CountAsync(x => x.StudentId == s.Id && x.GradeSheet!.TeachingTask!.AcademicTermId == termId && x.GradeSheet.Status == GradeSheetStatus.Published && x.TotalScore < 60, ct); + if (failed >= rule.Threshold) + { + if (await db.WarningRecords.AnyAsync(x => x.StudentId == s.Id && x.AcademicTermId == termId && x.Type == WarningType.FailedCredits, ct)) continue; + records.Add(new WarningRecord { StudentId = s.Id, Type = rule.Type, TriggerValue = failed, Detail = $"不及格课程 {failed} 门,达到预警阈值 {rule.Threshold} 门。", AcademicTermId = termId }); + } + } + return records; + } + + private async Task> DetectLowGPA(WarningRule rule, Guid termId, List students, CancellationToken ct) + { + var records = new List(); + foreach (var s in students) + { + var grades = await db.GradeRecords.Where(x => x.StudentId == s.Id && x.GradeSheet!.TeachingTask!.AcademicTermId == termId && x.GradeSheet.Status == GradeSheetStatus.Published && x.GradePoint != null).ToListAsync(ct); + if (grades.Count == 0) continue; + var gpa = grades.Average(x => x.GradePoint!.Value); + if (gpa < rule.Threshold) + { + if (await db.WarningRecords.AnyAsync(x => x.StudentId == s.Id && x.AcademicTermId == termId && x.Type == WarningType.LowGPA, ct)) continue; + records.Add(new WarningRecord { StudentId = s.Id, Type = rule.Type, TriggerValue = Math.Round(gpa, 2), Detail = $"平均绩点 {gpa:F2},低于预警阈值 {rule.Threshold}。", AcademicTermId = termId }); + } + } + return records; + } + + private async Task> DetectAbsenteeism(WarningRule rule, Guid termId, List students, CancellationToken ct) + { + var records = new List(); + foreach (var s in students) + { + var absent = await db.AttendanceRecords.CountAsync(x => x.StudentId == s.Id && x.AttendanceSheet!.Status == AttendanceSheetStatus.Submitted && x.AttendanceSheet.TeachingTask!.AcademicTermId == termId && (x.Status == AttendanceStatus.Absent || x.Status == AttendanceStatus.Late), ct); + if (absent >= rule.Threshold) + { + if (await db.WarningRecords.AnyAsync(x => x.StudentId == s.Id && x.AcademicTermId == termId && x.Type == WarningType.Absenteeism, ct)) continue; + records.Add(new WarningRecord { StudentId = s.Id, Type = rule.Type, TriggerValue = absent, Detail = $"缺勤/迟到 {absent} 次,达到预警阈值 {rule.Threshold} 次。", AcademicTermId = termId }); + } + } + return records; + } + + private async Task> DetectGraduationDelay(WarningRule rule, Guid termId, List students, CancellationToken ct) + { + var records = new List(); + foreach (var s in students) + { + var total = await db.GradeRecords.CountAsync(x => x.StudentId == s.Id && x.GradeSheet!.Status == GradeSheetStatus.Published && x.TotalScore < 60, ct); + if (total >= rule.Threshold) + { + if (await db.WarningRecords.AnyAsync(x => x.StudentId == s.Id && x.AcademicTermId == termId && x.Type == WarningType.GraduationDelay, ct)) continue; + records.Add(new WarningRecord { StudentId = s.Id, Type = rule.Type, TriggerValue = total, Detail = $"累计不及格 {total} 门,达到延毕预警阈值 {rule.Threshold} 门。", AcademicTermId = termId }); + } + } + return records; + } + + private async Task GetStudentIdAsync(CancellationToken ct) => await db.Students.Where(s => s.UserId == scope.Current.UserId).Select(s => (Guid?)s.Id).FirstOrDefaultAsync(ct); + private ActionResult StudentNotFound() => Conflict(new ProblemDetails { Title = "未关联学生档案", Status = 409 }); + private ActionResult ConflictProblem(string d) => Conflict(new ProblemDetails { Title = "操作失败", Detail = d, Status = 409 }); +} + +public sealed record StudentInfo(Guid Id, Guid? UserId, string Name, Guid ClassId); +public sealed record WarningRuleDto(WarningType Type, [MaxLength(100)] string Name, decimal Threshold, bool IsEnabled, bool NotifyStudent, bool NotifyCounselor, [MaxLength(300)] string? Description); +public sealed record AckBody([MaxLength(300)] string? Comment); diff --git a/src/Jiaowu.Api/Domain/Academic/WarningEntities.cs b/src/Jiaowu.Api/Domain/Academic/WarningEntities.cs new file mode 100644 index 0000000..2e1452c --- /dev/null +++ b/src/Jiaowu.Api/Domain/Academic/WarningEntities.cs @@ -0,0 +1,45 @@ +using Jiaowu.Api.Domain.Common; + +namespace Jiaowu.Api.Domain.Academic; + +public sealed class WarningRule : EntityBase +{ + public WarningType Type { get; set; } + public required string Name { get; set; } + public decimal Threshold { get; set; } + public bool IsEnabled { get; set; } = true; + public bool NotifyStudent { get; set; } = true; + public bool NotifyCounselor { get; set; } = true; + public Guid AcademicTermId { get; set; } + public AcademicTerm? AcademicTerm { get; set; } + public string? Description { get; set; } +} + +public sealed class WarningRecord : EntityBase +{ + public Guid StudentId { get; set; } + public Student? Student { get; set; } + public WarningType Type { get; set; } + public WarningStatus Status { get; set; } = WarningStatus.Active; + public decimal TriggerValue { get; set; } + public required string Detail { get; set; } + public DateTime? AcknowledgedAt { get; set; } + public string? AcknowledgeComment { get; set; } + public Guid AcademicTermId { get; set; } +} + +public enum WarningType +{ + FailedCredits = 1, + LowGPA = 2, + Absenteeism = 3, + GraduationDelay = 4 +} + +public enum WarningStatus +{ + Active = 1, + Acknowledged = 2, + Resolved = 3, + Dismissed = 4 +} diff --git a/src/Jiaowu.Api/Infrastructure/Persistence/AppDbContext.cs b/src/Jiaowu.Api/Infrastructure/Persistence/AppDbContext.cs index 4f3ccc7..21729fc 100644 --- a/src/Jiaowu.Api/Infrastructure/Persistence/AppDbContext.cs +++ b/src/Jiaowu.Api/Infrastructure/Persistence/AppDbContext.cs @@ -60,6 +60,8 @@ public sealed class AppDbContext(DbContextOptions options) public DbSet DeferredExams => Set(); public DbSet GradeModifications => Set(); public DbSet CourseSubstitutions => Set(); + public DbSet WarningRules => Set(); + public DbSet WarningRecords => Set(); public DbSet Notifications => Set(); public DbSet StudentStatusChanges => Set(); @@ -709,6 +711,26 @@ public sealed class AppDbContext(DbContextOptions options) entity.HasOne(x => x.GradeRecord).WithMany() .HasForeignKey(x => x.GradeRecordId).OnDelete(DeleteBehavior.Restrict); }); + builder.Entity(entity => + { + entity.Property(x => x.Name).HasMaxLength(100); + entity.Property(x => x.Threshold).HasPrecision(7, 2); + entity.Property(x => x.Description).HasMaxLength(300); + entity.HasIndex(x => new { x.AcademicTermId, x.Type }).IsUnique(); + entity.HasOne(x => x.AcademicTerm).WithMany() + .HasForeignKey(x => x.AcademicTermId).OnDelete(DeleteBehavior.Cascade); + }); + builder.Entity(entity => + { + entity.Property(x => x.TriggerValue).HasPrecision(7, 2); + entity.Property(x => x.Detail).HasMaxLength(1000); + entity.Property(x => x.AcknowledgeComment).HasMaxLength(300); + entity.HasIndex(x => new { x.StudentId, x.AcademicTermId, x.Type }).IsUnique(); + entity.HasIndex(x => x.Status); + entity.HasOne(x => x.Student).WithMany() + .HasForeignKey(x => x.StudentId).OnDelete(DeleteBehavior.Restrict); + }); + builder.Entity(entity => { entity.Property(x => x.Reason).HasMaxLength(500); diff --git a/src/Jiaowu.Api/Infrastructure/Persistence/DevelopmentSqliteMigrator.cs b/src/Jiaowu.Api/Infrastructure/Persistence/DevelopmentSqliteMigrator.cs index a5edddc..37b1d93 100644 --- a/src/Jiaowu.Api/Infrastructure/Persistence/DevelopmentSqliteMigrator.cs +++ b/src/Jiaowu.Api/Infrastructure/Persistence/DevelopmentSqliteMigrator.cs @@ -42,6 +42,8 @@ public sealed class DevelopmentSqliteMigrator( "20260725_23_attendance_appeal"; private const string ApprovalTablesMigration = "20260725_24_approval_tables"; + private const string AcademicWarningsMigration = + "20260725_25_academic_warnings"; public async Task MigrateAsync(CancellationToken cancellationToken = default) { @@ -280,6 +282,14 @@ public sealed class DevelopmentSqliteMigrator( ApprovalTablesMigration, approvalTablesExist ? [] : ApprovalTableStatements, cancellationToken); + + var warningRulesExist = await db.Database + .SqlQueryRaw("SELECT COUNT(*) AS \"Value\" FROM sqlite_master WHERE type = 'table' AND name = 'WarningRules'") + .AnyAsync(value => value > 0, cancellationToken); + await ApplyMigrationAsync( + AcademicWarningsMigration, + warningRulesExist ? [] : AcademicWarningStatements, + cancellationToken); } private async Task ApplyMigrationAsync( @@ -1606,4 +1616,13 @@ public sealed class DevelopmentSqliteMigrator( """CREATE UNIQUE INDEX "IX_CourseSubstitutions_StudentId_OriginalCourseId" ON "CourseSubstitutions" ("StudentId", "OriginalCourseId");""", """CREATE INDEX "IX_CourseSubstitutions_Status_CreatedAt" ON "CourseSubstitutions" ("Status", "CreatedAt");""" ]; + + private static readonly string[] AcademicWarningStatements = + [ + """CREATE TABLE "WarningRules" ("Id" TEXT NOT NULL CONSTRAINT "PK_WarningRules" PRIMARY KEY, "Type" INTEGER NOT NULL, "Name" TEXT NOT NULL, "Threshold" TEXT NOT NULL, "IsEnabled" INTEGER NOT NULL, "NotifyStudent" INTEGER NOT NULL, "NotifyCounselor" INTEGER NOT NULL, "AcademicTermId" TEXT NOT NULL, "Description" TEXT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, CONSTRAINT "FK_WarningRules_AcademicTerms" FOREIGN KEY ("AcademicTermId") REFERENCES "AcademicTerms" ("Id") ON DELETE CASCADE);""", + """CREATE UNIQUE INDEX "IX_WarningRules_AcademicTermId_Type" ON "WarningRules" ("AcademicTermId", "Type");""", + """CREATE TABLE "WarningRecords" ("Id" TEXT NOT NULL CONSTRAINT "PK_WarningRecords" PRIMARY KEY, "StudentId" TEXT NOT NULL, "Type" INTEGER NOT NULL, "Status" INTEGER NOT NULL, "TriggerValue" TEXT NOT NULL, "Detail" TEXT NOT NULL, "AcknowledgedAt" TEXT NULL, "AcknowledgeComment" TEXT NULL, "AcademicTermId" TEXT NOT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, CONSTRAINT "FK_WarningRecords_Students" FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id") ON DELETE RESTRICT);""", + """CREATE UNIQUE INDEX "IX_WarningRecords_StudentId_AcademicTermId_Type" ON "WarningRecords" ("StudentId", "AcademicTermId", "Type");""", + """CREATE INDEX "IX_WarningRecords_Status" ON "WarningRecords" ("Status");""" + ]; } diff --git a/src/Jiaowu.Api/Infrastructure/Persistence/Migrations/MySql/20260725190000_AcademicWarnings.cs b/src/Jiaowu.Api/Infrastructure/Persistence/Migrations/MySql/20260725190000_AcademicWarnings.cs new file mode 100644 index 0000000..704b289 --- /dev/null +++ b/src/Jiaowu.Api/Infrastructure/Persistence/Migrations/MySql/20260725190000_AcademicWarnings.cs @@ -0,0 +1,46 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable +namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql +{ + public partial class AcademicWarnings : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable("WarningRules", table => new + { + Id = table.Column(type: "char(36)", nullable: false), + Type = table.Column(type: "int", nullable: false), + Name = table.Column(type: "varchar(100)", maxLength: 100, nullable: false), + Threshold = table.Column(type: "decimal(7,2)", precision: 7, scale: 2, nullable: false), + IsEnabled = table.Column(type: "tinyint(1)", nullable: false), + NotifyStudent = table.Column(type: "tinyint(1)", nullable: false), + NotifyCounselor = table.Column(type: "tinyint(1)", nullable: false), + AcademicTermId = table.Column(type: "char(36)", nullable: false), + Description = table.Column(type: "varchar(300)", maxLength: 300, nullable: true), + CreatedAt = table.Column(type: "datetime(6)", nullable: false), + UpdatedAt = table.Column(type: "datetime(6)", nullable: false) + }, constraints: t => { t.PrimaryKey("PK_WarningRules", x => x.Id); t.ForeignKey("FK_WarningRules_AcademicTerms", x => x.AcademicTermId, "AcademicTerms", "Id", onDelete: ReferentialAction.Cascade); }); + migrationBuilder.CreateIndex("IX_WarningRules_AcademicTermId_Type", "WarningRules", new[] { "AcademicTermId", "Type" }, unique: true); + + migrationBuilder.CreateTable("WarningRecords", table => new + { + Id = table.Column(type: "char(36)", nullable: false), + StudentId = table.Column(type: "char(36)", nullable: false), + Type = table.Column(type: "int", nullable: false), + Status = table.Column(type: "int", nullable: false), + TriggerValue = table.Column(type: "decimal(7,2)", precision: 7, scale: 2, nullable: false), + Detail = table.Column(type: "varchar(1000)", maxLength: 1000, nullable: false), + AcknowledgedAt = table.Column(type: "datetime(6)", nullable: true), + AcknowledgeComment = table.Column(type: "varchar(300)", maxLength: 300, nullable: true), + AcademicTermId = table.Column(type: "char(36)", nullable: false), + CreatedAt = table.Column(type: "datetime(6)", nullable: false), + UpdatedAt = table.Column(type: "datetime(6)", nullable: false) + }, constraints: t => { t.PrimaryKey("PK_WarningRecords", x => x.Id); t.ForeignKey("FK_WarningRecords_Students", x => x.StudentId, "Students", "Id", onDelete: ReferentialAction.Restrict); }); + migrationBuilder.CreateIndex("IX_WarningRecords_StudentId_AcademicTermId_Type", "WarningRecords", new[] { "StudentId", "AcademicTermId", "Type" }, unique: true); + migrationBuilder.CreateIndex("IX_WarningRecords_Status", "WarningRecords", "Status"); + } + protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable("WarningRecords"); migrationBuilder.DropTable("WarningRules"); } + } +} diff --git a/web/src/layouts/AdminLayout.vue b/web/src/layouts/AdminLayout.vue index e3c028a..36559cf 100644 --- a/web/src/layouts/AdminLayout.vue +++ b/web/src/layouts/AdminLayout.vue @@ -152,6 +152,10 @@ const navigationGroups = computed(() => [ hasAnyRole(['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Counselor', 'Teacher', 'Student']), { path: '/approvals', label: '审批中心' }, ), + ...whenVisible( + hasAnyRole(['SuperAdmin', 'AcademicAdmin', 'Counselor', 'Student']), + { path: '/warnings', label: '学业预警' }, + ), ], }, { diff --git a/web/src/router/index.ts b/web/src/router/index.ts index fcd9f92..62771b4 100644 --- a/web/src/router/index.ts +++ b/web/src/router/index.ts @@ -216,6 +216,12 @@ const router = createRouter({ roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Counselor', 'Teacher', 'Student'], }, }, + { + path: 'warnings', + name: 'warnings', + component: () => import('../views/WarningsView.vue'), + meta: { roles: ['SuperAdmin', 'AcademicAdmin', 'Counselor', 'Student'] }, + }, { path: 'student-status-changes', name: 'student-status-changes', diff --git a/web/src/views/WarningsView.vue b/web/src/views/WarningsView.vue new file mode 100644 index 0000000..044fc21 --- /dev/null +++ b/web/src/views/WarningsView.vue @@ -0,0 +1,178 @@ + + + + +