From 1ddfecbeccfbf4ca248af22f6ff7f2ba1d44f286 Mon Sep 17 00:00:00 2001 From: biss Date: Sun, 25 Oct 2026 21:21:36 +0800 Subject: [PATCH] feat: improve filtered exports and server pagination --- .../Controllers/BaseDataExcelController.cs | 52 +++++++- .../CampusRegistrationsController.cs | 34 ++++- .../Controllers/DegreeAwardsController.cs | 18 ++- .../Controllers/DormitoryHygieneController.cs | 28 +++-- .../DormitoryServicesController.cs | 18 ++- .../Controllers/GraduationAuditsController.cs | 22 +++- .../Controllers/OtherExamsController.cs | 68 +++++++++- .../Controllers/PhysicalFitnessController.cs | 72 +++++++++++ .../TimetableManagementController.cs | 8 +- .../Controllers/WarningsController.cs | 118 ++++++++++++++---- .../Infrastructure/Files/DownloadFileName.cs | 11 +- src/Jiaowu.Api/Program.cs | 3 +- .../Jiaowu.Api.Tests/DownloadFileNameTests.cs | 14 ++- web/src/api/excel.ts | 26 +++- web/src/api/pagination.ts | 19 +++ web/src/views/BaseDataView.vue | 20 ++- web/src/views/CampusRegistrationsView.vue | 9 +- web/src/views/CampusWalletManagementView.vue | 6 +- web/src/views/DegreeAwardsView.vue | 29 +++-- web/src/views/DormitoryHygieneView.vue | 20 +-- web/src/views/ExamsView.vue | 7 +- web/src/views/GraduationAuditsView.vue | 30 +++-- web/src/views/MakeupExamsView.vue | 7 +- web/src/views/OtherExamsView.vue | 25 +++- web/src/views/PhysicalFitnessView.vue | 25 +++- web/src/views/WarningsView.vue | 76 +++++++++-- 26 files changed, 645 insertions(+), 120 deletions(-) create mode 100644 web/src/api/pagination.ts diff --git a/src/Jiaowu.Api/Controllers/BaseDataExcelController.cs b/src/Jiaowu.Api/Controllers/BaseDataExcelController.cs index 40f07aa..d3e611c 100644 --- a/src/Jiaowu.Api/Controllers/BaseDataExcelController.cs +++ b/src/Jiaowu.Api/Controllers/BaseDataExcelController.cs @@ -51,10 +51,24 @@ public sealed class BaseDataExcelController(AppDbContext db, IAppCache cache) : } [HttpGet("{kind}/export")] - public async Task Export(string kind, CancellationToken cancellationToken, bool? isArchived = null, string? keyword = null) + public async Task Export( + string kind, + CancellationToken cancellationToken, + bool? isArchived = null, + string? keyword = null, + Guid? collegeId = null, + Guid? majorId = null, + int? grade = null, + Guid? campusId = null, + Guid? buildingId = null, + int? minimumCapacity = null, + TeachingVenueNature? teachingVenueNature = null, + bool? isEnabled = null) { if (!TryGetHeaders(kind, out var headers)) return NotFound(); - var rows = await GetExportRowsAsync(kind, cancellationToken, isArchived, keyword?.Trim()); + var rows = await GetExportRowsAsync(kind, cancellationToken, isArchived, keyword?.Trim(), + collegeId, majorId, grade, campusId, buildingId, minimumCapacity, + teachingVenueNature, isEnabled); var bytes = ExcelWorkbookHelper.Create(KindName(kind), headers, rows); return File(bytes, ExcelWorkbookHelper.ContentType, DownloadFileName.Export(KindName(kind), ".xlsx")); @@ -140,22 +154,42 @@ public sealed class BaseDataExcelController(AppDbContext db, IAppCache cache) : private async Task>> GetExportRowsAsync( string kind, - CancellationToken cancellationToken, bool? isArchived, string? keyword) => + CancellationToken cancellationToken, + bool? isArchived, + string? keyword, + Guid? collegeId, + Guid? majorId, + int? grade, + Guid? campusId, + Guid? buildingId, + int? minimumCapacity, + TeachingVenueNature? teachingVenueNature, + bool? isEnabled) => kind.ToLowerInvariant() switch { - "campuses" => (await db.Campuses.AsNoTracking().OrderBy(x => x.Code) + "campuses" => (await db.Campuses.AsNoTracking() + .Where(x => keyword == null || keyword == "" || x.Code.Contains(keyword) || x.Name.Contains(keyword)) + .OrderBy(x => x.Code) .ToListAsync(cancellationToken)) .Select(x => Row(x.Code, x.Name, x.Address, x.SortOrder, Status(x.IsEnabled))).ToList(), "colleges" => (await db.Colleges.AsNoTracking().Include(x => x.Campus) + .Where(x => keyword == null || keyword == "" || x.Code.Contains(keyword) || x.Name.Contains(keyword) || x.Campus!.Name.Contains(keyword)) .OrderBy(x => x.Code).ToListAsync(cancellationToken)) .Select(x => Row(x.Code, x.Name, x.ShortName, x.Campus?.Code, x.SortOrder, Status(x.IsEnabled))).ToList(), "majors" => (await db.Majors.AsNoTracking().Include(x => x.College) + .Where(x => keyword == null || keyword == "" || x.Code.Contains(keyword) || x.Name.Contains(keyword) || x.College!.Name.Contains(keyword)) .OrderBy(x => x.Code).ToListAsync(cancellationToken)) .Select(x => Row(x.Code, x.Name, x.College!.Code, x.DegreeType, x.SchoolingYears, x.SortOrder, Status(x.IsEnabled))).ToList(), "classes" => (await db.AdministrativeClasses.AsNoTracking().Include(x => x.Major) - .Include(x => x.CounselorUser).OrderBy(x => x.Code).ToListAsync(cancellationToken)) + .Include(x => x.CounselorUser) + .Where(x => !collegeId.HasValue || x.Major!.CollegeId == collegeId.Value) + .Where(x => !majorId.HasValue || x.MajorId == majorId.Value) + .Where(x => !grade.HasValue || x.Grade == grade.Value) + .Where(x => !isEnabled.HasValue || x.IsEnabled == isEnabled.Value) + .Where(x => keyword == null || keyword == "" || x.Code.Contains(keyword) || x.Name.Contains(keyword) || x.Major!.Name.Contains(keyword) || x.Major.College!.Name.Contains(keyword)) + .OrderBy(x => x.Code).ToListAsync(cancellationToken)) .Select(x => Row(x.Code, x.Name, x.Major!.Code, x.Grade, x.CounselorUser?.StaffNumber, x.SortOrder, Status(x.IsEnabled))).ToList(), "terms" => (await db.AcademicTerms.AsNoTracking() @@ -166,15 +200,23 @@ public sealed class BaseDataExcelController(AppDbContext db, IAppCache cache) : .Select(x => Row(x.Code, x.Name, x.AcademicYear, SeasonName(x.Season), x.StartDate, x.EndDate, YesNo(x.IsCurrent), Status(x.IsEnabled))).ToList(), "buildings" => (await db.Buildings.AsNoTracking().Include(x => x.Campus) + .Where(x => keyword == null || keyword == "" || x.Code.Contains(keyword) || x.Name.Contains(keyword) || x.Campus!.Name.Contains(keyword)) .OrderBy(x => x.Code).ToListAsync(cancellationToken)) .Select(x => Row(x.Code, x.Name, x.Campus!.Code, x.SortOrder, Status(x.IsEnabled))).ToList(), "classrooms" => (await db.Classrooms.AsNoTracking().Include(x => x.Building) + .Where(x => !campusId.HasValue || x.Building!.CampusId == campusId.Value) + .Where(x => !buildingId.HasValue || x.BuildingId == buildingId.Value) + .Where(x => !minimumCapacity.HasValue || x.Capacity >= minimumCapacity.Value) + .Where(x => !teachingVenueNature.HasValue || (x.TeachingVenueNature & teachingVenueNature.Value) != 0) + .Where(x => !isEnabled.HasValue || x.IsEnabled == isEnabled.Value) + .Where(x => keyword == null || keyword == "" || x.Code.Contains(keyword) || x.Name.Contains(keyword) || x.Building!.Name.Contains(keyword) || x.Building.Campus!.Name.Contains(keyword)) .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() + .Where(x => keyword == null || keyword == "" || x.Code.Contains(keyword) || x.Name.Contains(keyword)) .OrderBy(x => x.SortOrder).ThenBy(x => x.Code) .ToListAsync(cancellationToken)) .Select(x => Row(x.Code, x.Name, x.SortOrder, Status(x.IsEnabled))).ToList(), diff --git a/src/Jiaowu.Api/Controllers/CampusRegistrationsController.cs b/src/Jiaowu.Api/Controllers/CampusRegistrationsController.cs index c3ba81c..0500f18 100644 --- a/src/Jiaowu.Api/Controllers/CampusRegistrationsController.cs +++ b/src/Jiaowu.Api/Controllers/CampusRegistrationsController.cs @@ -216,11 +216,29 @@ public sealed class CampusRegistrationsController(AppDbContext db, ICurrentUserD [HttpGet("wallets/export.xlsx")] [Authorize(Roles = Managers)] - public async Task ExportWallets(CancellationToken ct) + public async Task ExportWallets( + [FromQuery] string? keyword, + [FromQuery] int? grade, + [FromQuery] Guid? collegeId, + [FromQuery] Guid? majorId, + [FromQuery] Guid? administrativeClassId, + CancellationToken ct) { var students = db.Students.AsNoTracking().AsQueryable(); - if (scope.Current.RestrictedCollegeId is { } collegeId) - students = students.Where(x => x.AdministrativeClass!.Major!.CollegeId == collegeId); + if (scope.Current.RestrictedCollegeId is { } restrictedCollegeId) + { + if (collegeId.HasValue && collegeId != restrictedCollegeId) return Forbid(); + collegeId = restrictedCollegeId; + } + if (collegeId.HasValue) students = students.Where(x => x.AdministrativeClass!.Major!.CollegeId == collegeId); + if (majorId.HasValue) students = students.Where(x => x.AdministrativeClass!.MajorId == majorId); + if (administrativeClassId.HasValue) students = students.Where(x => x.AdministrativeClassId == administrativeClassId); + if (grade.HasValue) students = students.Where(x => x.AdministrativeClass!.Grade == grade); + if (!string.IsNullOrWhiteSpace(keyword)) + { + var term = keyword.Trim(); + students = students.Where(x => x.StudentNumber.Contains(term) || x.Name.Contains(term)); + } var rows = await students.OrderBy(x => x.StudentNumber).Select(x => new { x.StudentNumber, x.Name, CollegeName = x.AdministrativeClass!.Major!.College!.Name, MajorName = x.AdministrativeClass.Major.Name, ClassName = x.AdministrativeClass.Name, Balance = db.CampusWalletAccounts.Where(a => a.StudentId == x.Id).Select(a => (decimal?)a.Balance).FirstOrDefault() ?? 0m }).ToListAsync(ct); return File(ExcelWorkbookHelper.Create("学生余额", ["学号", "姓名", "学院", "专业", "行政班", "当前余额"], rows.Select(x => (IReadOnlyList)[x.StudentNumber, x.Name, x.CollegeName, x.MajorName, x.ClassName, x.Balance])), ExcelWorkbookHelper.ContentType, DownloadFileName.Export("学生余额", ".xlsx")); } @@ -296,9 +314,15 @@ public sealed class CampusRegistrationsController(AppDbContext db, ICurrentUserD [HttpGet("applications/export.xlsx")] [Authorize(Roles = Managers)] - public async Task ExportApplications([FromQuery] Guid? projectId, CancellationToken ct) + public async Task ExportApplications( + [FromQuery] Guid? projectId, + [FromQuery] CampusRegistrationApplicationStatus? status, + CancellationToken ct) { - var rows = await ScopedApplications().AsNoTracking().Where(x => !projectId.HasValue || x.ProjectId == projectId).OrderByDescending(x => x.CreatedAt) + var source = ScopedApplications().AsNoTracking(); + if (projectId.HasValue) source = source.Where(x => x.ProjectId == projectId); + if (status.HasValue) source = source.Where(x => x.Status == status); + var rows = await source.OrderByDescending(x => x.CreatedAt) .Select(x => new { x.Project!.Code, ProjectName = x.Project.Name, x.Student!.StudentNumber, StudentName = x.Student.Name, Status = x.Status.ToString(), x.CreatedAt, Amount = x.PaymentOrder == null ? 0m : x.PaymentOrder.Amount, PaymentStatus = x.PaymentOrder == null ? "—" : x.PaymentOrder.Status.ToString(), x.ReviewComment }).ToListAsync(ct); var content = ExcelWorkbookHelper.Create("校园报名与缴费", ["项目编码", "项目名称", "学号", "姓名", "报名状态", "提交时间", "应收金额", "支付状态", "审核意见"], rows.Select(x => (IReadOnlyList)[x.Code, x.ProjectName, x.StudentNumber, x.StudentName, x.Status, x.CreatedAt, x.Amount, x.PaymentStatus, x.ReviewComment]).ToList()); return File(content, ExcelWorkbookHelper.ContentType, DownloadFileName.Export("校园报名与缴费", ".xlsx")); diff --git a/src/Jiaowu.Api/Controllers/DegreeAwardsController.cs b/src/Jiaowu.Api/Controllers/DegreeAwardsController.cs index 27189ca..818e35b 100644 --- a/src/Jiaowu.Api/Controllers/DegreeAwardsController.cs +++ b/src/Jiaowu.Api/Controllers/DegreeAwardsController.cs @@ -74,6 +74,8 @@ public sealed class DegreeAwardsController( [FromQuery] int pageSize = 20, [FromQuery] string? keyword = null, [FromQuery] DegreeAwardConclusion? conclusion = null, + [FromQuery] int? grade = null, + [FromQuery] Guid? collegeId = null, [FromQuery] Guid? majorId = null, [FromQuery] Guid? administrativeClassId = null, CancellationToken token = default) @@ -84,12 +86,16 @@ public sealed class DegreeAwardsController( var batch = await db.DegreeAwardBatches.AsNoTracking() .FirstOrDefaultAsync(x => x.Id == id, token); if (batch is null) return NotFound(); - var collegeId = RestrictedCollegeId(); + var restrictedCollegeId = RestrictedCollegeId(); var source = db.DegreeAwardResults.AsNoTracking() .Where(x => x.DegreeAwardBatchId == id); - if (collegeId.HasValue) + if (restrictedCollegeId.HasValue) source = source.Where(x => - x.Student!.AdministrativeClass!.Major!.CollegeId == collegeId); + x.Student!.AdministrativeClass!.Major!.CollegeId == restrictedCollegeId); + if (grade.HasValue) + source = source.Where(x => x.Student!.AdministrativeClass!.Grade == grade); + if (collegeId.HasValue) + source = source.Where(x => x.Student!.AdministrativeClass!.Major!.CollegeId == collegeId); if (majorId.HasValue) source = source.Where(x => x.Student!.AdministrativeClass!.MajorId == majorId); if (administrativeClassId.HasValue) @@ -377,6 +383,8 @@ public sealed class DegreeAwardsController( Guid id, [FromQuery] string? keyword, [FromQuery] DegreeAwardConclusion? conclusion, + [FromQuery] int? grade, + [FromQuery] Guid? collegeId, [FromQuery] Guid? majorId, [FromQuery] Guid? administrativeClassId, CancellationToken token) @@ -384,7 +392,9 @@ public sealed class DegreeAwardsController( var batch = await db.DegreeAwardBatches.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id, token); if (batch is null) return NotFound(); var results = db.DegreeAwardResults.AsNoTracking().Where(x => x.DegreeAwardBatchId == id); - var collegeId = RestrictedCollegeId(); + var restrictedCollegeId = RestrictedCollegeId(); + if (restrictedCollegeId.HasValue) results = results.Where(x => x.Student!.AdministrativeClass!.Major!.CollegeId == restrictedCollegeId); + if (grade.HasValue) results = results.Where(x => x.Student!.AdministrativeClass!.Grade == grade); if (collegeId.HasValue) results = results.Where(x => x.Student!.AdministrativeClass!.Major!.CollegeId == collegeId); if (majorId.HasValue) results = results.Where(x => x.Student!.AdministrativeClass!.MajorId == majorId); if (administrativeClassId.HasValue) results = results.Where(x => x.Student!.AdministrativeClassId == administrativeClassId); diff --git a/src/Jiaowu.Api/Controllers/DormitoryHygieneController.cs b/src/Jiaowu.Api/Controllers/DormitoryHygieneController.cs index 383919d..dee642e 100644 --- a/src/Jiaowu.Api/Controllers/DormitoryHygieneController.cs +++ b/src/Jiaowu.Api/Controllers/DormitoryHygieneController.cs @@ -209,22 +209,26 @@ public sealed class DormitoryHygieneController(AppDbContext db, ICurrentUserData [HttpGet("batches/{id:guid}/export.xlsx")] [Authorize(Roles = Viewers)] - public async Task Export(Guid id, CancellationToken ct) + public async Task Export(Guid id, CancellationToken ct, + Guid? buildingId = null, int? floor = null) { var batch = await db.DormitoryHygieneBatches.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id, ct); if (batch is null) return NotFound(); var rooms = ApplyRoomScope(db.DormitoryRooms.AsNoTracking()); - var data = await (from score in db.DormitoryHygieneScores.AsNoTracking() - join room in rooms on score.DormitoryRoomId equals room.Id - where score.DormitoryHygieneBatchId == id - orderby room.DormitoryBuilding!.Code, room.RoomNumber - select new - { - BuildingName = room.DormitoryBuilding!.Name, room.RoomNumber, room.Floor, - score.FloorScore, score.BeddingScore, score.BelongingsScore, - score.FacilitiesScore, score.SafetyScore, score.TotalScore, - score.Grade, score.IsViolation, score.Issues, score.Notes - }).ToListAsync(ct); + var query = from score in db.DormitoryHygieneScores.AsNoTracking() + join room in rooms on score.DormitoryRoomId equals room.Id + where score.DormitoryHygieneBatchId == id + select new { score, room }; + if (buildingId.HasValue) query = query.Where(x => x.room.DormitoryBuildingId == buildingId.Value); + if (floor.HasValue) query = query.Where(x => x.room.Floor == floor.Value); + var data = await query.OrderBy(x => x.room.DormitoryBuilding!.Code).ThenBy(x => x.room.RoomNumber) + .Select(x => new + { + BuildingName = x.room.DormitoryBuilding!.Name, x.room.RoomNumber, x.room.Floor, + x.score.FloorScore, x.score.BeddingScore, x.score.BelongingsScore, + x.score.FacilitiesScore, x.score.SafetyScore, x.score.TotalScore, + x.score.Grade, x.score.IsViolation, x.score.Issues, x.score.Notes + }).ToListAsync(ct); string[] headers = ["宿舍楼", "房间号", "楼层", .. ImportHeaders.Skip(2), "总分", "等级"]; var rows = data.Select(x => (IReadOnlyList) [x.BuildingName, x.RoomNumber, x.Floor, x.FloorScore, x.BeddingScore, x.BelongingsScore, diff --git a/src/Jiaowu.Api/Controllers/DormitoryServicesController.cs b/src/Jiaowu.Api/Controllers/DormitoryServicesController.cs index 69239e4..db61f7d 100644 --- a/src/Jiaowu.Api/Controllers/DormitoryServicesController.cs +++ b/src/Jiaowu.Api/Controllers/DormitoryServicesController.cs @@ -1,4 +1,5 @@ using System.Text.Json; +using Jiaowu.Api.Contracts; using Jiaowu.Api.Domain.Academic; using Jiaowu.Api.Domain.Identity; using Jiaowu.Api.Domain.System; @@ -656,12 +657,14 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat [HttpGet("applications")] [Authorize(Roles = Viewers)] public async Task GetApplications(DormitoryApplicationStatus? status = null, - DormitoryApplicationType? type = null, CancellationToken ct = default) + DormitoryApplicationType? type = null, int? page = null, int? pageSize = null, + CancellationToken ct = default) { var source = ApplyApplicationScope(db.DormitoryApplications.AsNoTracking()); if (status.HasValue) source = source.Where(x => x.Status == status.Value); if (type.HasValue) source = source.Where(x => x.Type == type.Value); - var items = await source.OrderByDescending(x => x.SubmittedAt).Take(500).Select(x => new + var ordered = source.OrderByDescending(x => x.SubmittedAt).ThenByDescending(x => x.Id); + var projection = ordered.Select(x => new { x.Id, x.Type, x.Status, x.Reason, x.SubmittedAt, x.StudentId, x.Student!.StudentNumber, StudentName = x.Student.Name, @@ -671,8 +674,15 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat PreferredBuildingName = x.PreferredBuilding != null ? x.PreferredBuilding.Name : null, PreferredRoomNumber = x.PreferredRoom != null ? x.PreferredRoom.RoomNumber : null, x.CounselorComment, x.CounselorReviewedAt, x.FinalComment, x.FinalReviewedAt, x.TargetBedId - }).ToListAsync(ct); - return Ok(items); + }); + if (!page.HasValue && !pageSize.HasValue) return Ok(await projection.ToListAsync(ct)); + var normalizedPage = Math.Max(1, page ?? 1); + var normalizedPageSize = Math.Clamp(pageSize ?? 20, 1, 100); + var total = await source.CountAsync(ct); + var items = await projection.Skip((normalizedPage - 1) * normalizedPageSize) + .Take(normalizedPageSize).ToListAsync(ct); + return Ok(new PagedResult(items.Cast().ToList(), total, + normalizedPage, normalizedPageSize)); } [HttpGet("applications/mine")] diff --git a/src/Jiaowu.Api/Controllers/GraduationAuditsController.cs b/src/Jiaowu.Api/Controllers/GraduationAuditsController.cs index 4d2957f..fb454c8 100644 --- a/src/Jiaowu.Api/Controllers/GraduationAuditsController.cs +++ b/src/Jiaowu.Api/Controllers/GraduationAuditsController.cs @@ -74,6 +74,8 @@ public sealed class GraduationAuditsController( [FromQuery] int pageSize = 20, [FromQuery] string? keyword = null, [FromQuery] GraduationAuditConclusion? conclusion = null, + [FromQuery] int? grade = null, + [FromQuery] Guid? collegeId = null, [FromQuery] Guid? majorId = null, [FromQuery] Guid? administrativeClassId = null, CancellationToken token = default) @@ -84,12 +86,16 @@ public sealed class GraduationAuditsController( .FirstOrDefaultAsync(x => x.Id == id, token); if (batch is null) return NotFound(); - var collegeId = RestrictedCollegeId(); + var restrictedCollegeId = RestrictedCollegeId(); var results = db.GraduationAuditResults.AsNoTracking() .Where(x => x.GraduationAuditBatchId == id); - if (collegeId.HasValue) + if (restrictedCollegeId.HasValue) results = results.Where(x => - x.Student!.AdministrativeClass!.Major!.CollegeId == collegeId); + x.Student!.AdministrativeClass!.Major!.CollegeId == restrictedCollegeId); + if (grade.HasValue) + results = results.Where(x => x.Student!.AdministrativeClass!.Grade == grade); + if (collegeId.HasValue) + results = results.Where(x => x.Student!.AdministrativeClass!.Major!.CollegeId == collegeId); if (majorId.HasValue) results = results.Where(x => x.Student!.AdministrativeClass!.MajorId == majorId); if (administrativeClassId.HasValue) @@ -409,6 +415,8 @@ public sealed class GraduationAuditsController( Guid id, [FromQuery] string? keyword, [FromQuery] GraduationAuditConclusion? conclusion, + [FromQuery] int? grade, + [FromQuery] Guid? collegeId, [FromQuery] Guid? majorId, [FromQuery] Guid? administrativeClassId, CancellationToken token) @@ -418,9 +426,11 @@ public sealed class GraduationAuditsController( if (batch is null) return NotFound(); var results = db.GraduationAuditResults.AsNoTracking() .Where(x => x.GraduationAuditBatchId == id); - var collegeId = RestrictedCollegeId(); - if (collegeId.HasValue) - results = results.Where(x => x.Student!.AdministrativeClass!.Major!.CollegeId == collegeId); + var restrictedCollegeId = RestrictedCollegeId(); + if (restrictedCollegeId.HasValue) + results = results.Where(x => x.Student!.AdministrativeClass!.Major!.CollegeId == restrictedCollegeId); + if (grade.HasValue) results = results.Where(x => x.Student!.AdministrativeClass!.Grade == grade); + if (collegeId.HasValue) results = results.Where(x => x.Student!.AdministrativeClass!.Major!.CollegeId == collegeId); if (majorId.HasValue) results = results.Where(x => x.Student!.AdministrativeClass!.MajorId == majorId); if (administrativeClassId.HasValue) results = results.Where(x => x.Student!.AdministrativeClassId == administrativeClassId); var normalizedKeyword = keyword?.Trim(); diff --git a/src/Jiaowu.Api/Controllers/OtherExamsController.cs b/src/Jiaowu.Api/Controllers/OtherExamsController.cs index 5211549..fb29da8 100644 --- a/src/Jiaowu.Api/Controllers/OtherExamsController.cs +++ b/src/Jiaowu.Api/Controllers/OtherExamsController.cs @@ -97,7 +97,10 @@ public sealed class OtherExamsController(AppDbContext db, ICurrentUserDataScope [HttpGet("batches/{id:guid}")] [Authorize(Roles = Managers)] - public async Task GetBatch(Guid id, string? cursor = null, int pageSize = 30, CancellationToken ct = default) + public async Task GetBatch( + Guid id, string? keyword = null, int? grade = null, Guid? collegeId = null, + Guid? majorId = null, Guid? administrativeClassId = null, + string? cursor = null, int pageSize = 30, CancellationToken ct = default) { 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); @@ -105,6 +108,15 @@ public sealed class OtherExamsController(AppDbContext db, ICurrentUserDataScope pageSize = Math.Clamp(pageSize, 10, 100); if (!CursorToken.TryDecode(cursor, out var after)) return BadRequest("无效的游标。"); var source = db.OtherExamResults.AsNoTracking().Where(x => x.OtherExamBatchId == id); + if (!string.IsNullOrWhiteSpace(keyword)) + { + var term = keyword.Trim(); + source = source.Where(x => x.Student!.StudentNumber.Contains(term) || x.Student.Name.Contains(term)); + } + if (grade.HasValue) source = source.Where(x => x.Student!.AdministrativeClass!.Grade == grade.Value); + if (collegeId.HasValue) source = source.Where(x => x.Student!.AdministrativeClass!.Major!.CollegeId == collegeId.Value); + if (majorId.HasValue) source = source.Where(x => x.Student!.AdministrativeClass!.MajorId == majorId.Value); + if (administrativeClassId.HasValue) source = source.Where(x => x.Student!.AdministrativeClassId == administrativeClassId.Value); var total = await source.CountAsync(ct); if (after is not null) { @@ -115,7 +127,7 @@ public sealed class OtherExamsController(AppDbContext db, ICurrentUserDataScope .OrderBy(x => x.Student!.StudentNumber) .ThenBy(x => x.Id) .Take(pageSize + 1) - .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); + .Select(x => new { x.Id, x.StudentId, StudentNumber = x.Student!.StudentNumber, StudentName = x.Student.Name, Grade = x.Student.AdministrativeClass!.Grade, CollegeName = x.Student.AdministrativeClass.Major!.College!.Name, MajorName = x.Student.AdministrativeClass.Major.Name, ClassName = x.Student.AdministrativeClass.Name, x.AttemptNumber, x.Score, x.Level, x.IsPassed, x.Notes }).ToListAsync(ct); var hasMore = rows.Count > pageSize; var items = rows.Take(pageSize).Cast().ToArray(); var last = rows.Take(pageSize).LastOrDefault(); @@ -128,6 +140,58 @@ public sealed class OtherExamsController(AppDbContext db, ICurrentUserDataScope }); } + [HttpGet("batches/{id:guid}/result-filter-options")] + [Authorize(Roles = Managers)] + public async Task GetResultFilterOptions(Guid id, CancellationToken ct) + { + if (!await db.OtherExamBatches.AsNoTracking().AnyAsync(x => x.Id == id, ct)) return NotFound(); + var students = db.Students.AsNoTracking() + .Where(student => db.OtherExamResults.Any(result => result.OtherExamBatchId == id && result.StudentId == student.Id)); + return Ok(new + { + Grades = await students.Select(x => x.AdministrativeClass!.Grade).Distinct().OrderByDescending(x => x).ToListAsync(ct), + Colleges = await students.Select(x => new { Id = x.AdministrativeClass!.Major!.CollegeId, x.AdministrativeClass.Major.College!.Name }).Distinct().OrderBy(x => x.Name).ToListAsync(ct), + Majors = await students.Select(x => new { Id = x.AdministrativeClass!.MajorId, x.AdministrativeClass.Major!.Name, x.AdministrativeClass.Major.CollegeId }).Distinct().OrderBy(x => x.Name).ToListAsync(ct), + Classes = await students.Select(x => new { Id = x.AdministrativeClassId, x.AdministrativeClass!.Name, x.AdministrativeClass.Grade, x.AdministrativeClass.MajorId }).Distinct().OrderByDescending(x => x.Grade).ThenBy(x => x.Name).ToListAsync(ct) + }); + } + + [HttpGet("batches/{id:guid}/export.xlsx")] + [Authorize(Roles = Managers)] + public async Task ExportResults( + Guid id, string? keyword = null, int? grade = null, Guid? collegeId = null, + Guid? majorId = null, Guid? administrativeClassId = null, + CancellationToken ct = default) + { + var batch = await db.OtherExamBatches.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id, ct); + if (batch is null) return NotFound(); + var source = db.OtherExamResults.AsNoTracking().Where(x => x.OtherExamBatchId == id); + if (!string.IsNullOrWhiteSpace(keyword)) + { + var term = keyword.Trim(); + source = source.Where(x => x.Student!.StudentNumber.Contains(term) || x.Student.Name.Contains(term)); + } + if (grade.HasValue) source = source.Where(x => x.Student!.AdministrativeClass!.Grade == grade.Value); + if (collegeId.HasValue) source = source.Where(x => x.Student!.AdministrativeClass!.Major!.CollegeId == collegeId.Value); + if (majorId.HasValue) source = source.Where(x => x.Student!.AdministrativeClass!.MajorId == majorId.Value); + if (administrativeClassId.HasValue) source = source.Where(x => x.Student!.AdministrativeClassId == administrativeClassId.Value); + var data = await source.OrderBy(x => x.Student!.StudentNumber).Select(x => new + { + x.Student!.StudentNumber, x.Student.Name, Grade = x.Student.AdministrativeClass!.Grade, + College = x.Student.AdministrativeClass.Major!.College!.Name, + Major = x.Student.AdministrativeClass.Major.Name, Class = x.Student.AdministrativeClass.Name, + x.AttemptNumber, x.Score, x.Level, x.IsPassed, x.Notes + }).ToListAsync(ct); + var rows = data.Select(x => (IReadOnlyList) + [x.StudentNumber, x.Name, x.Grade, x.College, x.Major, x.Class, x.AttemptNumber, + x.Score, x.Level, x.IsPassed.HasValue ? x.IsPassed.Value ? "合格" : "不合格" : null, x.Notes]).ToList(); + var bytes = ExcelWorkbookHelper.Create("其他考试成绩", + ["学号", "姓名", "年级", "学院", "专业", "行政班", "参加次数", "分数", "等级", "合格结果", "备注"], + rows, ["导出内容按当前筛选生成,不受页面游标分页影响。"]); + return File(bytes, ExcelWorkbookHelper.ContentType, + DownloadFileName.Export("其他考试成绩", ".xlsx", batch.ExamCode ?? batch.Name, batch.ExamDate.ToString("yyyyMMdd"))); + } + [HttpPut("batches/{id:guid}/results")] [Authorize(Roles = Managers)] public async Task ReplaceResults(Guid id, ReplaceOtherExamResultsRequest request, CancellationToken ct) diff --git a/src/Jiaowu.Api/Controllers/PhysicalFitnessController.cs b/src/Jiaowu.Api/Controllers/PhysicalFitnessController.cs index 2e6c6ff..cb3fb4e 100644 --- a/src/Jiaowu.Api/Controllers/PhysicalFitnessController.cs +++ b/src/Jiaowu.Api/Controllers/PhysicalFitnessController.cs @@ -101,6 +101,10 @@ public sealed class PhysicalFitnessController(AppDbContext db, ICurrentUserDataS string? keyword = null, PhysicalTestRecordStatus? status = null, PhysicalTestGrade? grade = null, + int? studentGrade = null, + Guid? collegeId = null, + Guid? majorId = null, + Guid? administrativeClassId = null, bool attentionOnly = false, string? cursor = null, int pageSize = 30, @@ -145,6 +149,10 @@ public sealed class PhysicalFitnessController(AppDbContext db, ICurrentUserDataS if (status.HasValue) source = source.Where(x => x.record.Status == status.Value); if (grade.HasValue) source = source.Where(x => x.record.Status == PhysicalTestRecordStatus.Normal && x.record.Grade == grade.Value); + if (studentGrade.HasValue) source = source.Where(x => x.student.AdministrativeClass!.Grade == studentGrade.Value); + if (collegeId.HasValue) source = source.Where(x => x.student.AdministrativeClass!.Major!.CollegeId == collegeId.Value); + if (majorId.HasValue) source = source.Where(x => x.student.AdministrativeClass!.MajorId == majorId.Value); + if (administrativeClassId.HasValue) source = source.Where(x => x.student.AdministrativeClassId == administrativeClassId.Value); if (attentionOnly) source = source.Where(x => x.record.Status != PhysicalTestRecordStatus.Normal || x.record.Grade == PhysicalTestGrade.Fail); var total = await source.CountAsync(ct); @@ -193,6 +201,70 @@ public sealed class PhysicalFitnessController(AppDbContext db, ICurrentUserDataS }); } + [HttpGet("batches/{id:guid}/record-filter-options")] + [Authorize(Roles = Managers)] + public async Task GetRecordFilterOptions(Guid id, CancellationToken ct) + { + if (!await db.PhysicalTestBatches.AsNoTracking().AnyAsync(x => x.Id == id, ct)) return NotFound(); + var students = ApplyStudentScope(db.Students.AsNoTracking()) + .Where(student => db.PhysicalTestRecords.Any(record => record.PhysicalTestBatchId == id && record.StudentId == student.Id)); + return Ok(new + { + Grades = await students.Select(x => x.AdministrativeClass!.Grade).Distinct().OrderByDescending(x => x).ToListAsync(ct), + Colleges = await students.Select(x => new { Id = x.AdministrativeClass!.Major!.CollegeId, x.AdministrativeClass.Major.College!.Name }).Distinct().OrderBy(x => x.Name).ToListAsync(ct), + Majors = await students.Select(x => new { Id = x.AdministrativeClass!.MajorId, x.AdministrativeClass.Major!.Name, x.AdministrativeClass.Major.CollegeId }).Distinct().OrderBy(x => x.Name).ToListAsync(ct), + Classes = await students.Select(x => new { Id = x.AdministrativeClassId, x.AdministrativeClass!.Name, x.AdministrativeClass.Grade, x.AdministrativeClass.MajorId }).Distinct().OrderByDescending(x => x.Grade).ThenBy(x => x.Name).ToListAsync(ct) + }); + } + + [HttpGet("batches/{id:guid}/export.xlsx")] + [Authorize(Roles = Managers)] + public async Task ExportRecords( + Guid id, string? keyword = null, PhysicalTestRecordStatus? status = null, + PhysicalTestGrade? grade = null, int? studentGrade = null, Guid? collegeId = null, + Guid? majorId = null, Guid? administrativeClassId = null, bool attentionOnly = false, + CancellationToken ct = default) + { + var batch = await db.PhysicalTestBatches.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id, ct); + if (batch is null) return NotFound(); + var students = ApplyStudentScope(db.Students.AsNoTracking()); + var source = from record in db.PhysicalTestRecords.AsNoTracking() + join student in students on record.StudentId equals student.Id + where record.PhysicalTestBatchId == id + select new { record, student }; + if (!string.IsNullOrWhiteSpace(keyword)) + { + var term = keyword.Trim(); + source = source.Where(x => x.student.StudentNumber.Contains(term) || x.student.Name.Contains(term)); + } + if (status.HasValue) source = source.Where(x => x.record.Status == status.Value); + if (grade.HasValue) source = source.Where(x => x.record.Status == PhysicalTestRecordStatus.Normal && x.record.Grade == grade.Value); + if (studentGrade.HasValue) source = source.Where(x => x.student.AdministrativeClass!.Grade == studentGrade.Value); + if (collegeId.HasValue) source = source.Where(x => x.student.AdministrativeClass!.Major!.CollegeId == collegeId.Value); + if (majorId.HasValue) source = source.Where(x => x.student.AdministrativeClass!.MajorId == majorId.Value); + if (administrativeClassId.HasValue) source = source.Where(x => x.student.AdministrativeClassId == administrativeClassId.Value); + if (attentionOnly) source = source.Where(x => x.record.Status != PhysicalTestRecordStatus.Normal || x.record.Grade == PhysicalTestGrade.Fail); + var data = await source.OrderBy(x => x.student.StudentNumber).Select(x => new + { + x.student.StudentNumber, x.student.Name, + College = x.student.AdministrativeClass!.Major!.College!.Name, + Major = x.student.AdministrativeClass.Major.Name, + Class = x.student.AdministrativeClass.Name, + StudentGrade = x.student.AdministrativeClass.Grade, + x.record.GradeLevel, x.record.Status, x.record.StandardScore, x.record.BonusScore, + x.record.TotalScore, x.record.Grade, x.record.SpecialReason, x.record.Notes + }).ToListAsync(ct); + var rows = data.Select(x => (IReadOnlyList) + [x.StudentNumber, x.Name, x.StudentGrade, x.College, x.Major, x.Class, x.GradeLevel, + x.Status.ToString(), x.StandardScore, x.BonusScore, x.TotalScore, x.Grade?.ToString(), + x.SpecialReason, x.Notes]).ToList(); + var bytes = ExcelWorkbookHelper.Create("体测成绩", + ["学号", "姓名", "年级", "学院", "专业", "行政班", "大学年级", "体测状态", "标准分", "附加分", "综合成绩", "成绩等级", "特殊原因", "备注"], + rows, ["导出内容按当前筛选和账号数据权限生成,不受页面游标分页影响。"]); + return File(bytes, ExcelWorkbookHelper.ContentType, + DownloadFileName.Export("体测成绩", ".xlsx", batch.AcademicYear, batch.Name)); + } + [HttpGet("students/lookup")] [Authorize(Roles = Managers)] public async Task LookupStudent([Required] string studentNumber, CancellationToken ct) diff --git a/src/Jiaowu.Api/Controllers/TimetableManagementController.cs b/src/Jiaowu.Api/Controllers/TimetableManagementController.cs index 7c0b391..a78a2f9 100644 --- a/src/Jiaowu.Api/Controllers/TimetableManagementController.cs +++ b/src/Jiaowu.Api/Controllers/TimetableManagementController.cs @@ -252,10 +252,14 @@ public sealed class TimetableManagementController( [HttpPost("display-links/export.xlsx")] public async Task ExportDisplayLinks(VenueDisplayLinkExportRequest request, CancellationToken cancellationToken) { - var classroomIds = request.ClassroomIds.Distinct().Take(200).ToArray(); - var buildingIds = request.BuildingIds.Distinct().Take(100).ToArray(); + var classroomIds = request.ClassroomIds.Distinct().ToArray(); + var buildingIds = request.BuildingIds.Distinct().ToArray(); if (classroomIds.Length + buildingIds.Length == 0) return ValidationProblem("请至少选择一个教室或教学楼。", statusCode: StatusCodes.Status400BadRequest); + if (classroomIds.Length > 200) + return ValidationProblem("单次最多导出 200 个教室,请缩小选择范围后重试。", statusCode: StatusCodes.Status400BadRequest); + if (buildingIds.Length > 100) + return ValidationProblem("单次最多导出 100 个教学楼,请缩小选择范围后重试。", statusCode: StatusCodes.Status400BadRequest); var classrooms = await db.Classrooms.AsNoTracking().WhereIn(classroomIds, x => x.Id) .OrderBy(x => x.Building!.Name).ThenBy(x => x.Code) .Select(x => new object?[] { "教室当天课程", x.Building!.Name + " · " + x.Name, "/venue-display/classroom/" + x.Id }) diff --git a/src/Jiaowu.Api/Controllers/WarningsController.cs b/src/Jiaowu.Api/Controllers/WarningsController.cs index 635f562..b4f2ee3 100644 --- a/src/Jiaowu.Api/Controllers/WarningsController.cs +++ b/src/Jiaowu.Api/Controllers/WarningsController.cs @@ -3,6 +3,8 @@ using Jiaowu.Api.Contracts; using Jiaowu.Api.Domain.Academic; using Jiaowu.Api.Domain.Identity; using Jiaowu.Api.Infrastructure.Auth; +using Jiaowu.Api.Infrastructure.Excel; +using Jiaowu.Api.Infrastructure.Files; using Jiaowu.Api.Infrastructure.Persistence; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; @@ -141,6 +143,11 @@ public sealed class WarningsController(AppDbContext db, ICurrentUserDataScope sc public async Task>> GetRecords( Guid? academicTermId, WarningType? type, + string? keyword = null, + int? grade = null, + Guid? collegeId = null, + Guid? majorId = null, + Guid? administrativeClassId = null, string? cursor = null, int pageSize = 20, CancellationToken ct = default) @@ -150,24 +157,18 @@ public sealed class WarningsController(AppDbContext db, ICurrentUserDataScope sc if (!CursorToken.TryDecode(cursor, out var after)) return BadRequest("预警记录游标无效。"); - var q = db.WarningRecords.AsNoTracking().AsQueryable(); - if (scope.Current.Scope == DataScope.College) - { - q = q.Where(x => - x.Student!.AdministrativeClass!.Major!.CollegeId == - scope.Current.RestrictedCollegeId); - } - else if (scope.Current.Scope == DataScope.Class) - { - q = q.Where(x => - x.Student!.AdministrativeClass!.CounselorUserId == scope.Current.UserId); - } - else if (scope.Current.Scope != DataScope.All) - { - q = q.Where(_ => false); - } + var q = ScopedWarningRecords(); if (academicTermId.HasValue) q = q.Where(x => x.AcademicTermId == academicTermId); if (type.HasValue) q = q.Where(x => x.Type == type); + if (!string.IsNullOrWhiteSpace(keyword)) + { + var term = keyword.Trim(); + q = q.Where(x => x.Student!.StudentNumber.Contains(term) || x.Student.Name.Contains(term)); + } + if (grade.HasValue) q = q.Where(x => x.Student!.AdministrativeClass!.Grade == grade.Value); + if (collegeId.HasValue) q = q.Where(x => x.Student!.AdministrativeClass!.Major!.CollegeId == collegeId.Value); + if (majorId.HasValue) q = q.Where(x => x.Student!.AdministrativeClass!.MajorId == majorId.Value); + if (administrativeClassId.HasValue) q = q.Where(x => x.Student!.AdministrativeClassId == administrativeClassId.Value); if (after is not null) { @@ -183,6 +184,9 @@ public sealed class WarningsController(AppDbContext db, ICurrentUserDataScope sc x.StudentId, x.Student!.Name, x.Student.StudentNumber, + x.Student.AdministrativeClass!.Grade, + x.Student.AdministrativeClass.Major!.College!.Name, + x.Student.AdministrativeClass.Major.Name, x.Student.AdministrativeClass!.Name, (int)x.Type, (int)x.Status, @@ -204,6 +208,67 @@ public sealed class WarningsController(AppDbContext db, ICurrentUserDataScope sc pageSize)); } + [HttpGet("records/filter-options")] + [Authorize(Roles = Managers + "," + SystemRoles.Counselor)] + public async Task GetRecordFilterOptions(Guid? academicTermId, CancellationToken ct) + { + var records = ScopedWarningRecords(); + if (academicTermId.HasValue) records = records.Where(x => x.AcademicTermId == academicTermId.Value); + var students = records.Select(x => x.Student!).Distinct(); + return Ok(new + { + Grades = await students.Select(x => x.AdministrativeClass!.Grade).Distinct().OrderByDescending(x => x).ToListAsync(ct), + Colleges = await students.Select(x => new { Id = x.AdministrativeClass!.Major!.CollegeId, x.AdministrativeClass.Major.College!.Name }).Distinct().OrderBy(x => x.Name).ToListAsync(ct), + Majors = await students.Select(x => new { Id = x.AdministrativeClass!.MajorId, x.AdministrativeClass.Major!.Name, x.AdministrativeClass.Major.CollegeId }).Distinct().OrderBy(x => x.Name).ToListAsync(ct), + Classes = await students.Select(x => new { Id = x.AdministrativeClassId, x.AdministrativeClass!.Name, x.AdministrativeClass.Grade, x.AdministrativeClass.MajorId }).Distinct().OrderByDescending(x => x.Grade).ThenBy(x => x.Name).ToListAsync(ct) + }); + } + + [HttpGet("records/export.xlsx")] + [Authorize(Roles = Managers + "," + SystemRoles.Counselor)] + public async Task ExportRecords( + Guid? academicTermId, WarningType? type, string? keyword = null, int? grade = null, + Guid? collegeId = null, Guid? majorId = null, Guid? administrativeClassId = null, + CancellationToken ct = default) + { + var query = ScopedWarningRecords(); + if (academicTermId.HasValue) query = query.Where(x => x.AcademicTermId == academicTermId.Value); + if (type.HasValue) query = query.Where(x => x.Type == type.Value); + if (!string.IsNullOrWhiteSpace(keyword)) + { + var term = keyword.Trim(); + query = query.Where(x => x.Student!.StudentNumber.Contains(term) || x.Student.Name.Contains(term)); + } + if (grade.HasValue) query = query.Where(x => x.Student!.AdministrativeClass!.Grade == grade.Value); + if (collegeId.HasValue) query = query.Where(x => x.Student!.AdministrativeClass!.Major!.CollegeId == collegeId.Value); + if (majorId.HasValue) query = query.Where(x => x.Student!.AdministrativeClass!.MajorId == majorId.Value); + if (administrativeClassId.HasValue) query = query.Where(x => x.Student!.AdministrativeClassId == administrativeClassId.Value); + var data = await query.OrderByDescending(x => x.CreatedAt).ThenByDescending(x => x.Id).Select(x => new + { + x.Student!.StudentNumber, x.Student.Name, Grade = x.Student.AdministrativeClass!.Grade, + College = x.Student.AdministrativeClass.Major!.College!.Name, + Major = x.Student.AdministrativeClass.Major.Name, Class = x.Student.AdministrativeClass.Name, + x.Type, x.Status, x.TriggerValue, x.Detail, x.AcknowledgedAt, x.AcknowledgeComment, x.CreatedAt + }).ToListAsync(ct); + var rows = data.Select(x => (IReadOnlyList) + [x.StudentNumber, x.Name, x.Grade, x.College, x.Major, x.Class, x.Type.ToString(), + x.Status.ToString(), x.TriggerValue, x.Detail, x.AcknowledgedAt, x.AcknowledgeComment, x.CreatedAt]).ToList(); + var bytes = ExcelWorkbookHelper.Create("学业预警记录", + ["学号", "姓名", "年级", "学院", "专业", "行政班", "预警类型", "状态", "触发值", "详情", "确认时间", "确认备注", "生成时间"], + rows, ["导出内容按当前筛选和账号数据权限生成,不受页面游标分页影响。"]); + return File(bytes, ExcelWorkbookHelper.ContentType, DownloadFileName.Export("学业预警记录", ".xlsx")); + } + + private IQueryable ScopedWarningRecords() + { + var query = db.WarningRecords.AsNoTracking().AsQueryable(); + if (scope.Current.Scope == DataScope.College) + return query.Where(x => x.Student!.AdministrativeClass!.Major!.CollegeId == scope.Current.RestrictedCollegeId); + if (scope.Current.Scope == DataScope.Class) + return query.Where(x => x.Student!.AdministrativeClass!.CounselorUserId == scope.Current.UserId); + return scope.Current.Scope == DataScope.All ? query : query.Where(_ => false); + } + private sealed record WarningCursor(DateTime CreatedAt, Guid Id); // ═══════════ Student ═══════════ @@ -254,7 +319,9 @@ public sealed class WarningsController(AppDbContext db, ICurrentUserDataScope sc // ═══════════ Confidential risk disposition ═══════════ [HttpGet("risk-cases")] [Authorize(Roles = Managers + "," + SystemRoles.Counselor)] - public async Task GetRiskCases(bool mineOnly = false, CancellationToken ct = default) + public async Task GetRiskCases( + bool mineOnly = false, int? page = null, int? pageSize = null, + CancellationToken ct = default) { var current = scope.Current; var q = db.AcademicRiskCases.AsNoTracking(); @@ -263,12 +330,18 @@ public sealed class WarningsController(AppDbContext db, ICurrentUserDataScope sc else if (mineOnly) q = q.Where(x => x.AssignedCounselorUserId == current.UserId); - return Ok(await q.OrderBy(x => x.Status).ThenBy(x => x.FollowUpDueDate) - .Select(x => new AcademicRiskCaseListItem(x.Id, x.WarningRecordId, x.StudentId, + var ordered = q.OrderBy(x => x.Status).ThenBy(x => x.FollowUpDueDate).ThenBy(x => x.Id); + var projection = ordered.Select(x => new AcademicRiskCaseListItem(x.Id, x.WarningRecordId, x.StudentId, x.Student!.Name, x.Student.StudentNumber, x.Student.AdministrativeClass!.Name, (int)x.WarningRecord!.Type, (int)x.Status, x.FollowUpDueDate, x.ReviewDate, - x.TaskCompletedAt, x.AssignedCounselorUser!.DisplayName, x.CreatedAt)) - .ToListAsync(ct)); + x.TaskCompletedAt, x.AssignedCounselorUser!.DisplayName, x.CreatedAt)); + if (!page.HasValue && !pageSize.HasValue) return Ok(await projection.ToListAsync(ct)); + var normalizedPage = Math.Max(1, page ?? 1); + var normalizedPageSize = Math.Clamp(pageSize ?? 20, 1, 100); + var total = await q.CountAsync(ct); + var items = await projection.Skip((normalizedPage - 1) * normalizedPageSize) + .Take(normalizedPageSize).ToListAsync(ct); + return Ok(new PagedResult(items, total, normalizedPage, normalizedPageSize)); } [HttpGet("risk-cases/{id:guid}")] @@ -415,6 +488,9 @@ public sealed record WarningRecordListItem( Guid StudentId, string StudentName, string StudentNumber, + int Grade, + string CollegeName, + string MajorName, string ClassName, int Type, int Status, diff --git a/src/Jiaowu.Api/Infrastructure/Files/DownloadFileName.cs b/src/Jiaowu.Api/Infrastructure/Files/DownloadFileName.cs index 86cd563..b5e1ac8 100644 --- a/src/Jiaowu.Api/Infrastructure/Files/DownloadFileName.cs +++ b/src/Jiaowu.Api/Infrastructure/Files/DownloadFileName.cs @@ -27,11 +27,14 @@ public static class DownloadFileName { var segments = new List { Clean(title) }; segments.AddRange(parts.Select(Clean).Where(value => value.Length > 0)); - if (includeTimestamp) - segments.Add(DateTime.Now.ToString("yyyyMMdd-HHmmss")); - + var uniqueSuffix = includeTimestamp + ? $"{DateTimeOffset.UtcNow.ToOffset(TimeSpan.FromHours(8)):yyyyMMdd-HHmmss-fff}-{Guid.NewGuid():N}"[..26].ToUpperInvariant() + : null; var name = string.Join('-', segments.Where(value => value.Length > 0)); - if (name.Length > 180) name = name[..180].TrimEnd('.', ' '); + var suffixLength = uniqueSuffix is null ? 0 : uniqueSuffix.Length + 1; + var maximumBaseLength = Math.Max(1, 180 - suffixLength); + if (name.Length > maximumBaseLength) name = name[..maximumBaseLength].TrimEnd('.', ' ', '-'); + if (uniqueSuffix is not null) name = $"{name}-{uniqueSuffix}"; return $"{name}{NormalizeExtension(extension)}"; } diff --git a/src/Jiaowu.Api/Program.cs b/src/Jiaowu.Api/Program.cs index 9011450..7fa2e30 100644 --- a/src/Jiaowu.Api/Program.cs +++ b/src/Jiaowu.Api/Program.cs @@ -720,7 +720,8 @@ builder.Services.AddCors(options => { policy.WithOrigins(origins) .AllowAnyHeader() - .AllowAnyMethod(); + .AllowAnyMethod() + .WithExposedHeaders("Content-Disposition"); } }); }); diff --git a/tests/Jiaowu.Api.Tests/DownloadFileNameTests.cs b/tests/Jiaowu.Api.Tests/DownloadFileNameTests.cs index 2c5a495..d775604 100644 --- a/tests/Jiaowu.Api.Tests/DownloadFileNameTests.cs +++ b/tests/Jiaowu.Api.Tests/DownloadFileNameTests.cs @@ -5,11 +5,21 @@ namespace Jiaowu.Api.Tests; public sealed class DownloadFileNameTests { [Fact] - public void Export_includes_safe_context_and_a_second_precision_timestamp() + public void Export_includes_safe_context_and_a_unique_human_readable_suffix() { var name = DownloadFileName.Export("课程/名单", "xlsx", " A:B "); - Assert.Matches("^课程-名单-A-B-\\d{8}-\\d{6}\\.xlsx$", name); + Assert.Matches("^课程-名单-A-B-\\d{8}-\\d{6}-\\d{3}-[0-9A-F]{6}\\.xlsx$", name); + } + + [Fact] + public void Export_does_not_repeat_when_created_in_the_same_clock_tick() + { + var names = Enumerable.Range(0, 100) + .Select(_ => DownloadFileName.Export("学生名单", ".xlsx")) + .ToArray(); + + Assert.Equal(names.Length, names.Distinct(StringComparer.Ordinal).Count()); } [Fact] diff --git a/web/src/api/excel.ts b/web/src/api/excel.ts index d8b13a4..0ecc88b 100644 --- a/web/src/api/excel.ts +++ b/web/src/api/excel.ts @@ -9,6 +9,24 @@ function responseFileName(header: string | undefined, fallback: string) { return plain || fallback } +function uniqueFallbackName(path: string, fallback: string) { + if (/template|模板/i.test(path) || !fallback.includes('.')) return fallback + const dot = fallback.lastIndexOf('.') + const now = new Date() + const parts = new Intl.DateTimeFormat('zh-CN', { + timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit', + hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false, + }).formatToParts(now).reduce>((result, item) => { + result[item.type] = item.value + return result + }, {}) + const milliseconds = String(now.getMilliseconds()).padStart(3, '0') + const random = crypto.getRandomValues(new Uint8Array(3)) + const code = Array.from(random, value => value.toString(16).padStart(2, '0')).join('').toUpperCase() + const suffix = `${parts.year}${parts.month}${parts.day}-${parts.hour}${parts.minute}${parts.second}-${milliseconds}-${code}` + return `${fallback.slice(0, dot)}-${suffix}${fallback.slice(dot)}` +} + export async function downloadApiFile( path: string, fallbackName: string, @@ -21,7 +39,9 @@ export async function downloadApiFile( const url = URL.createObjectURL(response.data) const anchor = document.createElement('a') anchor.href = url - anchor.download = responseFileName(response.headers['content-disposition'], fallbackName) + anchor.download = responseFileName( + response.headers['content-disposition'], uniqueFallbackName(path, fallbackName), + ) document.body.appendChild(anchor) anchor.click() anchor.remove() @@ -37,7 +57,9 @@ export async function downloadApiPostFile( const url = URL.createObjectURL(response.data) const anchor = document.createElement('a') anchor.href = url - anchor.download = responseFileName(response.headers['content-disposition'], fallbackName) + anchor.download = responseFileName( + response.headers['content-disposition'], uniqueFallbackName(path, fallbackName), + ) document.body.appendChild(anchor) anchor.click() anchor.remove() diff --git a/web/src/api/pagination.ts b/web/src/api/pagination.ts new file mode 100644 index 0000000..5bca14c --- /dev/null +++ b/web/src/api/pagination.ts @@ -0,0 +1,19 @@ +import http from './http' + +export async function fetchAllPagedItems( + url: string, + params: Record = {}, + pageSize = 100, +): Promise { + const items: T[] = [] + let page = 1 + + for (;;) { + const response = await http.get(url, { params: { ...params, page, pageSize } }) + const batch = (response.data?.items ?? []) as T[] + items.push(...batch) + const total = Number(response.data?.total ?? items.length) + if (batch.length === 0 || items.length >= total) return items + page++ + } +} diff --git a/web/src/views/BaseDataView.vue b/web/src/views/BaseDataView.vue index 2b6c867..425e410 100644 --- a/web/src/views/BaseDataView.vue +++ b/web/src/views/BaseDataView.vue @@ -242,10 +242,28 @@ async function downloadTemplate() { async function exportRows() { try { + const params = active.value === 'classes' + ? { + keyword: keyword.value.trim() || undefined, + collegeId: listFilters.collegeId, majorId: listFilters.majorId, + grade: listFilters.grade, isEnabled: listFilters.isEnabled, + } + : active.value === 'classrooms' + ? { + keyword: keyword.value.trim() || undefined, + campusId: listFilters.campusId, buildingId: listFilters.buildingId, + minimumCapacity: listFilters.minimumCapacity, + teachingVenueNature: listFilters.teachingVenueNature, + isEnabled: listFilters.isEnabled, + } + : { + keyword: keyword.value.trim() || undefined, + isArchived: active.value === 'terms' ? archiveFilter.value : undefined, + } await downloadApiFile( `/base-data/${active.value}/export`, `${title.value}.xlsx`, - { params: active.value === 'terms' ? { isArchived: archiveFilter.value, keyword: keyword.value.trim() || undefined } : undefined }, + { params }, ) ElMessage.success(`${title.value}已导出`) } catch (error) { diff --git a/web/src/views/CampusRegistrationsView.vue b/web/src/views/CampusRegistrationsView.vue index 7cf60c8..89db638 100644 --- a/web/src/views/CampusRegistrationsView.vue +++ b/web/src/views/CampusRegistrationsView.vue @@ -2,6 +2,7 @@ import { computed, onMounted, reactive, ref } from 'vue' import { ElMessage, ElMessageBox } from 'element-plus' import http, { apiErrorMessage } from '../api/http' +import { downloadApiFile } from '../api/excel' import { useAuthStore } from '../stores/auth' type ProjectStatus = 'Draft' | 'Published' | 'Closed' @@ -15,6 +16,8 @@ const isStudent = computed(() => auth.user?.roles.includes('Student') ?? false) const canManage = computed(() => auth.user?.roles.some(x => ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin'].includes(x)) ?? false) const tab = ref(isStudent.value ? 'projects' : 'manage') const projects = ref([]); const mine = ref([]); const applications = ref([]); const applicationsPage = ref(1); const applicationsPageSize = ref(20); const applicationsTotal = ref(0); const loading = ref(false); const dialog = ref(false); const editingId = ref(null) +const applicationProjectId = ref('') +const applicationStatusFilter = ref('') const balance = ref(0) const form = reactive({ code: '', name: '', description: '', registrationStartsAt: '', registrationEndsAt: '', capacity: 50, feeAmount: 0, requiresReview: true, status: 'Draft' as ProjectStatus, contactName: '', contactPhone: '', notes: '' }) const statusLabel: Record = { PendingReview: '待审核', PendingPayment: '待缴费', Confirmed: '已确认', Waitlisted: '候补中', Rejected: '已驳回', Cancelled: '已取消' } @@ -29,7 +32,7 @@ function resetForm(project?: Project) { editingId.value = project?.id ?? null; O async function loadProjects() { const { data } = await http.get('/campus-registrations/projects'); projects.value = data } async function loadMine() { if (isStudent.value) { const { data } = await http.get('/campus-registrations/mine'); mine.value = data } } async function loadWallet() { if (isStudent.value) { const { data } = await http.get('/campus-registrations/wallet/mine'); balance.value = data.balance } } -async function loadApplications() { if (canManage.value) { const { data } = await http.get>('/campus-registrations/applications', { params: { page: applicationsPage.value, pageSize: applicationsPageSize.value } }); applications.value = data.items; applicationsTotal.value = data.total; if (applications.value.length === 0 && applicationsTotal.value > 0 && applicationsPage.value > 1) { applicationsPage.value--; await loadApplications() } } } +async function loadApplications(resetPage = false) { if (canManage.value) { if (resetPage) applicationsPage.value = 1; const { data } = await http.get>('/campus-registrations/applications', { params: { projectId: applicationProjectId.value || undefined, status: applicationStatusFilter.value || undefined, page: applicationsPage.value, pageSize: applicationsPageSize.value } }); applications.value = data.items; applicationsTotal.value = data.total; if (applications.value.length === 0 && applicationsTotal.value > 0 && applicationsPage.value > 1) { applicationsPage.value--; await loadApplications() } } } async function changeApplicationsPage(page: number) { applicationsPage.value = page; await loadApplications() } async function changeApplicationsPageSize(pageSize: number) { applicationsPageSize.value = pageSize; applicationsPage.value = 1; await loadApplications() } async function saveProject() { try { const payload = { ...form, registrationStartsAt: new Date(form.registrationStartsAt).toISOString(), registrationEndsAt: new Date(form.registrationEndsAt).toISOString(), collegeId: null }; if (editingId.value) await http.put(`/campus-registrations/projects/${editingId.value}`, payload); else await http.post('/campus-registrations/projects', payload); ElMessage.success('项目已保存'); dialog.value = false; await loadProjects() } catch (e) { ElMessage.error(apiErrorMessage(e)) } } @@ -38,7 +41,7 @@ async function review(item: Application, approved: boolean) { try { const { valu async function confirmOffline(item: Application) { try { const { value } = await ElMessageBox.prompt('填写线下收款凭据编号(可选)', '确认线下缴费'); await http.post(`/campus-registrations/orders/${item.order!.id}/confirm-offline`, { referenceNumber: value || null, note: null }); ElMessage.success('已确认收款和报名'); await loadApplications() } catch (e) { if (e !== 'cancel' && e !== 'close') ElMessage.error(apiErrorMessage(e)) } } async function cancel(item: Application) { try { await ElMessageBox.confirm('撤销后不可恢复,确定继续吗?', '撤销报名', { type: 'warning' }); await http.post(`/campus-registrations/applications/${item.id}/cancel`); ElMessage.success('报名已撤销'); await loadMine() } catch (e) { if (e !== 'cancel' && e !== 'close') ElMessage.error(apiErrorMessage(e)) } } async function payBalance(item: Application) { try { await ElMessageBox.confirm(`将从校园余额扣除 ${amount(item.order!.amount)},确定支付吗?`, '余额支付', { type: 'warning' }); await http.post(`/campus-registrations/orders/${item.order!.id}/pay-balance`); ElMessage.success('余额支付成功,报名已确认'); await Promise.all([loadMine(), loadWallet(), loadProjects()]) } catch (e) { if (e !== 'cancel' && e !== 'close') ElMessage.error(apiErrorMessage(e)) } } -async function exportApplications() { loading.value = true; try { const response = await http.get('/campus-registrations/applications/export.xlsx', { responseType: 'blob' }); const url = URL.createObjectURL(response.data); const a = document.createElement('a'); a.href = url; a.download = '校园报名与缴费.xlsx'; a.click(); URL.revokeObjectURL(url) } finally { loading.value = false } } +async function exportApplications() { loading.value = true; try { await downloadApiFile('/campus-registrations/applications/export.xlsx', '校园报名与缴费.xlsx', { params: { projectId: applicationProjectId.value || undefined, status: applicationStatusFilter.value || undefined } }) } finally { loading.value = false } } onMounted(async () => { loading.value = true; try { await Promise.all([loadProjects(), loadMine(), loadWallet(), loadApplications()]) } finally { loading.value = false } }) @@ -47,7 +50,7 @@ onMounted(async () => { loading.value = true; try { await Promise.all([loadProje

CAMPUS SERVICES

校园支付与报名

报名、审核、线下缴费确认和名单导出在同一闭环内完成。

新建报名项目

{{ project.code }} · {{ project.collegeName }}

{{ project.description || '暂无项目说明。' }}

报名时间
{{ localDateTime(project.registrationStartsAt) }} 至 {{ localDateTime(project.registrationEndsAt) }}
名额 / 已确认
{{ project.capacity }} / {{ project.confirmedCount }} 人
费用
{{ amount(project.feeAmount) }} {{ project.requiresReview ? '· 需审核' : '· 自动受理' }}
{{ project.isAvailableNow ? '立即报名' : '当前不可报名' }}编辑项目
校园余额{{ amount(balance) }}余额由管理员调整,可用于支付待缴费报名。
-
所有操作均按项目所属学院的数据范围限制。导出当前可见报名
+
所有操作均按项目所属学院的数据范围限制。导出当前筛选
草稿发布关闭
diff --git a/web/src/views/CampusWalletManagementView.vue b/web/src/views/CampusWalletManagementView.vue index 98f7503..654db83 100644 --- a/web/src/views/CampusWalletManagementView.vue +++ b/web/src/views/CampusWalletManagementView.vue @@ -55,7 +55,11 @@ async function downloadTemplate() { catch (error) { ElMessage.error(apiErrorMessage(error)) } } async function exportWallets() { - try { await downloadApiFile('/campus-registrations/wallets/export.xlsx', '学生余额.xlsx') } + try { + await downloadApiFile('/campus-registrations/wallets/export.xlsx', '学生余额.xlsx', { + params: { keyword: keyword.value || undefined, ...filters.value }, + }) + } catch (error) { ElMessage.error(apiErrorMessage(error)) } } async function importFile(event: Event) { diff --git a/web/src/views/DegreeAwardsView.vue b/web/src/views/DegreeAwardsView.vue index 080c934..1931a90 100644 --- a/web/src/views/DegreeAwardsView.vue +++ b/web/src/views/DegreeAwardsView.vue @@ -18,10 +18,19 @@ const reviewDialog = ref(false) const reviewTarget = ref(null) const keyword = ref('') const conclusionFilter = ref('') +const grade = ref() +const collegeId = ref('') const majorId = ref('') const administrativeClassId = ref('') +const colleges = ref([]) const majors = ref([]) const classes = ref([]) +const grades = computed(() => [...new Set(classes.value.map((item: any) => item.grade))].sort((a, b) => b - a)) +const filteredMajors = computed(() => majors.value.filter((item: any) => !collegeId.value || item.collegeId === collegeId.value)) +const filteredClasses = computed(() => classes.value.filter((item: any) => + (!grade.value || item.grade === grade.value) && + (!collegeId.value || filteredMajors.value.some((major: any) => major.id === item.majorId)) && + (!majorId.value || item.majorId === majorId.value))) const resultPage = ref(1) const resultCursors = ref([]) const nextResultCursor = ref() @@ -58,10 +67,10 @@ async function load() { myResult.value = (await http.get('/degree-awards/my-result')).data return } - const [batchResponse, majorResponse, classResponse] = await Promise.all([ - http.get('/degree-awards/batches'), http.get('/base-data/majors'), http.get('/base-data/classes'), + const [batchResponse, collegeResponse, majorResponse, classResponse] = await Promise.all([ + http.get('/degree-awards/batches'), http.get('/base-data/colleges'), http.get('/base-data/majors'), http.get('/base-data/classes'), ]) - batches.value = batchResponse.data; majors.value = majorResponse.data; classes.value = classResponse.data + batches.value = batchResponse.data; colleges.value = collegeResponse.data; majors.value = majorResponse.data; classes.value = classResponse.data const batch = batches.value.find((x) => x.id === selected.value?.id) ?? batches.value[0] if (batch) await selectBatch(batch.id) else selected.value = null @@ -88,6 +97,8 @@ async function loadBatch(id = selected.value?.id) { pageSize: resultPageSize, keyword: keyword.value.trim() || undefined, conclusion: conclusionFilter.value || undefined, + grade: grade.value || undefined, + collegeId: collegeId.value || undefined, majorId: majorId.value || undefined, administrativeClassId: administrativeClassId.value || undefined, }, @@ -103,7 +114,9 @@ async function loadBatch(id = selected.value?.id) { if (requestId === resultRequestId.value) loading.value = false } } -async function exportRows() { try { await downloadApiFile(`/degree-awards/batches/${selected.value.id}/export.xlsx`, '学位授予审核.xlsx', { params: { keyword: keyword.value.trim() || undefined, conclusion: conclusionFilter.value || undefined, majorId: majorId.value || undefined, administrativeClassId: administrativeClassId.value || undefined } }); ElMessage.success('已导出当前筛选范围的全部记录。') } catch (error) { ElMessage.error(apiErrorMessage(error)) } } +async function exportRows() { try { await downloadApiFile(`/degree-awards/batches/${selected.value.id}/export.xlsx`, '学位授予审核.xlsx', { params: { keyword: keyword.value.trim() || undefined, conclusion: conclusionFilter.value || undefined, grade: grade.value || undefined, collegeId: collegeId.value || undefined, majorId: majorId.value || undefined, administrativeClassId: administrativeClassId.value || undefined } }); ElMessage.success('已导出当前筛选范围的全部记录。') } catch (error) { ElMessage.error(apiErrorMessage(error)) } } +function onCollegeChange() { majorId.value = ''; administrativeClassId.value = '' } +function onMajorChange() { administrativeClassId.value = '' } async function removeBatch() { try { await ElMessageBox.confirm(`删除草稿批次“${selected.value.name}”及其审核结果?此操作不可恢复。`, '删除授予批次', { type: 'warning', confirmButtonText: '删除' }); await http.delete(`/degree-awards/batches/${selected.value.id}`); ElMessage.success('草稿批次已删除。'); await load() } catch (error: any) { if (error !== 'cancel' && error !== 'close') ElMessage.error(apiErrorMessage(error)) } } async function nextResultPage() { if (nextResultCursor.value && !loading.value) { resultCursors.value.push(nextResultCursor.value); resultPage.value++; await loadBatch() } } @@ -164,7 +177,7 @@ async function publish() { } } -watch([keyword, conclusionFilter, majorId, administrativeClassId], () => { +watch([keyword, conclusionFilter, grade, collegeId, majorId, administrativeClassId], () => { resultPage.value = 1 resultCursors.value = [] nextResultCursor.value = undefined @@ -227,8 +240,10 @@ onMounted(load)
- - + + + + 共 {{ resultTotal }} 条
diff --git a/web/src/views/DormitoryHygieneView.vue b/web/src/views/DormitoryHygieneView.vue index faff6ca..e66623c 100644 --- a/web/src/views/DormitoryHygieneView.vue +++ b/web/src/views/DormitoryHygieneView.vue @@ -7,6 +7,7 @@ import { CanvasRenderer } from 'echarts/renderers' import { Download, HomeFilled, Plus, Search, Upload } from '@element-plus/icons-vue' import { ElMessage, ElMessageBox } from 'element-plus' import http, { apiErrorMessage } from '../api/http' +import { fetchAllPagedItems } from '../api/pagination' import { downloadApiFile, importExcel } from '../api/excel' import { useAuthStore } from '../stores/auth' import VacantBedPicker from '../components/VacantBedPicker.vue' @@ -23,6 +24,7 @@ const canManage=computed(()=>roles.value.some(x=>['SuperAdmin','AcademicAdmin',' const canCounselor=computed(()=>roles.value.some(x=>['SuperAdmin','AcademicAdmin','CollegeAdmin','Counselor'].includes(x))) const loading=ref(false),saving=ref(false),activeTab=ref(props.section??'overview') const overview=ref(),buildings=ref([]),applications=ref([]),myApplications=ref([]) +const applicationPage=ref(1),applicationPageSize=ref(20),applicationTotal=ref(0) const mine=reactive<{room?:any;scores:any[]}>({scores:[]}) const pieEl=ref(),barEl=ref();let charts:echarts.ECharts[]=[] const buildingDialog=ref(false),roomDialog=ref(false),bedsDialog=ref(false),transferDialog=ref(false),checkInDateDialog=ref(false),applicationDialog=ref(false),finalDialog=ref(false) @@ -35,7 +37,9 @@ const applicationForm=reactive({type:1,reason:''}),finalForm=reactive({approved: const allocationTable=ref(),students=ref([]),selectedStudents=ref([]),studentKeyword=ref(''),studentGradeFilter=ref([]),studentMajorFilter=ref([]),studentClassFilter=ref([]),buildingFilter=ref([]),assignments=ref([]),allocationMode=ref(2),allocationJobId=ref(),allocationJobStatus=ref(''),studentTotal=ref(0),studentPage=ref(1),studentPageSize=ref(50) const studentFilterOptions=reactive<{grades:number[];majors:any[];classes:any[]}>({grades:[],majors:[],classes:[]}) const batches=ref([]),selectedBatch=ref(),scores=ref([]),scoreSummary=ref(),batchDialog=ref(false),scoreDialog=ref(false) +const batchPage=ref(1),batchPageSize=ref(20),batchTotal=ref(0),scorePage=ref(1),scorePageSize=ref(50),scoreTotal=ref(0) const terms=ref([]),calculationTermId=ref(''),calculationBatchIds=ref([]),calculationOptions=ref([]),calculations=ref([]),selectedCalculation=ref(),calculationResults=ref([]),calculationResultPage=ref(1),calculationResultTotal=ref(0) +const calculationPage=ref(1),calculationPageSize=ref(20),calculationTotal=ref(0) const studentTermId=ref(''),studentBatchIds=ref([]) const hygieneBuilding=ref(),hygieneFloor=ref() const batchForm=reactive({name:'',inspectionDate:new Date().toISOString().slice(0,10),inspector:''}) @@ -62,7 +66,7 @@ async function loadTerms(){terms.value=(await http.get('/base-data/terms')).data function resetStudentCalculator(){studentBatchIds.value=studentTermScores.value.map(x=>x.dormitoryHygieneBatchId)} async function loadOverview(){overview.value=(await http.get('/dormitory-services/overview')).data;if(activeTab.value==='overview')await nextTick(renderCharts)} async function loadBuildings(){buildings.value=(await http.get('/dormitory-services/buildings')).data??[]} -async function loadApps(){applications.value=(await http.get('/dormitory-services/applications')).data??[]} +async function loadApps(page=applicationPage.value){applicationPage.value=page;const{data}=await http.get('/dormitory-services/applications',{params:{page,pageSize:applicationPageSize.value}});applications.value=data.items??[];applicationTotal.value=data.total??0} async function refreshHousing(){await Promise.all([loadBuildings(),loadOverview()])} function renderCharts(){charts.forEach(x=>x.dispose());charts=[];if(!overview.value||!pieEl.value||!barEl.value)return;const p=echarts.init(pieEl.value),b=echarts.init(barEl.value);p.setOption({tooltip:{trigger:'item'},legend:{bottom:0},series:[{type:'pie',radius:['50%','75%'],data:[{name:'已入住',value:overview.value.occupiedCount},{name:'空置',value:overview.value.vacantCount}]}]});b.setOption({tooltip:{trigger:'axis'},legend:{bottom:0},grid:{left:40,right:10,bottom:45},xAxis:{type:'category',data:overview.value.buildings.map((x:any)=>x.name)},yAxis:{type:'value'},series:[{name:'已入住',type:'bar',stack:'床位',data:overview.value.buildings.map((x:any)=>x.occupiedCount)},{name:'空置',type:'bar',stack:'床位',data:overview.value.buildings.map((x:any)=>x.bedCount-x.occupiedCount)}]});charts=[p,b]} function openBuilding(x?:Building){editingBuilding.value=x?.id;Object.assign(buildingForm,x?{code:x.code,name:x.name,floorCount:x.floorCount,genderPolicy:enumCode(x.genderPolicy,{Any:0,Male:1,Female:2}),isEnabled:x.isEnabled,notes:x.notes??''}:{code:'',name:'',floorCount:6,genderPolicy:0,isEnabled:true,notes:''});buildingDialog.value=true} @@ -100,21 +104,21 @@ async function cancelApp(id:string){await safe(async()=>{await http.post(`/dormi async function counselorReview(x:any,approved:boolean){try{const{value}=await ElMessageBox.prompt('审核意见','辅导员审核',{inputType:'textarea'});await http.post(`/dormitory-services/applications/${x.id}/counselor-review`,{approved,comment:value});await loadApps()}catch(e){if(e!=='cancel'&&e!=='close')ElMessage.error(apiErrorMessage(e))}} function openFinal(x:any){finalApplication.value=x;Object.assign(finalForm,{approved:true,targetBedId:'',comment:''});finalDialog.value=true} async function finalReview(){if(finalForm.approved&&appType(finalApplication.value.type)===1&&!finalForm.targetBedId)return ElMessage.warning('请选择调入床位');await safe(async()=>{await http.post(`/dormitory-services/applications/${finalApplication.value.id}/final-review`,{...finalForm,targetBedId:finalForm.targetBedId||null});finalDialog.value=false;await Promise.all([loadApps(),refreshHousing()]);ElMessage.success('终审已完成')})} -async function loadBatches(){const{data}=await http.get('/dormitory-hygiene/batches',{params:{page:1,pageSize:100}});batches.value=data.items??[]} +async function loadBatches(page=batchPage.value){batchPage.value=page;const{data}=await http.get('/dormitory-hygiene/batches',{params:{page,pageSize:batchPageSize.value}});batches.value=data.items??[];batchTotal.value=data.total??0} async function loadCalculationOptions(){if(!calculationTermId.value)return;const{data}=await http.get(`/dormitory-hygiene/calculations/options/${calculationTermId.value}`);calculationOptions.value=data.batches??[];calculationBatchIds.value=calculationOptions.value.map(x=>x.id)} -async function loadCalculations(){const{data}=await http.get('/dormitory-hygiene/calculations',{params:{page:1,pageSize:50}});calculations.value=data.items??[]} +async function loadCalculations(page=calculationPage.value){calculationPage.value=page;const{data}=await http.get('/dormitory-hygiene/calculations',{params:{page,pageSize:calculationPageSize.value}});calculations.value=data.items??[];calculationTotal.value=data.total??0} const calculationStatus=(v:any)=>({1:'排队中',2:'计算中',3:'已完成',4:'失败'} as Record)[enumCode(v,{Queued:1,Running:2,Succeeded:3,Failed:4})]??'未知' async function openCalculation(x:any,pageOrColumn:any=1){const page=typeof pageOrColumn==='number'?pageOrColumn:1;calculationResultPage.value=page;const{data}=await http.get(`/dormitory-hygiene/calculations/${x.id}`,{params:{page,pageSize:50}});selectedCalculation.value=data.calculation;calculationResults.value=data.results.items??[];calculationResultTotal.value=data.results.total??0} async function startCalculation(){if(!calculationTermId.value)return ElMessage.warning('请选择学期');if(!calculationBatchIds.value.length)return ElMessage.warning('请至少选择一个检查批次');saving.value=true;await safe(async()=>{const{data}=await http.post('/dormitory-hygiene/calculations',{academicTermId:calculationTermId.value,batchIds:calculationBatchIds.value});ElMessage.success('汇总任务已进入后台队列');let completed=false;for(let attempt=0;attempt<300;attempt++){await wait(1000);const detail=(await http.get(`/dormitory-hygiene/calculations/${data.id}`,{params:{page:1,pageSize:50}})).data;selectedCalculation.value=detail.calculation;calculationResults.value=detail.results.items??[];calculationResultTotal.value=detail.results.total??0;const status=enumCode(detail.calculation.status,{Queued:1,Running:2,Succeeded:3,Failed:4});if(status===3){completed=true;ElMessage.success('本学期宿舍卫生平均分已入库');break}if(status===4)throw new Error(detail.calculation.errorMessage||'汇总计算失败')}if(!completed)throw new Error('后台计算仍在进行,可稍后从计算记录中查看结果');await loadCalculations()});saving.value=false} -async function openBatch(x:any){selectedBatch.value=x;const{data}=await http.get(`/dormitory-hygiene/batches/${x.id}/scores`,{params:{buildingId:hygieneBuilding.value,floor:hygieneFloor.value,page:1,pageSize:200}});scores.value=data.scores.items;scoreSummary.value=data.summary} +async function openBatch(x:any,page=1){selectedBatch.value=x;scorePage.value=page;const{data}=await http.get(`/dormitory-hygiene/batches/${x.id}/scores`,{params:{buildingId:hygieneBuilding.value,floor:hygieneFloor.value,page,pageSize:scorePageSize.value}});scores.value=data.scores.items;scoreTotal.value=data.scores.total??0;scoreSummary.value=data.summary} function openBatchForm(x?:any){editingBatch.value=x;Object.assign(batchForm,x?{name:x.name,inspectionDate:x.inspectionDate,inspector:x.inspector??''}:{name:'',inspectionDate:localDateValue(),inspector:''});batchDialog.value=true} async function saveBatch(){if(!batchForm.name.trim())return ElMessage.warning('请填写批次名称');await safe(async()=>{editingBatch.value?await http.put(`/dormitory-hygiene/batches/${editingBatch.value.id}`,batchForm):await http.post('/dormitory-hygiene/batches',batchForm);batchDialog.value=false;ElMessage.success(editingBatch.value?'批次已修改':'批次已创建');await loadBatches();if(editingBatch.value&&selectedBatch.value?.id===editingBatch.value.id){const updated=batches.value.find(x=>x.id===editingBatch.value.id);if(updated)await openBatch(updated)}})} async function deleteBatch(x:any){if(enumCode(x.status,{Draft:1,Published:2})===2)return ElMessage.warning('已发布批次不能删除');try{await ElMessageBox.confirm(`将删除“${x.name}”及其中 ${x.scoreCount??0} 条成绩,且无法恢复。确认继续?`,'删除检查批次',{type:'warning',confirmButtonText:'确认删除'});await http.delete(`/dormitory-hygiene/batches/${x.id}`);if(selectedBatch.value?.id===x.id){selectedBatch.value=undefined;scores.value=[];scoreSummary.value=undefined}await loadBatches();ElMessage.success('检查批次已删除')}catch(e){if(e!=='cancel'&&e!=='close')ElMessage.error(apiErrorMessage(e))}} -async function newScore(x?:any){scoreRooms.value=(await http.get('/dormitory-hygiene/rooms',{params:{page:1,pageSize:200}})).data.items;Object.assign(scoreForm,x?{dormitoryRoomId:x.dormitoryRoomId,floorScore:x.floorScore,beddingScore:x.beddingScore,belongingsScore:x.belongingsScore,facilitiesScore:x.facilitiesScore,safetyScore:x.safetyScore,isViolation:Boolean(x.isViolation),issues:x.issues??'',notes:x.notes??''}:{dormitoryRoomId:'',floorScore:20,beddingScore:20,belongingsScore:20,facilitiesScore:20,safetyScore:20,isViolation:false,issues:'',notes:''});scoreDialog.value=true} +async function newScore(x?:any){scoreRooms.value=await fetchAllPagedItems('/dormitory-hygiene/rooms');Object.assign(scoreForm,x?{dormitoryRoomId:x.dormitoryRoomId,floorScore:x.floorScore,beddingScore:x.beddingScore,belongingsScore:x.belongingsScore,facilitiesScore:x.facilitiesScore,safetyScore:x.safetyScore,isViolation:Boolean(x.isViolation),issues:x.issues??'',notes:x.notes??''}:{dormitoryRoomId:'',floorScore:20,beddingScore:20,belongingsScore:20,facilitiesScore:20,safetyScore:20,isViolation:false,issues:'',notes:''});scoreDialog.value=true} async function saveScore(){if(!selectedBatch.value||!scoreForm.dormitoryRoomId)return;await safe(async()=>{await http.put(`/dormitory-hygiene/batches/${selectedBatch.value.id}/scores`,{scores:[scoreForm]});scoreDialog.value=false;await openBatch(selectedBatch.value);ElMessage.success('成绩已保存')})} async function publish(){if(!selectedBatch.value)return;try{await ElMessageBox.confirm('确认发布本批次成绩?','发布成绩',{type:'warning'});await http.post(`/dormitory-hygiene/batches/${selectedBatch.value.id}/publish`);await Promise.all([openBatch(selectedBatch.value),loadBatches()]);ElMessage.success('成绩已发布')}catch(e){if(e!=='cancel'&&e!=='close')ElMessage.error(apiErrorMessage(e))}} async function downloadScoreTemplate(){if(selectedBatch.value)await safe(async()=>downloadApiFile(`/dormitory-hygiene/batches/${selectedBatch.value.id}/template`,`${selectedBatch.value.name}-卫生成绩导入模板.xlsx`))} -async function exportScores(){if(selectedBatch.value)await safe(async()=>downloadApiFile(`/dormitory-hygiene/batches/${selectedBatch.value.id}/export.xlsx`,`${selectedBatch.value.name}-卫生成绩.xlsx`))} +async function exportScores(){if(selectedBatch.value)await safe(async()=>downloadApiFile(`/dormitory-hygiene/batches/${selectedBatch.value.id}/export.xlsx`,`${selectedBatch.value.name}-卫生成绩.xlsx`,{params:{buildingId:hygieneBuilding.value,floor:hygieneFloor.value}}))} async function importScores(event:Event){const input=event.target as HTMLInputElement,file=input.files?.[0];input.value='';if(!file||!selectedBatch.value)return;saving.value=true;await safe(async()=>{const{data}=await importExcel(`/dormitory-hygiene/batches/${selectedBatch.value.id}/import`,file);ElMessage.success(`已合并导入 ${data.imported} 间宿舍成绩`);await Promise.all([openBatch(selectedBatch.value),loadBatches()])});saving.value=false} watch(activeTab,async x=>{if(x==='overview'){await nextTick();renderCharts()}if(x==='allocation')await Promise.all([students.value.length?Promise.resolve():loadStudents(),studentFilterOptions.classes.length?Promise.resolve():loadStudentFilterOptions()])}) watch(()=>props.section,x=>{if(x)activeTab.value=x}) @@ -130,8 +134,8 @@ onMounted(()=>{window.addEventListener('resize',renderCharts);load()});onBeforeU

楼栋—房间—床位

有学生入住的床位必须先调宿或退宿后才能删除;Excel 导入按编码合并,不删除文件外数据。

导入模板批量导入导出全部新增楼栋
新增房间编辑楼栋
-

调宿与退宿审批

辅导员核实,宿管终审时实际变更或释放床位。

- +

调宿与退宿审批

辅导员核实,宿管终审时实际变更或释放床位。

+

有学生入住的床位不能删除。

diff --git a/web/src/views/ExamsView.vue b/web/src/views/ExamsView.vue index 69d419c..ab86df3 100644 --- a/web/src/views/ExamsView.vue +++ b/web/src/views/ExamsView.vue @@ -2,6 +2,7 @@ import { computed, onBeforeUnmount, onMounted, reactive, ref } from 'vue' import { Delete, Download, Plus, Promotion, Refresh, UserFilled, Setting } from '@element-plus/icons-vue' import http, { apiErrorMessage } from '../api/http' +import { fetchAllPagedItems } from '../api/pagination' import { downloadApiFile } from '../api/excel' import { useAuthStore } from '../stores/auth' import { academicTermLabel, academicTermOptionClass, defaultAcademicTermId } from '../utils/academicTerms' @@ -569,15 +570,15 @@ function parseBuildingIds(raw: string | undefined | null): string[] { onMounted(async () => { try { if (isManager.value) { - const [termRes, roomRes, teacherRes, buildingRes] = await Promise.all([ + const [termRes, roomRes, teacherItems, buildingRes] = await Promise.all([ http.get('/base-data/terms'), http.get('/base-data/classrooms'), - http.get('/personnel/teachers', { params: { page: 1, pageSize: 200, teacherStatus: 'Active' } }), + fetchAllPagedItems('/personnel/teachers', { teacherStatus: 'Active' }), http.get('/base-data/buildings'), ]) terms.value = termRes.data rooms.value = roomRes.data - teachers.value = teacherRes.data.items + teachers.value = teacherItems buildings.value = buildingRes.data } await load() diff --git a/web/src/views/GraduationAuditsView.vue b/web/src/views/GraduationAuditsView.vue index e7015f3..7507bd2 100644 --- a/web/src/views/GraduationAuditsView.vue +++ b/web/src/views/GraduationAuditsView.vue @@ -18,10 +18,19 @@ const decisionDialog = ref(false) const decisionTarget = ref(null) const keyword = ref('') const conclusionFilter = ref('') +const grade = ref() +const collegeId = ref('') const majorId = ref('') const administrativeClassId = ref('') +const colleges = ref([]) const majors = ref([]) const classes = ref([]) +const grades = computed(() => [...new Set(classes.value.map((item: any) => item.grade))].sort((a, b) => b - a)) +const filteredMajors = computed(() => majors.value.filter((item: any) => !collegeId.value || item.collegeId === collegeId.value)) +const filteredClasses = computed(() => classes.value.filter((item: any) => + (!grade.value || item.grade === grade.value) && + (!collegeId.value || filteredMajors.value.some((major: any) => major.id === item.majorId)) && + (!majorId.value || item.majorId === majorId.value))) const resultPage = ref(1) const resultPageSize = 20 const resultRequestId = ref(0) @@ -56,10 +65,10 @@ async function load() { myResult.value = (await http.get('/graduation-audits/my-result')).data return } - const [batchResponse, majorResponse, classResponse] = await Promise.all([ - http.get('/graduation-audits/batches'), http.get('/base-data/majors'), http.get('/base-data/classes'), + const [batchResponse, collegeResponse, majorResponse, classResponse] = await Promise.all([ + http.get('/graduation-audits/batches'), http.get('/base-data/colleges'), http.get('/base-data/majors'), http.get('/base-data/classes'), ]) - batches.value = batchResponse.data; majors.value = majorResponse.data; classes.value = classResponse.data + batches.value = batchResponse.data; colleges.value = collegeResponse.data; majors.value = majorResponse.data; classes.value = classResponse.data const batch = batches.value.find((x) => x.id === selected.value?.id) ?? batches.value[0] if (batch) await selectBatch(batch.id) else selected.value = null @@ -84,6 +93,8 @@ async function loadBatch(id = selected.value?.id) { pageSize: resultPageSize, keyword: keyword.value.trim() || undefined, conclusion: conclusionFilter.value || undefined, + grade: grade.value || undefined, + collegeId: collegeId.value || undefined, majorId: majorId.value || undefined, administrativeClassId: administrativeClassId.value || undefined, }, @@ -95,7 +106,10 @@ async function loadBatch(id = selected.value?.id) { if (requestId === resultRequestId.value) loading.value = false } } -async function exportRows() { try { await downloadApiFile(`/graduation-audits/batches/${selected.value.id}/export.xlsx`, '毕业资格审核.xlsx', { params: { keyword: keyword.value.trim() || undefined, conclusion: conclusionFilter.value || undefined, majorId: majorId.value || undefined, administrativeClassId: administrativeClassId.value || undefined } }); ElMessage.success('已导出当前筛选范围的全部记录。') } catch (error) { ElMessage.error(apiErrorMessage(error)) } } +async function exportRows() { try { await downloadApiFile(`/graduation-audits/batches/${selected.value.id}/export.xlsx`, '毕业资格审核.xlsx', { params: { keyword: keyword.value.trim() || undefined, conclusion: conclusionFilter.value || undefined, grade: grade.value || undefined, collegeId: collegeId.value || undefined, majorId: majorId.value || undefined, administrativeClassId: administrativeClassId.value || undefined } }); ElMessage.success('已导出当前筛选范围的全部记录。') } catch (error) { ElMessage.error(apiErrorMessage(error)) } } + +function onCollegeChange() { majorId.value = ''; administrativeClassId.value = '' } +function onMajorChange() { administrativeClassId.value = '' } async function removeBatch() { try { await ElMessageBox.confirm(`删除草稿批次“${selected.value.name}”及其审核结果?此操作不可恢复。`, '删除审核批次', { type: 'warning', confirmButtonText: '删除' }); await http.delete(`/graduation-audits/batches/${selected.value.id}`); ElMessage.success('草稿批次已删除。'); await load() } catch (error: any) { if (error !== 'cancel' && error !== 'close') ElMessage.error(apiErrorMessage(error)) } } async function createBatch() { if (!batchForm.name.trim()) return @@ -156,7 +170,7 @@ async function publish() { } } -watch([keyword, conclusionFilter, majorId, administrativeClassId], () => { +watch([keyword, conclusionFilter, grade, collegeId, majorId, administrativeClassId], () => { resultPage.value = 1 if (filterTimer) clearTimeout(filterTimer) filterTimer = setTimeout(() => loadBatch(), 300) @@ -247,8 +261,10 @@ onMounted(load) - - + + + + 共 {{ resultTotal }} 条
diff --git a/web/src/views/MakeupExamsView.vue b/web/src/views/MakeupExamsView.vue index 0fb8a05..0509ef0 100644 --- a/web/src/views/MakeupExamsView.vue +++ b/web/src/views/MakeupExamsView.vue @@ -2,6 +2,7 @@ import { computed, onBeforeUnmount, onMounted, reactive, ref } from 'vue' import { Plus, Promotion, Refresh, UserFilled, Setting, Search, MagicStick } from '@element-plus/icons-vue' import http, { apiErrorMessage } from '../api/http' +import { fetchAllPagedItems } from '../api/pagination' import { useAuthStore } from '../stores/auth' import { academicTermLabel, academicTermOptionClass, defaultAcademicTermId } from '../utils/academicTerms' @@ -500,15 +501,15 @@ function stopPolling() { onMounted(async () => { try { if (isManager.value) { - const [termRes, roomRes, teacherRes, buildingRes] = await Promise.all([ + const [termRes, roomRes, teacherItems, buildingRes] = await Promise.all([ http.get('/base-data/terms'), http.get('/base-data/classrooms'), - http.get('/personnel/teachers', { params: { page: 1, pageSize: 200, teacherStatus: 'Active' } }), + fetchAllPagedItems('/personnel/teachers', { teacherStatus: 'Active' }), http.get('/base-data/buildings'), ]) terms.value = termRes.data rooms.value = roomRes.data - teachers.value = teacherRes.data.items + teachers.value = teacherItems buildings.value = buildingRes.data } await load() diff --git a/web/src/views/OtherExamsView.vue b/web/src/views/OtherExamsView.vue index 70d9ef3..2e14b23 100644 --- a/web/src/views/OtherExamsView.vue +++ b/web/src/views/OtherExamsView.vue @@ -29,6 +29,13 @@ const resultCursors = ref([]) const nextResultCursor = ref() const resultHasMore = ref(false) const resultTotal = ref(0) +const resultKeyword = ref('') +const resultGrade = ref() +const resultCollegeId = ref('') +const resultMajorId = ref('') +const resultClassId = ref('') +const resultFilterOptions = ref({ grades: [], colleges: [], majors: [], classes: [] }) +const resultFilterBatchId = ref('') const mine = reactive({ best: [] as any[], history: [] as any[] }) const dialog = ref(false) const publishDialog = ref(false) @@ -38,6 +45,10 @@ const selectedMetricKind = computed(() => Number(selected.value?.metricKind ?? 0 const isScoreMetric = computed(() => selectedMetricKind.value === 3) const isLevelMetric = computed(() => selectedMetricKind.value === 2) const isPassMetric = computed(() => selectedMetricKind.value === 1) +const resultMajors = computed(() => resultFilterOptions.value.majors.filter((item: any) => !resultCollegeId.value || item.collegeId === resultCollegeId.value)) +const resultClasses = computed(() => resultFilterOptions.value.classes.filter((item: any) => + (!resultGrade.value || item.grade === resultGrade.value) && + (!resultMajorId.value ? !resultCollegeId.value || resultMajors.value.some((major: any) => major.id === item.majorId) : item.majorId === resultMajorId.value))) function metricKindValue(kind: unknown) { if (typeof kind === 'string') return ({ PassFail: 1, Level: 2, Score: 3 } as Record)[kind] ?? Number(kind) return Number(kind) @@ -97,7 +108,12 @@ async function openBatch(row: any, resetPage = true) { nextResultCursor.value = undefined } try { - const data = (await http.get(`/other-exams/batches/${row.id}`, { params: { cursor: resultCursors.value.at(-1), pageSize: resultPageSize } })).data + if (resultFilterBatchId.value !== row.id) { + resultFilterOptions.value = (await http.get(`/other-exams/batches/${row.id}/result-filter-options`)).data + resultFilterBatchId.value = row.id + resultKeyword.value = ''; resultGrade.value = undefined; resultCollegeId.value = ''; resultMajorId.value = ''; resultClassId.value = '' + } + const data = (await http.get(`/other-exams/batches/${row.id}`, { params: resultRequestParams(true) })).data const metricKind = metricKindValue(data.batch.metricKind) data.batch.metricKind = [1, 2, 3].includes(metricKind) ? metricKind : 3 selected.value = data.batch @@ -107,6 +123,11 @@ async function openBatch(row: any, resetPage = true) { nextResultCursor.value = data.results.nextCursor } catch (error) { ElMessage.error(apiErrorMessage(error)) } } +function resultRequestParams(includePage: boolean) { return { keyword: resultKeyword.value.trim() || undefined, grade: resultGrade.value, collegeId: resultCollegeId.value || undefined, majorId: resultMajorId.value || undefined, administrativeClassId: resultClassId.value || undefined, cursor: includePage ? resultCursors.value.at(-1) : undefined, pageSize: includePage ? resultPageSize : undefined } } +function onResultCollegeChange() { resultMajorId.value = ''; resultClassId.value = '' } +function onResultMajorChange() { resultClassId.value = '' } +async function searchResults() { if (selected.value) await openBatch(selected.value, true) } +async function exportResults() { if (!selected.value) return; try { await downloadApiFile(`/other-exams/batches/${selected.value.id}/export.xlsx`, `${selected.value.name}-其他考试成绩.xlsx`, { params: resultRequestParams(false) }); ElMessage.success('已导出当前筛选范围的全部成绩') } catch (error) { ElMessage.error(apiErrorMessage(error)) } } async function nextResultPage() { if (!selected.value || !nextResultCursor.value || loading.value) return resultCursors.value.push(nextResultCursor.value); resultPage.value += 1 @@ -178,7 +199,7 @@ onMounted(load)
确认发布“{{ selected?.name }}”成绩?

发布后学生可以查看本批次成绩;如需更正,可以修改后再次发布。

diff --git a/web/src/views/PhysicalFitnessView.vue b/web/src/views/PhysicalFitnessView.vue index a05f2cd..e81d4ae 100644 --- a/web/src/views/PhysicalFitnessView.vue +++ b/web/src/views/PhysicalFitnessView.vue @@ -30,6 +30,12 @@ const records = ref([]) const recordKeyword = ref('') const recordStatus = ref() const recordGrade = ref() +const recordStudentGrade = ref() +const recordCollegeId = ref('') +const recordMajorId = ref('') +const recordClassId = ref('') +const recordFilterOptions = ref({ grades: [], colleges: [], majors: [], classes: [] }) +const recordFilterBatchId = ref('') const attentionOnly = ref(false) const recordPage = ref(1) const recordCursors = ref([]) @@ -61,6 +67,10 @@ const scoreChange = computed(() => normalHistory.value.length < 2 ? undefined : const weakestItems = computed(() => (latestNormal.value?.items ?? []).filter((item: Item) => itemCode(item.itemCode) >= 3 && item.score != null).sort((a: Item, b: Item) => Number(a.score) - Number(b.score)).slice(0, 2)) const gradeDistribution = computed(() => [4, 3, 2, 1].map(grade => ({ grade, label: gradeLabels[grade], count: summary.value?.gradeDistribution.find(item => gradeCode(item.grade) === grade)?.count ?? 0 }))) const specialCount = computed(() => (summary.value?.statusDistribution ?? []).filter(item => statusCode(item.status) !== 1).reduce((sum, item) => sum + item.count, 0)) +const recordMajors = computed(() => recordFilterOptions.value.majors.filter((item: any) => !recordCollegeId.value || item.collegeId === recordCollegeId.value)) +const recordClasses = computed(() => recordFilterOptions.value.classes.filter((item: any) => + (!recordStudentGrade.value || item.grade === recordStudentGrade.value) && + (!recordMajorId.value ? !recordCollegeId.value || recordMajors.value.some((major: any) => major.id === item.majorId) : item.majorId === recordMajorId.value))) function enumCode(value: EnumValue, map: Record) { if (typeof value === 'number') return Number.isFinite(value) ? value : 0 @@ -104,11 +114,20 @@ async function openBatch(batch: any, reset = true) { if (reset) { recordPage.value = 1; recordCursors.value = [] } loading.value = true try { - const { data } = await http.get(`/physical-fitness/batches/${batch.id}/records`, { params: { keyword: recordKeyword.value.trim() || undefined, status: recordStatus.value, grade: recordGrade.value, attentionOnly: attentionOnly.value || undefined, cursor: recordCursors.value.at(-1), pageSize: 30 } }) + if (recordFilterBatchId.value !== batch.id) { + recordFilterOptions.value = (await http.get(`/physical-fitness/batches/${batch.id}/record-filter-options`)).data + recordFilterBatchId.value = batch.id + recordStudentGrade.value = undefined; recordCollegeId.value = ''; recordMajorId.value = ''; recordClassId.value = '' + } + const { data } = await http.get(`/physical-fitness/batches/${batch.id}/records`, { params: recordRequestParams(true) }) selected.value = { ...selected.value, ...data.batch }; summary.value = data.summary; records.value = data.page.items; nextRecordCursor.value = data.page.nextCursor; recordHasMore.value = data.page.hasMore } catch (error) { ElMessage.error(apiErrorMessage(error)) } finally { loading.value = false } } -function resetRecordFilters() { recordKeyword.value = ''; recordStatus.value = undefined; recordGrade.value = undefined; attentionOnly.value = false; if (selected.value) void openBatch(selected.value) } +function recordRequestParams(includePage: boolean) { return { keyword: recordKeyword.value.trim() || undefined, status: recordStatus.value, grade: recordGrade.value, studentGrade: recordStudentGrade.value, collegeId: recordCollegeId.value || undefined, majorId: recordMajorId.value || undefined, administrativeClassId: recordClassId.value || undefined, attentionOnly: attentionOnly.value || undefined, cursor: includePage ? recordCursors.value.at(-1) : undefined, pageSize: includePage ? 30 : undefined } } +function onRecordCollegeChange() { recordMajorId.value = ''; recordClassId.value = '' } +function onRecordMajorChange() { recordClassId.value = '' } +function resetRecordFilters() { recordKeyword.value = ''; recordStatus.value = undefined; recordGrade.value = undefined; recordStudentGrade.value = undefined; recordCollegeId.value = ''; recordMajorId.value = ''; recordClassId.value = ''; attentionOnly.value = false; if (selected.value) void openBatch(selected.value) } +async function exportRecords() { if (!selected.value) return; try { await downloadApiFile(`/physical-fitness/batches/${selected.value.id}/export.xlsx`, `${selected.value.name}-体测成绩.xlsx`, { params: recordRequestParams(false) }); ElMessage.success('已导出当前筛选范围的全部体测成绩') } catch (error) { ElMessage.error(apiErrorMessage(error)) } } async function nextBatch() { if (!nextBatchCursor.value) return; batchCursors.value.push(nextBatchCursor.value); batchPage.value++; await load() } async function previousBatch() { if (!batchCursors.value.length) return; batchCursors.value.pop(); batchPage.value--; await load() } async function nextRecords() { if (!nextRecordCursor.value) return; recordCursors.value.push(nextRecordCursor.value); recordPage.value++; await openBatch(selected.value, false) } @@ -157,7 +176,7 @@ onMounted(() => load())
{{ selected.academicYear }} · {{ formatDate(selected.testDate) }}

{{ selected.name }}

{{ selected.standardVersion }}

下载模板新增记录{{ batchCode(selected.status) === 2 ? '重新发布' : '发布结果' }}
可见记录{{ summary?.totalCount ?? 0 }}当前数据范围
平均成绩{{ scoreText(summary?.averageScore) }}{{ summary?.scoredCount ?? 0 }} 人有效计分
及格率{{ percentText(summary?.passRate) }}{{ summary?.passCount ?? 0 }} 人及格
需关注{{ specialCount + (summary?.gradeDistribution.find(item => gradeCode(item.grade) === 1)?.count ?? 0) }}不及格或特殊状态

成绩等级分布

仅统计正常且已完成计分的记录

最高 {{ scoreText(summary?.highestScore) }}
{{ item.label }}
{{ item.count }} 人{{ gradePercent(item.count) }}%

数据质量

发布前建议优先完成异常记录复核。

{{ statusLabels[code] }}
{{ summary?.statusDistribution.find(item => statusCode(item.status) === code)?.count ?? 0 }}
-

学生成绩明细

筛选在服务端执行,统计卡片始终展示整个批次。

当前页 {{ records.length }} 条
仅看需关注筛选重置
上一页第 {{ recordPage }} 页下一页
+

学生成绩明细

筛选在服务端执行,统计卡片始终展示整个批次。

当前页 {{ records.length }} 条
仅看需关注筛选重置导出当前筛选
上一页第 {{ recordPage }} 页下一页
diff --git a/web/src/views/WarningsView.vue b/web/src/views/WarningsView.vue index a093a6b..effc555 100644 --- a/web/src/views/WarningsView.vue +++ b/web/src/views/WarningsView.vue @@ -1,7 +1,8 @@