This commit is contained in:
2026-07-24 13:11:09 +08:00 Unverified
parent 6c3021ea8d
commit 30d793773c
23 changed files with 3479 additions and 79 deletions
@@ -0,0 +1,215 @@
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using Jiaowu.Api.Contracts;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Jiaowu.Api.Controllers;
[ApiController]
[Authorize]
[Route("api/courses")]
public sealed class CoursesController(AppDbContext db) : ControllerBase
{
private const string WriteRoles =
SystemRoles.SuperAdmin + "," +
SystemRoles.AcademicAdmin + "," +
SystemRoles.CollegeAdmin;
[HttpGet]
public async Task<ActionResult<PagedResult<object>>> Get(
int page = 1,
int pageSize = 20,
string? keyword = null,
Guid? collegeId = null,
CourseNature? nature = null,
bool? isEnabled = null,
CancellationToken cancellationToken = default)
{
page = Math.Max(1, page);
pageSize = Math.Clamp(pageSize, 10, 100);
var source = db.Courses.AsNoTracking().AsQueryable();
var scopedCollegeId = GetScopedCollegeId();
if (scopedCollegeId.HasValue)
source = source.Where(x => x.CollegeId == scopedCollegeId.Value);
if (collegeId.HasValue)
source = source.Where(x => x.CollegeId == collegeId.Value);
if (nature.HasValue)
source = source.Where(x => x.Nature == nature.Value);
if (isEnabled.HasValue)
source = source.Where(x => x.IsEnabled == isEnabled.Value);
if (!string.IsNullOrWhiteSpace(keyword))
{
keyword = keyword.Trim();
source = source.Where(x =>
x.Code.Contains(keyword) ||
x.Name.Contains(keyword) ||
(x.EnglishName != null && x.EnglishName.Contains(keyword)));
}
var total = await source.CountAsync(cancellationToken);
var items = await source
.OrderBy(x => x.SortOrder)
.ThenBy(x => x.Code)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.Select(x => new
{
x.Id,
x.Code,
x.Name,
x.EnglishName,
x.CollegeId,
CollegeName = x.College!.Name,
x.Credits,
x.TotalHours,
x.LectureHours,
x.PracticeHours,
x.Nature,
x.AssessmentMethod,
x.Description,
x.IsEnabled,
x.SortOrder,
x.CreatedAt
})
.ToListAsync(cancellationToken);
return Ok(new PagedResult<object>(items, total, page, pageSize));
}
[HttpPost]
[Authorize(Roles = WriteRoles)]
public async Task<ActionResult> Create(
CourseRequest request,
CancellationToken cancellationToken)
{
var validation = await ValidateAsync(request, cancellationToken);
if (validation is not null) return validation;
var entity = new Course
{
Code = request.Code.Trim(),
Name = request.Name.Trim(),
EnglishName = Normalize(request.EnglishName),
CollegeId = request.CollegeId,
Credits = request.Credits,
TotalHours = request.TotalHours,
LectureHours = request.LectureHours,
PracticeHours = request.PracticeHours,
Nature = request.Nature,
AssessmentMethod = request.AssessmentMethod,
Description = Normalize(request.Description),
IsEnabled = request.IsEnabled,
SortOrder = request.SortOrder
};
db.Courses.Add(entity);
return await SaveAsync(entity.Id, true, cancellationToken);
}
[HttpPut("{id:guid}")]
[Authorize(Roles = WriteRoles)]
public async Task<ActionResult> Update(
Guid id,
CourseRequest request,
CancellationToken cancellationToken)
{
var entity = await db.Courses.FindAsync([id], cancellationToken);
if (entity is null) return NotFound();
if (!CanAccessCollege(entity.CollegeId)) return Forbid();
var validation = await ValidateAsync(request, cancellationToken);
if (validation is not null) return validation;
entity.Code = request.Code.Trim();
entity.Name = request.Name.Trim();
entity.EnglishName = Normalize(request.EnglishName);
entity.CollegeId = request.CollegeId;
entity.Credits = request.Credits;
entity.TotalHours = request.TotalHours;
entity.LectureHours = request.LectureHours;
entity.PracticeHours = request.PracticeHours;
entity.Nature = request.Nature;
entity.AssessmentMethod = request.AssessmentMethod;
entity.Description = Normalize(request.Description);
entity.IsEnabled = request.IsEnabled;
entity.SortOrder = request.SortOrder;
return await SaveAsync(entity.Id, false, cancellationToken);
}
[HttpDelete("{id:guid}")]
[Authorize(Roles = WriteRoles)]
public async Task<ActionResult> Delete(Guid id, CancellationToken cancellationToken)
{
var entity = await db.Courses.FindAsync([id], cancellationToken);
if (entity is null) return NotFound();
if (!CanAccessCollege(entity.CollegeId)) return Forbid();
db.Courses.Remove(entity);
return await SaveAsync(id, false, cancellationToken);
}
private async Task<ActionResult?> ValidateAsync(
CourseRequest request,
CancellationToken cancellationToken)
{
if (!CanAccessCollege(request.CollegeId)) return Forbid();
if (!await db.Colleges.AnyAsync(x => x.Id == request.CollegeId, cancellationToken))
return ValidationProblem("所选学院不存在。");
if (request.LectureHours + request.PracticeHours > request.TotalHours)
return ValidationProblem("讲授学时与实践学时之和不能超过总学时。");
return null;
}
private Guid? GetScopedCollegeId()
{
if (!User.IsInRole(SystemRoles.CollegeAdmin))
return null;
return Guid.TryParse(User.FindFirstValue("college_id"), out var collegeId)
? collegeId
: Guid.Empty;
}
private bool CanAccessCollege(Guid collegeId) =>
!GetScopedCollegeId().HasValue || GetScopedCollegeId() == collegeId;
private async Task<ActionResult> SaveAsync(
Guid id,
bool created,
CancellationToken cancellationToken)
{
try
{
await db.SaveChangesAsync(cancellationToken);
return created ? Created(string.Empty, new { id }) : NoContent();
}
catch (DbUpdateException)
{
return Conflict(new ProblemDetails
{
Title = "无法完成操作",
Detail = "课程编码已存在,或课程已被其他教学业务引用。",
Status = StatusCodes.Status409Conflict
});
}
}
private static string? Normalize(string? value) =>
string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
public sealed record CourseRequest(
[Required, MaxLength(40)] string Code,
[Required, MaxLength(100)] string Name,
[MaxLength(150)] string? EnglishName,
Guid CollegeId,
[Range(typeof(decimal), "0.1", "99")] decimal Credits,
[Range(1, 1000)] int TotalHours,
[Range(0, 1000)] int LectureHours,
[Range(0, 1000)] int PracticeHours,
CourseNature Nature,
AssessmentMethod AssessmentMethod,
[MaxLength(1000)] string? Description,
bool IsEnabled,
int SortOrder);