21 Commits
94 changed files with 38434 additions and 437 deletions
+38 -1
View File
@@ -36,6 +36,24 @@ Cache__AnalyticsExpirationMinutes=3
Cache__AnalyticsLocalExpirationSeconds=30
Cache__MaximumPayloadKilobytes=2048
# OpenTelemetry 默认收集 HTTP、运行时和数据库指标;配置 OTLP 地址后才会外发。
Observability__Enabled=true
Observability__ServiceName=jiaowu-api
Observability__SlowQueryThresholdMilliseconds=500
# 默认不记录完整 SQL,避免日志或追踪系统接触业务数据。
Observability__IncludeSqlText=false
Observability__MaximumSqlTextLength=2000
# OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector.example.edu.cn:4317
# OTEL_EXPORTER_OTLP_HEADERS=Authorization=Bearer%20REPLACE_WITH_TOKEN
# 系统内“运维与审计 → 系统性能”从 Prometheus 只读查询汇总指标。
PerformanceReporting__Enabled=false
# PerformanceReporting__PrometheusBaseUrl=https://prometheus.example.edu.cn/
# PerformanceReporting__BearerToken=REPLACE_WITH_READ_ONLY_TOKEN
# PerformanceReporting__GrafanaBaseUrl=https://grafana.example.edu.cn/
PerformanceReporting__CacheSeconds=30
PerformanceReporting__TimeoutSeconds=10
# 运维控制台备份目录必须位于持久化、仅服务账号可写的位置。
Operations__BackupDirectory=/var/lib/jiaowu/backups
Operations__BackupWarningHours=24
@@ -49,7 +67,26 @@ Operations__MySqlClientPath=mysql
Jwt__Issuer=Jiaowu.Api
Jwt__Audience=Jiaowu.Web
Jwt__Key=REPLACE_WITH_AT_LEAST_32_RANDOM_BYTES
Jwt__ExpireMinutes=60
Jwt__AccessTokenMinutes=10
Jwt__WebIdleMinutes=30
Jwt__AppIdleMinutes=4320
# Keycloak SSO(可选)。Authority 必须指向 realm,例如:
# https://sso.example.edu.cn/realms/mingxu
Sso__Enabled=false
# Sso__DisplayName=学校统一身份认证
# Sso__Authority=https://sso.example.edu.cn/realms/mingxu
# Sso__ClientId=jiaowu-web
# Sso__ClientSecret=REPLACE_WITH_KEYCLOAK_CLIENT_SECRET
# Sso__UserNameClaim=preferred_username
# Sso__RequireHttpsMetadata=true
# 首次 SSO 登录优先绑定同名本地账号;用户名不同时由用户输入现有账号密码完成绑定。
# 不会自动创建账号或授予角色。
# Sso__LinkExistingUsersByUserName=true
# 前后端同域部署时留空;开发或分离部署时填写前端公开根地址。
# Sso__FrontendBaseUrl=https://jiaowu.example.edu.cn
# 必须与 Keycloak 客户端的 Valid redirect URI 完全一致。
# Sso__CallbackUrl=https://jiaowu.example.edu.cn/signin-keycloak
AllowedHosts=jiaowu.example.edu.cn
Cors__Origins__0=https://jiaowu.example.edu.cn
+97 -3
View File
@@ -144,6 +144,50 @@ Kubernetes 或密钥管理系统仍可覆盖文件中的值。
`chmod 600 .env`Windows 应通过 ACL 只允许服务账号和管理员读取。连接串中的证书
路径必须是运行服务器上的实际路径。
### Keycloak 单点登录(可选)
系统支持 Keycloak 的 OpenID Connect 授权码流程。Keycloak 只负责验证身份;账号是否
启用、角色和学院数据范围仍以本系统 Identity 数据为准。首次 SSO 登录会用
`preferred_username`(可通过 `Sso__UserNameClaim` 修改)优先匹配已有登录账号并记录
外部账号绑定。如果 Keycloak 用户名与教务系统账号不同,认证后会进入账户绑定页,用户
需要再输入一次现有教务系统账号和密码;验证成功后建立永久绑定并直接登录。绑定不会
自动创建本地账号、修改人员档案或从 Keycloak 导入高权限角色。同一 Keycloak 身份不能
绑定多个本地账号,同一本地账号也不能绑定多个 Keycloak 身份。原账号密码登录和学生
自助激活入口不受影响。
在 Keycloak 中创建 OpenID Connect 客户端,并至少配置:
- Valid redirect URI`https://jiaowu.example.edu.cn/signin-keycloak`
- Valid post logout redirect URI`https://jiaowu.example.edu.cn/*`(若后续启用 Keycloak 全局退出)
- Standard flow:开启;Implicit flow:关闭;PKCE`S256`
然后在 `.env` 中配置:
```dotenv
Sso__Enabled=true
Sso__DisplayName=学校统一身份认证
Sso__Authority=https://sso.example.edu.cn/realms/mingxu
Sso__ClientId=jiaowu-web
Sso__ClientSecret=REPLACE_WITH_KEYCLOAK_CLIENT_SECRET
Sso__UserNameClaim=preferred_username
Sso__RequireHttpsMetadata=true
Sso__LinkExistingUsersByUserName=true
Sso__FrontendBaseUrl=https://jiaowu.example.edu.cn
Sso__CallbackUrl=https://jiaowu.example.edu.cn/signin-keycloak
```
前后端同域时 `Sso__FrontendBaseUrl` 可以留空。本地 Vite 开发默认回到
`http://localhost:5173`,Keycloak 测试客户端需同时允许
`http://localhost:5255/signin-keycloak``Sso__CallbackUrl` 是应用实际发送给 Keycloak
`redirect_uri`,必须与客户端的 Valid redirect URI 完全一致;建议生产环境始终显式
配置它,避免反向代理导致 scheme 或 host 推导错误。个人账户页的“管理员配置参考”也会
显示当前生效的完整回调地址。多实例部署应配置 Redis,以便任意实例都能兑换两分钟内
有效、使用后即删除的 SSO 登录码及五分钟内有效的绑定意图。
用户登录后可从页面右上角进入“个人账户”,主动绑定或解除 Keycloak 账号。主动绑定先
使用当前 JWT 创建五分钟有效的一次性绑定意图,再跳转 Keycloak;回调只能绑定到发起该
意图的本地账号。解绑需要再次验证本地密码,避免仅凭未锁屏的登录会话解除身份关联。
### Linux systemd 服务
仓库提供 [`deploy/systemd/jiaowu.service`](deploy/systemd/jiaowu.service),适用于
@@ -322,6 +366,55 @@ Redis 只作为可丢弃的查询缓存。连接失败时应用回源数据库
`allkeys-lfu` 淘汰策略,不启用持久化。`compose.app.example.yml` 不创建 Redis
如需连接外部 Redis,在 `.env` 中配置上述连接串即可。
### OpenTelemetry 与慢查询定位
应用已接入 OpenTelemetry 的 ASP.NET Core、HttpClient、.NET Runtime 指标,并通过
`Jiaowu.Api.Database` ActivitySource 和 Meter 记录 EF Core 数据库命令。配置
`OTEL_EXPORTER_OTLP_ENDPOINT` 后才启动 OpenTelemetry SDK 并向 OTLP Collector 外发;
未配置时不会创建无处消费的请求 Span,也不会尝试连接本地 Collector,结构化慢查询日志
仍然有效。
```text
Observability__Enabled=true
Observability__ServiceName=jiaowu-api
Observability__SlowQueryThresholdMilliseconds=500
OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector.example.edu.cn:4317
```
数据库指标包括 `jiaowu.db.command.duration``jiaowu.db.command.slow`
`jiaowu.db.command.failed`。为关键 EF 查询添加 `TagWith("模块.查询名")` 后,日志和
追踪会直接显示该稳定名称;无标签查询只显示操作类型和 SQL 模板哈希。默认
`Observability__IncludeSqlText=false`,不会把 SQL、参数值或连接串发送到日志和追踪
系统。仅在受控诊断窗口内临时启用完整 SQL 模板,并限制 Collector 权限与保留时间。
应用侧阈值用于关联接口、TraceId 和查询名称;生产 MySQL 还应由数据库管理员启用慢查询
日志,并将 `long_query_time` 设为与应用阈值一致。先按查询哈希/标签汇总高频慢查询,再
对脱敏后的 `SELECT` 在测试库或只读副本执行 `EXPLAIN ANALYZE`,根据实际扫描行数和循环
次数决定是否补组合索引或改写投影。`EXPLAIN ANALYZE` 会真实执行语句,不能直接用于生产
写操作。参考 [MySQL 慢查询日志](https://dev.mysql.com/doc/refman/8.0/en/slow-query-log.html)
和 [MySQL 8.4 EXPLAIN](https://dev.mysql.com/doc/refman/8.4/en/explain.html)。
OpenTelemetry Collector 将指标写入 Prometheus 后,超级管理员可直接在“组织与权限 →
运维与审计 → 系统性能”查看请求量、5xx 比例、HTTP/数据库 P95、慢查询趋势,以及最慢
接口和数据库查询排行。报表由 API 使用固定 PromQL 只读查询 Prometheus,浏览器不会
接触 Prometheus 地址或令牌;结果默认缓存 30 秒。原始 Trace 和更长时间范围仍建议在
Grafana 中下钻,配置其地址后页面会显示跳转入口。
```text
PerformanceReporting__Enabled=true
PerformanceReporting__PrometheusBaseUrl=https://prometheus.example.edu.cn/
PerformanceReporting__BearerToken=REPLACE_WITH_READ_ONLY_TOKEN
PerformanceReporting__GrafanaBaseUrl=https://grafana.example.edu.cn/
PerformanceReporting__CacheSeconds=30
PerformanceReporting__TimeoutSeconds=10
```
`PrometheusBaseUrl` 必须指向可访问 `/api/v1/query``/api/v1/query_range`
Prometheus 兼容接口,令牌应仅具有查询权限。未启用、未配置或指标源暂时不可用时,页面
会显示明确的空状态,不会改查业务数据库或拖慢正常请求。若 Collector/Prometheus 对
指标名或 `service_name` 标签做了转换,可通过 `PerformanceReporting` 下对应的
`*MetricName``ServiceNameLabel` 配置项适配,无需改前端。
### 后台任务与 RabbitMQ
自动排课、课表发布和补考自动生成使用数据库 Outbox 保存任务消息。创建业务任务与
@@ -368,9 +461,10 @@ Outbox 租约恢复改为按维护周期执行,避免积压发布时每条消
### 运维与审计控制台
超级管理员可从“组织与权限 → 运维与审计”查询写操作日志、三类失败后台任务、数据库、
缓存与任务通道健康状态,并查看由 5xx、失败/重试任务、健康探针和备份时效汇总出的异常
告警。查询接口和备份操作均在后端强制要求 `SuperAdmin`,不能只依赖前端菜单隐藏。
超级管理员可从“组织与权限 → 运维与审计”查看系统性能,查询写操作日志、三类失败后台
任务、数据库、缓存与任务通道健康状态,并查看由 5xx、失败/重试任务、健康探针和备份
时效汇总出的异常告警。查询接口和备份操作均在后端强制要求 `SuperAdmin`,不能只依赖
前端菜单隐藏。
SQLite 开发环境直接使用在线备份 API。MySQL 环境需要在服务器安装 `mysqldump`
`mysql`(容器镜像已包含对应的 `mariadb-dump``mariadb` 客户端),并配置独立的
+3 -1
View File
@@ -30,7 +30,9 @@ x-jiaowu-environment: &jiaowu-environment
Jwt__Issuer: Jiaowu.Api
Jwt__Audience: Jiaowu.Web
Jwt__Key: "${JWT_KEY:?请在 .env.docker 中设置 JWT_KEY}"
Jwt__ExpireMinutes: "60"
Jwt__AccessTokenMinutes: "10"
Jwt__WebIdleMinutes: "30"
Jwt__AppIdleMinutes: "4320"
AllowedHosts: "${ALLOWED_HOSTS:-localhost}"
Cors__Origins__0: "${CORS_ORIGIN:-http://localhost:8080}"
OfficialDocuments__PublicBaseUrl: "${OFFICIAL_DOCUMENTS_PUBLIC_BASE_URL:-http://localhost:8080}"
+70 -12
View File
@@ -18,7 +18,7 @@ namespace Jiaowu.Api.Controllers;
public sealed class AuthController(
AppDbContext db,
UserManager<ApplicationUser> userManager,
ITokenService tokenService,
IAuthSessionService authSessionService,
IAppCache cache) : ControllerBase
{
[AllowAnonymous]
@@ -135,8 +135,11 @@ public sealed class AuthController(
}
[AllowAnonymous]
[EnableRateLimiting("public-auth")]
[HttpPost("login")]
public async Task<ActionResult<LoginResponse>> Login(LoginRequest request)
public async Task<ActionResult<LoginResponse>> Login(
LoginRequest request,
CancellationToken cancellationToken)
{
var user = await userManager.FindByNameAsync(request.UserName);
if (user is null || !user.IsEnabled)
@@ -166,15 +169,47 @@ public sealed class AuthController(
await userManager.UpdateAsync(user);
var roles = await userManager.GetRolesAsync(user);
return new LoginResponse(
tokenService.Create(user, roles),
new CurrentUserResponse(
user.Id,
user.UserName!,
user.DisplayName,
var session = await authSessionService.CreateAsync(
user,
roles,
user.CollegeId,
EffectiveDataScopeResolver.Resolve(roles).ToString()));
request.IsNativeApp
? AuthenticationClientType.App
: AuthenticationClientType.Web,
cancellationToken);
return CreateLoginResponse(session);
}
[AllowAnonymous]
[EnableRateLimiting("token-refresh")]
[HttpPost("refresh")]
public async Task<ActionResult<LoginResponse>> Refresh(
RefreshTokenRequest request,
CancellationToken cancellationToken)
{
var session = await authSessionService.RefreshAsync(
request.RefreshToken,
cancellationToken);
if (session is null)
{
return Unauthorized(new ProblemDetails
{
Title = "登录已过期",
Detail = "登录已过期或刷新令牌已失效,请重新登录。",
Status = StatusCodes.Status401Unauthorized
});
}
return CreateLoginResponse(session);
}
[AllowAnonymous]
[HttpPost("logout")]
public async Task<IActionResult> Logout(
RefreshTokenRequest request,
CancellationToken cancellationToken)
{
await authSessionService.RevokeAsync(request.RefreshToken, cancellationToken);
return NoContent();
}
[Authorize]
@@ -212,11 +247,29 @@ public sealed class AuthController(
Detail = detail,
Status = status
});
internal static LoginResponse CreateLoginResponse(AuthSessionResult session) =>
new(
session.AccessToken,
session.AccessTokenExpiresAt,
session.RefreshToken,
session.SessionExpiresAt,
new CurrentUserResponse(
session.User.Id,
session.User.UserName!,
session.User.DisplayName,
session.Roles,
session.User.CollegeId,
EffectiveDataScopeResolver.Resolve(session.Roles).ToString()));
}
public sealed record LoginRequest(
[Required, MaxLength(100)] string UserName,
[Required, MaxLength(100)] string Password);
[Required, MaxLength(100)] string Password,
bool IsNativeApp = false);
public sealed record RefreshTokenRequest(
[Required, MinLength(40), MaxLength(200)] string RefreshToken);
public sealed record StudentActivationRequest(
[Required, MaxLength(50)] string Name,
@@ -227,7 +280,12 @@ public sealed record StudentActivationRequest(
Guid AdministrativeClassId,
[Required, MinLength(8), MaxLength(100)] string Password);
public sealed record LoginResponse(string Token, CurrentUserResponse User);
public sealed record LoginResponse(
string Token,
DateTime AccessTokenExpiresAt,
string RefreshToken,
DateTime SessionExpiresAt,
CurrentUserResponse User);
public sealed record CurrentUserResponse(
Guid Id,
@@ -1639,13 +1639,25 @@ public sealed class CourseSelectionsController(
var students = await LoadTeachingTaskRosterAsync(id, cancellationToken);
var bytes = ExcelWorkbookHelper.Create(
"教学班名单",
["学号", "姓名", "班级", "专业", "进入方式", "选课时间"],
[
"学号", "姓名", "班级", "专业", "联系电话", "电子邮箱",
"微信", "紧急联系人", "与本人关系", "紧急联系电话",
"特殊标记", "特殊情况说明", "进入方式", "选课时间"
],
students.Select(student => new List<object?>
{
student.StudentNumber,
student.Name,
student.ClassName,
student.MajorName,
student.Phone,
student.Email,
student.WeChat,
student.EmergencyContactName,
student.EmergencyContactRelationship,
student.EmergencyContactPhone,
student.SpecialTags,
student.SpecialNeeds,
student.EnrolledAt.HasValue ? "选课" : "行政班关联",
student.EnrolledAt?.ToString("yyyy-MM-dd HH:mm") ?? "-"
}).ToList<IReadOnlyList<object?>>());
@@ -1754,6 +1766,14 @@ public sealed class CourseSelectionsController(
x.Name,
x.AdministrativeClass!.Name,
x.AdministrativeClass.Major!.Name,
x.Phone,
x.Email,
x.WeChat,
x.EmergencyContactName,
x.EmergencyContactRelationship,
x.EmergencyContactPhone,
x.SpecialTags,
x.SpecialNeeds,
db.CourseEnrollments
.Where(enrollment =>
enrollment.StudentId == x.Id &&
@@ -2154,6 +2174,14 @@ public sealed class CourseSelectionsController(
string Name,
string ClassName,
string MajorName,
string? Phone,
string? Email,
string? WeChat,
string? EmergencyContactName,
string? EmergencyContactRelationship,
string? EmergencyContactPhone,
string? SpecialTags,
string? SpecialNeeds,
DateTime? EnrolledAt);
}
@@ -75,6 +75,7 @@ public sealed class ExperimentsController(
x.TaskNumber,
x.Name,
x.AcademicTermId,
x.CourseId,
TermName = x.AcademicTerm!.Name,
TermStartDate = x.AcademicTerm.StartDate,
TermEndDate = x.AcademicTerm.EndDate,
@@ -295,6 +296,76 @@ public sealed class ExperimentsController(
return Created(string.Empty, new { project.Id });
}
[HttpPost("batch")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> CreateProjects(
ExperimentProjectBatchRequest request,
CancellationToken cancellationToken)
{
var taskIds = request.TeachingTaskIds
.Where(x => x != Guid.Empty)
.Distinct()
.ToList();
if (taskIds.Count == 0)
return ValidationProblem("请至少选择一个教学任务。");
if (taskIds.Count > 100)
return ValidationProblem("单次最多为 100 个教学任务创建实验项目。");
var tasks = await AccessibleTeachingTasks().AsNoTracking()
.Include(x => x.AcademicTerm)
.WhereIn(taskIds, x => x.Id)
.Where(x => x.Status == TeachingTaskStatus.Published)
.OrderBy(x => x.TaskNumber)
.ToListAsync(cancellationToken);
if (tasks.Count != taskIds.Count)
return ValidationProblem("部分教学任务不存在、未发布或不在当前管理范围内。");
var first = tasks[0];
if (tasks.Any(x =>
x.AcademicTermId != first.AcademicTermId ||
x.CourseId != first.CourseId))
return ValidationProblem("批量设置仅支持同一学期、同一课程的教学任务。");
var code = request.Code.Trim();
var conflictingTaskNumbers = await db.ExperimentProjects.AsNoTracking()
.WhereIn(taskIds, x => x.TeachingTaskId)
.Where(x => x.Code == code)
.Select(x => x.TeachingTask!.TaskNumber)
.OrderBy(x => x)
.ToListAsync(cancellationToken);
if (conflictingTaskNumbers.Count > 0)
return ConflictProblem(
$"以下教学任务已存在实验项目编码 {code}{string.Join("", conflictingTaskNumbers)}。");
var projects = new List<ExperimentProject>(tasks.Count);
foreach (var task in tasks)
{
var item = request.ForTeachingTask(task.Id);
var problem = ValidateProjectRequest(item, task.AcademicTerm!);
if (problem is not null) return ValidationProblem(problem);
projects.Add(new ExperimentProject
{
TeachingTaskId = task.Id,
Code = code,
Name = request.Name.Trim(),
ArrangementMode = request.ArrangementMode,
Description = Normalize(request.Description),
Requirements = Normalize(request.Requirements),
StartDate = request.StartDate,
EndDate = request.EndDate
});
}
db.ExperimentProjects.AddRange(projects);
await db.SaveChangesAsync(cancellationToken);
return Created(string.Empty, new
{
Count = projects.Count,
ProjectIds = projects.Select(x => x.Id)
});
}
[HttpPut("{id:guid}")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> UpdateProject(
@@ -478,6 +549,101 @@ public sealed class ExperimentsController(
return Created(string.Empty, new { session.Id });
}
[HttpPost("sessions/batch")]
[Authorize(Roles = Managers)]
public Task<ActionResult> CreateSessions(
ExperimentSessionBatchRequest request,
CancellationToken cancellationToken)
{
if (request.Items.Count == 0)
return Task.FromResult<ActionResult>(
ValidationProblem("请至少添加一条实验排课。"));
if (request.Items.Count > 100)
return Task.FromResult<ActionResult>(
ValidationProblem("单次最多安排 100 条实验场次。"));
if (request.Items.Any(x => x.ProjectId == Guid.Empty) ||
request.Items.Select(x => x.ProjectId).Distinct().Count() !=
request.Items.Count)
return Task.FromResult<ActionResult>(
ValidationProblem("同一批次中每个实验项目只能安排一个场次。"));
return db.ExecuteInRetriableTransactionAsync<ActionResult>(
async transaction =>
{
var projectIds = request.Items.Select(x => x.ProjectId).ToList();
var projects = await ScopedProjects()
.Include(x => x.TeachingTask)
.ThenInclude(x => x!.AcademicTerm)
.WhereIn(projectIds, x => x.Id)
.ToDictionaryAsync(x => x.Id, cancellationToken);
if (projects.Count != projectIds.Count)
return ValidationProblem(
"部分实验项目不存在或不在当前管理范围内。");
var createdSessions = new List<(ExperimentProject Project, ExperimentSession Session)>(
request.Items.Count);
foreach (var item in request.Items)
{
var project = projects[item.ProjectId];
if (project.Status == ExperimentProjectStatus.Closed)
return ConflictProblem(
$"实验项目“{project.Name}”已关闭,不能再增加场次。");
var sessionRequest = item.ToSessionRequest();
var problem = await ValidateSessionAsync(
project,
sessionRequest,
cancellationToken);
if (problem is not null)
return ConflictProblem(
$"实验项目“{project.Name}”:{problem}");
var session = new ExperimentSession
{
ExperimentProjectId = project.Id,
ClassroomId = item.ClassroomId,
SessionDate = item.SessionDate,
StartPeriod = item.StartPeriod,
PeriodCount = item.PeriodCount,
Capacity = await ResolveSessionCapacityAsync(
project,
item.Capacity,
cancellationToken),
Notes = Normalize(item.Notes)
};
db.ExperimentSessions.Add(session);
await db.SaveChangesAsync(cancellationToken);
createdSessions.Add((project, session));
}
foreach (var (project, session) in createdSessions.Where(x =>
x.Project.Status == ExperimentProjectStatus.Published))
{
var userIds = await RosterUserIdsAsync(
project.TeachingTaskId,
cancellationToken);
if (userIds.Count == 0) continue;
await NotificationService.SendToUserIdsAsync(
db,
userIds,
"新增实验场次",
$"“{project.Name}”新增 {session.SessionDate:yyyy-MM-dd} 第 {session.StartPeriod}—{session.StartPeriod + session.PeriodCount - 1} 节场次,请查看实验安排。",
"/experiments",
cancellationToken,
NotificationCategory.Schedule);
}
await transaction.CommitAsync(cancellationToken);
return Created(string.Empty, new
{
Count = createdSessions.Count,
SessionIds = createdSessions.Select(x => x.Session.Id)
});
},
cancellationToken,
IsolationLevel.Serializable);
}
[HttpDelete("sessions/{id:guid}")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> CancelSession(
@@ -1029,6 +1195,28 @@ public sealed record ExperimentProjectRequest(
DateOnly StartDate,
DateOnly EndDate);
public sealed record ExperimentProjectBatchRequest(
[Required] IReadOnlyList<Guid> TeachingTaskIds,
[Required, MaxLength(40)] string Code,
[Required, MaxLength(120)] string Name,
ExperimentArrangementMode ArrangementMode,
[MaxLength(1000)] string? Description,
[MaxLength(1000)] string? Requirements,
DateOnly StartDate,
DateOnly EndDate)
{
public ExperimentProjectRequest ForTeachingTask(Guid teachingTaskId) =>
new(
teachingTaskId,
Code,
Name,
ArrangementMode,
Description,
Requirements,
StartDate,
EndDate);
}
public sealed record ExperimentSessionRequest(
Guid ClassroomId,
DateOnly SessionDate,
@@ -1037,6 +1225,28 @@ public sealed record ExperimentSessionRequest(
[Range(1, 10000)] int Capacity,
[MaxLength(500)] string? Notes);
public sealed record ExperimentSessionBatchRequest(
[Required] IReadOnlyList<ExperimentSessionBatchItem> Items);
public sealed record ExperimentSessionBatchItem(
Guid ProjectId,
Guid ClassroomId,
DateOnly SessionDate,
[Range(1, 30)] int StartPeriod,
[Range(1, 30)] int PeriodCount,
[Range(1, 10000)] int Capacity,
[MaxLength(500)] string? Notes)
{
public ExperimentSessionRequest ToSessionRequest() =>
new(
ClassroomId,
SessionDate,
StartPeriod,
PeriodCount,
Capacity,
Notes);
}
public sealed record ExperimentPeriodOption(
Guid AcademicTermId,
int PeriodNumber,
@@ -4,6 +4,7 @@ using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Domain.System;
using Jiaowu.Api.Infrastructure.Operations;
using Jiaowu.Api.Infrastructure.Observability;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -18,8 +19,27 @@ public sealed class OperationsController(
AppDbContext db,
OperationalHealthService healthService,
DatabaseBackupService backupService,
PerformanceReportService performanceReportService,
OperationsOptions options) : ControllerBase
{
[HttpGet("performance")]
public async Task<ActionResult<PerformanceReport>> GetPerformance(
[FromQuery] string? range = "1h",
CancellationToken cancellationToken = default)
{
try
{
return Ok(await performanceReportService.GetAsync(
range,
cancellationToken));
}
catch (ArgumentOutOfRangeException)
{
return ValidationProblem(
"性能报表范围仅支持 15m、1h、24h 或 7d。");
}
}
[HttpGet("summary")]
public async Task<ActionResult<OperationsSummary>> GetSummary(
CancellationToken cancellationToken)
@@ -0,0 +1,216 @@
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Excel;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Jiaowu.Api.Controllers;
[ApiController]
[Authorize]
[Route("api/other-exams")]
public sealed class OtherExamsController(AppDbContext db, ICurrentUserDataScope scope) : ControllerBase
{
private const string Managers = SystemRoles.SuperAdmin + "," + SystemRoles.AcademicAdmin;
[HttpGet("batches")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> GetBatches(CancellationToken ct) => Ok(await db.OtherExamBatches
.AsNoTracking().OrderByDescending(x => x.ExamDate).ThenByDescending(x => x.CreatedAt)
.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, ResultCount = x.Results.Count })
.ToListAsync(ct));
[HttpPost("batches")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> CreateBatch(CreateOtherExamRequest request, CancellationToken ct)
{
var code = Normalize(request.ExamCode)?.ToUpperInvariant();
var name = Normalize(request.Name);
if (code is null || name is null) return ValidationProblem("考试编码和考试名称不能为空。");
var error = ValidateDefinition(request.MetricKind, request.MaxScore, request.LevelOptions);
if (error is not null) return ValidationProblem(error);
var definitionConflict = await db.OtherExamBatches.AnyAsync(x =>
x.ExamCode == code && (x.MetricKind != request.MetricKind || x.MaxScore != request.MaxScore || x.LevelOptions != Normalize(request.LevelOptions)), ct);
if (definitionConflict) return ConflictProblem("同一考试编码已经使用了不同的评价方式或评价参数,请检查考试编码。");
var batch = new OtherExamBatch { ExamCode = code, Name = name, Organizer = Normalize(request.Organizer), ExamDate = request.ExamDate, MetricKind = request.MetricKind, MaxScore = request.MaxScore, LevelOptions = Normalize(request.LevelOptions) };
db.OtherExamBatches.Add(batch);
await db.SaveChangesAsync(ct);
return Ok(new { batch.Id });
}
[HttpGet("students/lookup")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> LookupStudent(string studentNumber, CancellationToken ct)
{
var number = Normalize(studentNumber);
if (number is null) return ValidationProblem("请输入学号。");
var student = await db.Students.AsNoTracking().Where(x => x.StudentNumber == number)
.Select(x => new { x.Id, x.StudentNumber, x.Name, CollegeName = x.AdministrativeClass!.Major!.College!.Name, ClassName = x.AdministrativeClass!.Name }).FirstOrDefaultAsync(ct);
return student is null ? NotFound(new ProblemDetails { Detail = "未找到该学号对应的学生档案。", Status = 404 }) : Ok(student);
}
[HttpGet("batches/{id:guid}")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> GetBatch(Guid id, CancellationToken ct)
{
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);
if (batch is null) return NotFound();
var results = await db.OtherExamResults.AsNoTracking().Where(x => x.OtherExamBatchId == id)
.OrderBy(x => x.Student!.StudentNumber)
.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);
return Ok(new { Batch = batch, Results = results });
}
[HttpPut("batches/{id:guid}/results")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> ReplaceResults(Guid id, ReplaceOtherExamResultsRequest request, CancellationToken ct)
{
var batch = await db.OtherExamBatches.Include(x => x.Results).FirstOrDefaultAsync(x => x.Id == id, ct);
if (batch is null) return NotFound();
var result = await ReplaceResultsAsync(batch, request.Results, ct);
return result is null ? Ok(new { updated = batch.Results.Count }) : result;
}
[HttpGet("batches/{id:guid}/template")]
[Authorize(Roles = Managers)]
public async Task<IActionResult> DownloadTemplate(Guid id, CancellationToken ct)
{
var batch = await db.OtherExamBatches.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id, ct);
if (batch is null) return NotFound();
var headers = HeadersFor(batch);
var bytes = ExcelWorkbookHelper.Create("其他考试成绩导入", headers, [], ["第一行为表头,请勿修改;每行填写一名学生。", "学号用于自动匹配姓名、学院和班级,参加次数由系统自动计算。"]);
return File(bytes, ExcelWorkbookHelper.ContentType, $"其他考试成绩导入模板-{batch.ExamCode ?? batch.Name}.xlsx");
}
[HttpPost("batches/{id:guid}/import")]
[Authorize(Roles = Managers)]
[RequestSizeLimit(10 * 1024 * 1024)]
public async Task<ActionResult> Import(Guid id, IFormFile file, CancellationToken ct)
{
var batch = await db.OtherExamBatches.Include(x => x.Results).FirstOrDefaultAsync(x => x.Id == id, ct);
if (batch is null) return NotFound();
IReadOnlyList<ExcelRow> rows;
try { rows = await ExcelWorkbookHelper.ReadAsync(file, HeadersFor(batch), ct); }
catch (InvalidDataException ex) { return ValidationProblem(ex.Message); }
if (rows.Count == 0) return ValidationProblem("Excel 中没有可导入的成绩数据。");
var inputs = new List<OtherExamResultRequest>();
var errors = new List<string>();
foreach (var row in rows)
{
var number = row["学号"].Trim();
if (number.Length == 0) { errors.Add($"第 {row.RowNumber} 行:学号不能为空。"); continue; }
var score = batch.MetricKind == OtherExamMetricKind.Score ? ParseScore(row, batch, errors) : null;
var level = batch.MetricKind == OtherExamMetricKind.Level ? Normalize(row["等级"]) : null;
var passed = batch.MetricKind == OtherExamMetricKind.PassFail ? ParsePass(row["是否合格"], row.RowNumber, errors) : null;
inputs.Add(new OtherExamResultRequest(number, score, level, passed, Normalize(row["备注"])));
}
if (errors.Count > 0) return ImportValidationProblem(errors);
var result = await ReplaceResultsAsync(batch, inputs, ct);
return result ?? Ok(new { updated = inputs.Count });
}
[HttpPost("batches/{id:guid}/publish")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> Publish(Guid id, CancellationToken ct)
{
var batch = await db.OtherExamBatches.Include(x => x.Results).FirstOrDefaultAsync(x => x.Id == id, ct);
if (batch is null) return NotFound();
if (batch.Results.Count == 0) return ConflictProblem("没有成绩记录,不能发布。");
batch.Status = OtherExamBatchStatus.Published;
batch.PublicationCount++;
batch.PublishedAt = DateTime.UtcNow;
await db.SaveChangesAsync(ct);
return Ok(new { batch.PublicationCount, batch.PublishedAt });
}
[HttpGet("mine")]
[Authorize(Roles = SystemRoles.Student)]
public async Task<ActionResult> Mine(CancellationToken ct)
{
var studentId = await db.Students.Where(x => x.UserId == scope.Current.UserId).Select(x => (Guid?)x.Id).FirstOrDefaultAsync(ct);
if (studentId is null) return ConflictProblem("当前账号未关联有效学生档案。");
var history = await db.OtherExamResults.AsNoTracking().Where(x => x.StudentId == studentId && x.OtherExamBatch!.Status == OtherExamBatchStatus.Published)
.OrderByDescending(x => x.OtherExamBatch!.ExamDate).ThenByDescending(x => x.AttemptNumber)
.Select(x => new { x.Id, ExamCode = x.OtherExamBatch!.ExamCode ?? x.OtherExamBatch.Name, BatchId = x.OtherExamBatchId, ExamName = x.OtherExamBatch.Name, x.OtherExamBatch.ExamDate, x.OtherExamBatch.MetricKind, x.OtherExamBatch.MaxScore, x.OtherExamBatch.LevelOptions, x.AttemptNumber, x.Score, x.Level, x.IsPassed, x.OtherExamBatch.PublishedAt }).ToListAsync(ct);
var best = history.GroupBy(x => x.ExamCode).Select(g => g.OrderByDescending(x => Rank(x.MetricKind, x.Score, x.Level, x.IsPassed, x.LevelOptions)).ThenByDescending(x => x.ExamDate).First()).ToList();
return Ok(new { Best = best, History = history });
}
private async Task<ActionResult?> ReplaceResultsAsync(OtherExamBatch batch, IReadOnlyList<OtherExamResultRequest> inputs, CancellationToken ct)
{
var numbers = inputs.Select(x => x.StudentNumber.Trim()).ToList();
if (numbers.Count != numbers.Distinct(StringComparer.OrdinalIgnoreCase).Count()) return ValidationProblem("同一考试批次中学生不能重复出现。");
var students = await db.Students.Where(x => numbers.Contains(x.StudentNumber)).ToDictionaryAsync(x => x.StudentNumber, StringComparer.OrdinalIgnoreCase, ct);
if (students.Count != numbers.Count) return ValidationProblem("存在不存在的学号,请先检查学生档案。");
foreach (var item in inputs)
{
var error = ValidateResult(batch, item.Score, item.Level, item.IsPassed);
if (error is not null) return ValidationProblem(error);
}
var studentIds = students.Values.Select(x => x.Id).ToList();
var beforeCount = await db.OtherExamResults.AsNoTracking()
.Where(x => x.OtherExamBatchId != batch.Id && studentIds.Contains(x.StudentId) && (x.OtherExamBatch!.ExamCode == batch.ExamCode || (x.OtherExamBatch.ExamCode == null && batch.ExamCode == null && x.OtherExamBatch.Name == batch.Name)) && (x.OtherExamBatch.ExamDate < batch.ExamDate || (x.OtherExamBatch.ExamDate == batch.ExamDate && x.OtherExamBatch.CreatedAt < batch.CreatedAt)))
.GroupBy(x => x.StudentId).Select(x => new { StudentId = x.Key, Count = x.Count() }).ToDictionaryAsync(x => x.StudentId, x => x.Count, ct);
db.OtherExamResults.RemoveRange(batch.Results);
batch.Status = OtherExamBatchStatus.Draft;
batch.Results = inputs.Select(x => { var student = students[x.StudentNumber.Trim()]; return new OtherExamResult { OtherExamBatchId = batch.Id, StudentId = student.Id, AttemptNumber = (beforeCount.GetValueOrDefault(student.Id) + 1), Score = x.Score, Level = Normalize(x.Level), IsPassed = x.IsPassed, Notes = Normalize(x.Notes) }; }).ToList();
await db.SaveChangesAsync(ct);
return null;
}
private static string[] HeadersFor(OtherExamBatch batch) => batch.MetricKind switch
{
OtherExamMetricKind.Score => ["学号", "成绩", "备注"],
OtherExamMetricKind.Level => ["学号", "等级", "备注"],
_ => ["学号", "是否合格", "备注"]
};
private static decimal? ParseScore(ExcelRow row, OtherExamBatch batch, List<string> errors)
{
if (decimal.TryParse(row["成绩"], NumberStyles.Number, CultureInfo.InvariantCulture, out var value) && value >= 0 && value <= batch.MaxScore) return value;
errors.Add($"第 {row.RowNumber} 行:成绩必须在 0 到 {batch.MaxScore:0.##} 之间。"); return null;
}
private static bool? ParsePass(string value, int row, List<string> errors)
{
if (value is "合格" or "是" or "通过" or "true" or "True") return true;
if (value is "不合格" or "否" or "未通过" or "false" or "False") return false;
errors.Add($"第 {row} 行:是否合格请填写合格或不合格。"); return null;
}
private static string? ValidateDefinition(OtherExamMetricKind kind, decimal? max, string? levels) => kind switch
{
OtherExamMetricKind.Score when !max.HasValue || max <= 0 => "分数制必须填写大于 0 的满分。",
OtherExamMetricKind.Level when string.IsNullOrWhiteSpace(levels) => "等级制必须填写等级选项。",
_ => null
};
private static string? ValidateResult(OtherExamBatch b, decimal? score, string? level, bool? pass) => b.MetricKind switch
{
OtherExamMetricKind.Score when !score.HasValue || score < 0 || score > b.MaxScore => "分数必须在 0 到满分之间。",
OtherExamMetricKind.Level when string.IsNullOrWhiteSpace(level) => "等级制必须填写等级。",
OtherExamMetricKind.PassFail when !pass.HasValue => "合格/不合格考试必须填写结果。",
_ => null
};
private static int Rank(OtherExamMetricKind kind, decimal? score, string? level, bool? pass, string? options)
{
if (kind == OtherExamMetricKind.Score) return (int)((score ?? -1) * 1000);
if (kind == OtherExamMetricKind.PassFail) return pass == true ? 1 : 0;
var levels = (options ?? "").Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
var index = Array.IndexOf(levels, level ?? "");
return index >= 0 ? levels.Length - index : -1;
}
private ActionResult ImportValidationProblem(IReadOnlyList<string> errors)
{
foreach (var error in errors.Take(50)) ModelState.AddModelError("file", error);
return ValidationProblem(ModelState);
}
private static string? Normalize(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
private static ConflictObjectResult ConflictProblem(string message) => new(new ProblemDetails { Status = 409, Detail = message });
}
public sealed record CreateOtherExamRequest([Required] string ExamCode, [Required] string Name, DateOnly ExamDate, OtherExamMetricKind MetricKind, decimal? MaxScore, string? LevelOptions, string? Organizer);
public sealed record ReplaceOtherExamResultsRequest(List<OtherExamResultRequest> Results);
public sealed record OtherExamResultRequest([Required] string StudentNumber, decimal? Score, string? Level, bool? IsPassed, string? Notes);
@@ -224,6 +224,12 @@ public sealed class PersonnelController(
[FromQuery] PersonnelQuery query,
CancellationToken cancellationToken)
{
var roles = currentUserDataScope.Current.Roles;
var canReadFullProfile = roles.Any(role =>
role is SystemRoles.SuperAdmin or
SystemRoles.AcademicAdmin or
SystemRoles.CollegeAdmin or
SystemRoles.Counselor);
var page = NormalizePage(query.Page);
var pageSize = NormalizePageSize(query.PageSize);
var source = ApplyStudentScope(db.Students.AsNoTracking());
@@ -268,9 +274,26 @@ public sealed class PersonnelController(
x.EnrollmentDate,
x.Status,
x.DateOfBirth,
EnglishName = canReadFullProfile ? x.EnglishName : null,
IdCardNumber = canReadFullProfile ? x.IdCardNumber : null,
Nationality = canReadFullProfile ? x.Nationality : null,
Ethnicity = canReadFullProfile ? x.Ethnicity : null,
PoliticalStatus = canReadFullProfile ? x.PoliticalStatus : null,
NativePlace = canReadFullProfile ? x.NativePlace : null,
HouseholdAddress = canReadFullProfile ? x.HouseholdAddress : null,
CurrentAddress = canReadFullProfile ? x.CurrentAddress : null,
PostalCode = canReadFullProfile ? x.PostalCode : null,
x.Phone,
x.Email,
x.Notes,
Qq = canReadFullProfile ? x.Qq : null,
x.WeChat,
x.EmergencyContactName,
x.EmergencyContactRelationship,
x.EmergencyContactPhone,
x.SpecialTags,
x.SpecialNeeds,
Biography = canReadFullProfile ? x.Biography : null,
Notes = canReadFullProfile ? x.Notes : null,
x.UserId,
x.CreatedAt
})
@@ -304,8 +327,26 @@ public sealed class PersonnelController(
EnrollmentDate = request.EnrollmentDate,
Status = request.Status,
DateOfBirth = request.DateOfBirth,
EnglishName = Normalize(request.EnglishName),
IdCardNumber = Normalize(request.IdCardNumber),
Nationality = Normalize(request.Nationality),
Ethnicity = Normalize(request.Ethnicity),
PoliticalStatus = Normalize(request.PoliticalStatus),
NativePlace = Normalize(request.NativePlace),
HouseholdAddress = Normalize(request.HouseholdAddress),
CurrentAddress = Normalize(request.CurrentAddress),
PostalCode = Normalize(request.PostalCode),
Phone = Normalize(request.Phone),
Email = Normalize(request.Email),
Qq = Normalize(request.Qq),
WeChat = Normalize(request.WeChat),
EmergencyContactName = Normalize(request.EmergencyContactName),
EmergencyContactRelationship = Normalize(
request.EmergencyContactRelationship),
EmergencyContactPhone = Normalize(request.EmergencyContactPhone),
SpecialTags = Normalize(request.SpecialTags),
SpecialNeeds = Normalize(request.SpecialNeeds),
Biography = Normalize(request.Biography),
Notes = Normalize(request.Notes)
};
db.Students.Add(entity);
@@ -343,8 +384,26 @@ public sealed class PersonnelController(
entity.EnrollmentDate = request.EnrollmentDate;
entity.Status = request.Status;
entity.DateOfBirth = request.DateOfBirth;
entity.EnglishName = Normalize(request.EnglishName);
entity.IdCardNumber = Normalize(request.IdCardNumber);
entity.Nationality = Normalize(request.Nationality);
entity.Ethnicity = Normalize(request.Ethnicity);
entity.PoliticalStatus = Normalize(request.PoliticalStatus);
entity.NativePlace = Normalize(request.NativePlace);
entity.HouseholdAddress = Normalize(request.HouseholdAddress);
entity.CurrentAddress = Normalize(request.CurrentAddress);
entity.PostalCode = Normalize(request.PostalCode);
entity.Phone = Normalize(request.Phone);
entity.Email = Normalize(request.Email);
entity.Qq = Normalize(request.Qq);
entity.WeChat = Normalize(request.WeChat);
entity.EmergencyContactName = Normalize(request.EmergencyContactName);
entity.EmergencyContactRelationship = Normalize(
request.EmergencyContactRelationship);
entity.EmergencyContactPhone = Normalize(request.EmergencyContactPhone);
entity.SpecialTags = Normalize(request.SpecialTags);
entity.SpecialNeeds = Normalize(request.SpecialNeeds);
entity.Biography = Normalize(request.Biography);
entity.Notes = Normalize(request.Notes);
return await SaveNoContentAsync(cancellationToken);
}
@@ -522,8 +581,25 @@ public sealed record StudentRequest(
DateOnly EnrollmentDate,
StudentStatus Status,
DateOnly? DateOfBirth,
[MaxLength(100)] string? EnglishName,
[MaxLength(30)] string? IdCardNumber,
[MaxLength(50)] string? Nationality,
[MaxLength(50)] string? Ethnicity,
[MaxLength(50)] string? PoliticalStatus,
[MaxLength(100)] string? NativePlace,
[MaxLength(300)] string? HouseholdAddress,
[MaxLength(300)] string? CurrentAddress,
[MaxLength(20)] string? PostalCode,
[MaxLength(30)] string? Phone,
[EmailAddress, MaxLength(100)] string? Email,
[MaxLength(30)] string? Qq,
[MaxLength(60)] string? WeChat,
[MaxLength(50)] string? EmergencyContactName,
[MaxLength(30)] string? EmergencyContactRelationship,
[MaxLength(30)] string? EmergencyContactPhone,
[MaxLength(300)] string? SpecialTags,
[MaxLength(1000)] string? SpecialNeeds,
[MaxLength(1000)] string? Biography,
[MaxLength(500)] string? Notes);
public sealed record TeacherAccountActivationRequest(
@@ -31,6 +31,9 @@ public sealed class PersonnelExcelController(
SystemRoles.AcademicAdmin + "," +
SystemRoles.CollegeAdmin;
private const string ExportRoles =
WriteRoles + "," + SystemRoles.Counselor;
private static readonly string[] TeacherHeaders =
[
"工号", "姓名", "性别", "学院编码", "职称", "任职状态",
@@ -40,7 +43,10 @@ public sealed class PersonnelExcelController(
private static readonly string[] StudentHeaders =
[
"学号", "姓名", "性别", "行政班编码", "入学年级", "入学日期",
"学籍状态", "出生日期", "联系电话", "电子邮箱", "备注"
"学籍状态", "出生日期", "英文姓名", "证件号码", "国籍", "民族",
"政治面貌", "籍贯", "户籍地址", "现居住地址", "邮政编码",
"联系电话", "电子邮箱", "QQ", "微信", "紧急联系人", "与本人关系",
"紧急联系电话", "特殊标记", "特殊情况说明", "个人简介", "备注"
];
[HttpGet("{kind}/template")]
@@ -66,6 +72,7 @@ public sealed class PersonnelExcelController(
}
[HttpGet("{kind}/export")]
[Authorize(Roles = ExportRoles)]
public async Task<IActionResult> Export(
string kind,
[FromQuery] PersonnelQuery query,
@@ -96,7 +103,12 @@ public sealed class PersonnelExcelController(
.Select(x => Row(
x.StudentNumber, x.Name, GenderName(x.Gender),
x.AdministrativeClass!.Code, x.EnrollmentYear, x.EnrollmentDate,
StudentStatusName(x.Status), x.DateOfBirth, x.Phone, x.Email, x.Notes))
StudentStatusName(x.Status), x.DateOfBirth, x.EnglishName,
x.IdCardNumber, x.Nationality, x.Ethnicity, x.PoliticalStatus,
x.NativePlace, x.HouseholdAddress, x.CurrentAddress, x.PostalCode,
x.Phone, x.Email, x.Qq, x.WeChat, x.EmergencyContactName,
x.EmergencyContactRelationship, x.EmergencyContactPhone,
x.SpecialTags, x.SpecialNeeds, x.Biography, x.Notes))
.ToList();
}
@@ -296,8 +308,25 @@ public sealed class PersonnelExcelController(
entity.EnrollmentDate = enrollmentDate.Value;
entity.Status = status.Value;
entity.DateOfBirth = dateOfBirth;
entity.EnglishName = Optional(row, "英文姓名");
entity.IdCardNumber = Optional(row, "证件号码");
entity.Nationality = Optional(row, "国籍");
entity.Ethnicity = Optional(row, "民族");
entity.PoliticalStatus = Optional(row, "政治面貌");
entity.NativePlace = Optional(row, "籍贯");
entity.HouseholdAddress = Optional(row, "户籍地址");
entity.CurrentAddress = Optional(row, "现居住地址");
entity.PostalCode = Optional(row, "邮政编码");
entity.Phone = Optional(row, "联系电话");
entity.Email = Optional(row, "电子邮箱");
entity.Qq = Optional(row, "QQ");
entity.WeChat = Optional(row, "微信");
entity.EmergencyContactName = Optional(row, "紧急联系人");
entity.EmergencyContactRelationship = Optional(row, "与本人关系");
entity.EmergencyContactPhone = Optional(row, "紧急联系电话");
entity.SpecialTags = Optional(row, "特殊标记");
entity.SpecialNeeds = Optional(row, "特殊情况说明");
entity.Biography = Optional(row, "个人简介");
entity.Notes = Optional(row, "备注");
}
return new(created, updated, rows.Count);
@@ -3,7 +3,6 @@ using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Caching;
using Jiaowu.Api.Infrastructure.Persistence;
using Jiaowu.Api.Infrastructure.Teaching;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
@@ -110,15 +109,6 @@ public sealed class ScheduleSettingsController(AppDbContext db, IAppCache cache)
return Ok(tasks.Select(task =>
{
constraints.TryGetValue(task.Id, out var constraint);
var weeklyHours = task.WeeklyHours;
if (task.SchedulingMode == TeachingTaskSchedulingMode.Standard &&
TeachingTaskHours.TryResolveRegularWeeklyHours(
task.CourseTotalHours,
task.CoursePracticeHours,
task.StartWeek,
task.EndWeek,
out var regularWeeklyHours))
weeklyHours = regularWeeklyHours;
return new
{
task.Id,
@@ -132,7 +122,7 @@ public sealed class ScheduleSettingsController(AppDbContext db, IAppCache cache)
task.Capacity,
task.StartWeek,
task.EndWeek,
WeeklyHours = weeklyHours,
task.WeeklyHours,
task.CourseTotalHours,
task.CoursePracticeHours,
task.SchedulingMode,
@@ -71,6 +71,7 @@ public sealed class SchedulesController(
{
entry.Id,
entry.TeachingTaskId,
entry.Kind,
TaskNumber = entry.TeachingTask!.TaskNumber,
TaskName = entry.TeachingTask.Name,
CourseCode = entry.TeachingTask.Course!.Code,
@@ -167,6 +168,7 @@ public sealed class SchedulesController(
Entries = source.Entries.Select(entry => new ScheduleEntry
{
TeachingTaskId = entry.TeachingTaskId,
Kind = entry.Kind,
ClassroomId = entry.ClassroomId,
DayOfWeek = entry.DayOfWeek,
StartPeriod = entry.StartPeriod,
@@ -419,6 +421,7 @@ public sealed class SchedulesController(
var validation = await ValidateEntryAsync(plan, entryId, request, cancellationToken);
if (validation is not null) return validation;
entry.TeachingTaskId = request.TeachingTaskId;
entry.Kind = request.Kind;
entry.ClassroomId = request.ClassroomId;
entry.DayOfWeek = request.DayOfWeek;
entry.StartPeriod = request.StartPeriod;
@@ -508,34 +511,52 @@ public sealed class SchedulesController(
return ValidationProblem("非排时课程不进入正常课表,无需设置星期、节次或教室。");
if (request.StartWeek < task.StartWeek || request.EndWeek > task.EndWeek)
return ValidationProblem("排课周次必须位于教学任务的授课周次内。");
if (!TeachingTaskHours.TryResolveRegularWeeklyHours(
var targetHours = TeachingTaskHours.TargetHours(
task.Course!,
task.StartWeek,
task.EndWeek,
out var requiredWeeklyHours))
request.Kind);
if (targetHours == 0)
return ValidationProblem(
"该课程的普通排课学时不能按授课周次整除,请先调整教学任务周次。");
if (requiredWeeklyHours == 0)
return ValidationProblem(
"该课程全部为实践学时,无需进入普通课表,请在实验管理中安排。");
var existingHours = await db.ScheduleEntries.AsNoTracking()
request.Kind == ScheduleEntryKind.Experiment
? "该课程没有实践学时,不能安排实验课。"
: "该课程没有理论学时,不能安排理论课。");
var existingEntries = await db.ScheduleEntries.AsNoTracking()
.Where(x =>
x.SchedulePlanId == plan.Id &&
x.TeachingTaskId == request.TeachingTaskId &&
x.Kind == request.Kind &&
x.Id != entryId)
.SumAsync(x => x.PeriodCount, cancellationToken);
if (existingHours + request.PeriodCount > requiredWeeklyHours)
.Select(x => new
{
x.StartWeek,
x.EndWeek,
x.WeekPattern,
x.PeriodCount
})
.ToListAsync(cancellationToken);
var existingHours = existingEntries.Sum(x =>
TeachingTaskHours.ScheduledHours(
x.StartWeek,
x.EndWeek,
x.WeekPattern,
x.PeriodCount));
var proposedHours = TeachingTaskHours.ScheduledHours(
request.StartWeek,
request.EndWeek,
request.WeekPattern,
request.PeriodCount);
if (existingHours + proposedHours > targetHours)
return ValidationProblem(
$"该教学任务普通课表每周只需 {requiredWeeklyHours} 学时;" +
$"当前操作后将达到 {existingHours + request.PeriodCount} 学时," +
"实践学时请在实验管理中安排。");
$"该教学任务{(request.Kind == ScheduleEntryKind.Experiment ? "" : "")}课" +
$"共需 {targetHours} 学时;当前操作后将达到 " +
$"{existingHours + proposedHours} 学时。");
var constraint = await db.TeachingTaskScheduleConstraints.AsNoTracking()
.Include(x => x.AllowedClassrooms)
.FirstOrDefaultAsync(
x => x.TeachingTaskId == request.TeachingTaskId,
cancellationToken);
var requiresClassroom = constraint?.RequiresClassroom ?? true;
var requiresClassroom = request.Kind == ScheduleEntryKind.Experiment ||
constraint?.RequiresClassroom != false;
if (requiresClassroom && !request.ClassroomId.HasValue)
return ValidationProblem("该课程需要占用教室,请选择教室。");
if (!requiresClassroom && request.ClassroomId.HasValue)
@@ -559,6 +580,10 @@ public sealed class SchedulesController(
x => x.Id == request.ClassroomId && x.IsEnabled,
cancellationToken);
if (classroom is null) return ValidationProblem("所选教室不存在或已停用。");
if (request.Kind == ScheduleEntryKind.Experiment &&
!IsExperimentRoom(classroom.RoomType))
return ValidationProblem(
$"实验课必须安排在实验室、实训室或机房;“{classroom.Name}”的场地类型为“{classroom.RoomType}”。");
if (constraint?.RequiredCampusId is Guid campusId &&
classroom.Building!.CampusId != campusId)
return ValidationProblem("所选教室不在该课程指定的校区。");
@@ -612,6 +637,7 @@ public sealed class SchedulesController(
{
SchedulePlanId = planId,
TeachingTaskId = request.TeachingTaskId,
Kind = request.Kind,
ClassroomId = request.ClassroomId,
DayOfWeek = request.DayOfWeek,
StartPeriod = request.StartPeriod,
@@ -629,6 +655,12 @@ public sealed class SchedulesController(
.Select(int.Parse)
.ToHashSet();
private static bool IsExperimentRoom(string roomType) =>
roomType.Contains("实验", StringComparison.OrdinalIgnoreCase) ||
roomType.Contains("实训", StringComparison.OrdinalIgnoreCase) ||
roomType.Contains("机房", StringComparison.OrdinalIgnoreCase) ||
roomType.Contains("语音", StringComparison.OrdinalIgnoreCase);
private async Task<ActionResult> SaveAsync(
Guid id,
bool created,
@@ -726,7 +758,8 @@ public sealed record ScheduleEntryRequest(
[Range(1, 30)] int StartWeek,
[Range(1, 30)] int EndWeek,
WeekPattern WeekPattern,
[MaxLength(500)] string? Notes);
[MaxLength(500)] string? Notes,
ScheduleEntryKind Kind = ScheduleEntryKind.Lecture);
public sealed record AutomaticScheduleJobResponse(
Guid Id,
+550
View File
@@ -0,0 +1,550 @@
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text.Json;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Auth;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
namespace Jiaowu.Api.Controllers;
[ApiController]
[Route("api/auth/sso")]
public sealed class SsoController(
UserManager<ApplicationUser> userManager,
IAuthSessionService authSessionService,
IDistributedCache cache,
IOptions<SsoOptions> options,
ILogger<SsoController> logger) : ControllerBase
{
private const string BindingIntentProperty = "sso-binding-intent";
private readonly SsoOptions _options = options.Value;
[AllowAnonymous]
[HttpGet("settings")]
public ActionResult<SsoSettingsResponse> Settings() =>
new SsoSettingsResponse(
_options.Enabled,
_options.DisplayName,
EffectiveCallbackUrl());
[AllowAnonymous]
[EnableRateLimiting("public-auth")]
[HttpGet("login")]
public async Task<IActionResult> Login(
[FromQuery] string? returnUrl = null,
[FromQuery] string? bindingIntent = null,
CancellationToken cancellationToken = default)
{
if (!_options.Enabled)
return SsoProblem("统一身份认证尚未启用。", StatusCodes.Status404NotFound);
var safeReturnUrl = NormalizeReturnUrl(returnUrl);
var properties = new AuthenticationProperties();
if (!string.IsNullOrWhiteSpace(bindingIntent))
{
var targetUserId = await cache.GetStringAsync(
BindingIntentCacheKey(bindingIntent),
cancellationToken);
if (targetUserId is null)
return RedirectToFrontendError("binding_intent_expired", "/account");
properties.Items[BindingIntentProperty] = bindingIntent;
}
var completeUrl = Url.Action(
nameof(Complete),
values: new { returnUrl = safeReturnUrl })!;
properties.RedirectUri = completeUrl;
try
{
await HttpContext.ChallengeAsync(SsoAuthSchemes.Keycloak, properties);
return new EmptyResult();
}
catch (OpenIdConnectProtocolException exception)
{
logger.LogWarning(
exception,
"Keycloak 拒绝了 OIDC 授权请求。当前回调地址为 {CallbackUrl}",
EffectiveCallbackUrl());
return RedirectToFrontendError(
"configuration_error",
string.IsNullOrWhiteSpace(bindingIntent) ? "/login" : "/account");
}
}
[AllowAnonymous]
[ApiExplorerSettings(IgnoreApi = true)]
[HttpGet("complete")]
public async Task<ActionResult> Complete(
[FromQuery] string? returnUrl,
CancellationToken cancellationToken)
{
if (!_options.Enabled)
return SsoProblem("统一身份认证尚未启用。", StatusCodes.Status404NotFound);
var authentication = await HttpContext.AuthenticateAsync(
SsoAuthSchemes.ExternalCookie);
if (!authentication.Succeeded || authentication.Principal is null)
return RedirectToFrontendError("authentication_failed");
var principal = authentication.Principal;
var subject = principal.FindFirstValue("sub") ??
principal.FindFirstValue(ClaimTypes.NameIdentifier);
if (string.IsNullOrWhiteSpace(subject))
return RedirectToFrontendError("missing_subject");
ApplicationUser? user = null;
var bindingIntent =
authentication.Properties is { } authenticationProperties &&
authenticationProperties.Items.TryGetValue(
BindingIntentProperty,
out var storedBindingIntent)
? storedBindingIntent
: null;
if (!string.IsNullOrWhiteSpace(bindingIntent))
{
var targetUserId = await cache.GetStringAsync(
BindingIntentCacheKey(bindingIntent),
cancellationToken);
user = targetUserId is null
? null
: await userManager.FindByIdAsync(targetUserId);
if (user is null)
return RedirectToFrontendError("binding_intent_expired", "/account");
if (!user.IsEnabled || await userManager.IsLockedOutAsync(user))
return RedirectToFrontendError("account_disabled", "/account");
var linkError = await LinkSsoIdentityAsync(user, subject);
if (linkError is not null)
return RedirectToFrontendError(linkError, "/account");
await cache.RemoveAsync(
BindingIntentCacheKey(bindingIntent),
cancellationToken);
}
user ??= await userManager.FindByLoginAsync(
SsoAuthSchemes.LoginProvider,
subject);
if (user is null && _options.LinkExistingUsersByUserName)
{
var userName = principal.FindFirstValue(_options.UserNameClaim)?.Trim();
if (!string.IsNullOrWhiteSpace(userName))
{
user = await userManager.FindByNameAsync(userName);
if (user is not null)
{
var linkError = await LinkSsoIdentityAsync(user, subject);
if (linkError is not null)
return RedirectToFrontendError(linkError);
}
}
}
if (user is null)
{
var bindingCode = WebEncoders.Base64UrlEncode(
RandomNumberGenerator.GetBytes(32));
var externalUserName =
principal.FindFirstValue(_options.UserNameClaim)?.Trim() ??
principal.FindFirstValue("name")?.Trim() ??
subject;
await cache.SetStringAsync(
BindingCacheKey(bindingCode),
JsonSerializer.Serialize(new SsoBindingTicket(subject, externalUserName)),
new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
},
cancellationToken);
await HttpContext.SignOutAsync(SsoAuthSchemes.ExternalCookie);
var bindingPage = BuildFrontendUrl("/sso/bind") +
$"?code={Uri.EscapeDataString(bindingCode)}" +
$"&redirect={Uri.EscapeDataString(NormalizeReturnUrl(returnUrl))}";
return Redirect(bindingPage);
}
if (!user.IsEnabled || await userManager.IsLockedOutAsync(user))
return RedirectToFrontendError("account_disabled");
user.LastLoginAt = DateTime.UtcNow;
var updateResult = await userManager.UpdateAsync(user);
if (!updateResult.Succeeded)
return RedirectToFrontendError("account_update_failed");
var exchangeCode = WebEncoders.Base64UrlEncode(
RandomNumberGenerator.GetBytes(32));
await cache.SetStringAsync(
ExchangeCacheKey(exchangeCode),
user.Id.ToString("D"),
new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(2)
},
cancellationToken);
await HttpContext.SignOutAsync(SsoAuthSchemes.ExternalCookie);
var callback = BuildFrontendUrl("/sso/callback") +
$"?code={Uri.EscapeDataString(exchangeCode)}" +
$"&redirect={Uri.EscapeDataString(NormalizeReturnUrl(returnUrl))}";
return Redirect(callback);
}
[AllowAnonymous]
[EnableRateLimiting("public-auth")]
[HttpPost("exchange")]
public async Task<ActionResult<LoginResponse>> Exchange(
SsoExchangeRequest request,
CancellationToken cancellationToken)
{
if (!_options.Enabled)
return SsoProblem("统一身份认证尚未启用。", StatusCodes.Status404NotFound);
var cacheKey = ExchangeCacheKey(request.Code);
var userId = await cache.GetStringAsync(cacheKey, cancellationToken);
if (userId is null)
return SsoProblem(
"统一身份认证结果已失效,请重新登录。",
StatusCodes.Status401Unauthorized);
await cache.RemoveAsync(cacheKey, cancellationToken);
var user = await userManager.FindByIdAsync(userId);
if (user is null || !user.IsEnabled || await userManager.IsLockedOutAsync(user))
return SsoProblem(
"本地账号不存在、已停用或已锁定。",
StatusCodes.Status401Unauthorized);
var roles = await userManager.GetRolesAsync(user);
var session = await authSessionService.CreateAsync(
user,
roles,
request.IsNativeApp
? AuthenticationClientType.App
: AuthenticationClientType.Web,
cancellationToken);
return AuthController.CreateLoginResponse(session);
}
[AllowAnonymous]
[EnableRateLimiting("public-auth")]
[HttpGet("binding")]
public async Task<ActionResult<SsoBindingInfoResponse>> BindingInfo(
[FromQuery, Required, MinLength(20), MaxLength(200)] string code,
CancellationToken cancellationToken)
{
if (!_options.Enabled)
return SsoProblem("统一身份认证尚未启用。", StatusCodes.Status404NotFound);
var ticket = await ReadBindingTicketAsync(code, cancellationToken);
if (ticket is null)
return SsoProblem(
"账户绑定请求已失效,请重新使用统一身份认证登录。",
StatusCodes.Status401Unauthorized);
return new SsoBindingInfoResponse(_options.DisplayName, ticket.ExternalUserName);
}
[AllowAnonymous]
[EnableRateLimiting("public-auth")]
[HttpPost("bind")]
public async Task<ActionResult<LoginResponse>> Bind(
SsoBindRequest request,
CancellationToken cancellationToken)
{
if (!_options.Enabled)
return SsoProblem("统一身份认证尚未启用。", StatusCodes.Status404NotFound);
var ticket = await ReadBindingTicketAsync(request.Code, cancellationToken);
if (ticket is null)
return SsoProblem(
"账户绑定请求已失效,请重新使用统一身份认证登录。",
StatusCodes.Status401Unauthorized);
var user = await userManager.FindByNameAsync(request.UserName.Trim());
if (user is null || !user.IsEnabled || await userManager.IsLockedOutAsync(user))
return InvalidLocalCredentials();
if (!await userManager.CheckPasswordAsync(user, request.Password))
{
await userManager.AccessFailedAsync(user);
return InvalidLocalCredentials();
}
var subjectOwner = await userManager.FindByLoginAsync(
SsoAuthSchemes.LoginProvider,
ticket.Subject);
if (subjectOwner is not null && subjectOwner.Id != user.Id)
return BindingConflict("该统一身份账号已绑定其他教务系统账号。");
var keycloakLogins = (await userManager.GetLoginsAsync(user))
.Where(x => x.LoginProvider == SsoAuthSchemes.LoginProvider)
.ToList();
if (keycloakLogins.Any(x => x.ProviderKey != ticket.Subject))
return BindingConflict("该教务系统账号已绑定其他统一身份账号。");
if (subjectOwner is null)
{
var linkResult = await userManager.AddLoginAsync(
user,
new UserLoginInfo(
SsoAuthSchemes.LoginProvider,
ticket.Subject,
_options.DisplayName));
if (!linkResult.Succeeded)
{
subjectOwner = await userManager.FindByLoginAsync(
SsoAuthSchemes.LoginProvider,
ticket.Subject);
if (subjectOwner?.Id != user.Id)
return BindingConflict("账户绑定失败,请重新发起统一身份认证。");
}
}
await userManager.ResetAccessFailedCountAsync(user);
user.LastLoginAt = DateTime.UtcNow;
var updateResult = await userManager.UpdateAsync(user);
if (!updateResult.Succeeded)
return SsoProblem("本地账号状态更新失败,请稍后重试。", StatusCodes.Status500InternalServerError);
await cache.RemoveAsync(BindingCacheKey(request.Code), cancellationToken);
var roles = await userManager.GetRolesAsync(user);
var session = await authSessionService.CreateAsync(
user,
roles,
request.IsNativeApp
? AuthenticationClientType.App
: AuthenticationClientType.Web,
cancellationToken);
return AuthController.CreateLoginResponse(session);
}
[Authorize]
[HttpGet("account")]
public async Task<ActionResult<SsoAccountResponse>> Account()
{
var user = await CurrentUserAsync();
if (user is null)
return Unauthorized();
var login = (await userManager.GetLoginsAsync(user))
.SingleOrDefault(x => x.LoginProvider == SsoAuthSchemes.LoginProvider);
return new SsoAccountResponse(
_options.Enabled,
_options.DisplayName,
login is not null,
EffectiveCallbackUrl());
}
[Authorize]
[HttpPost("prepare-binding")]
public async Task<ActionResult<SsoBindingStartResponse>> PrepareBinding(
CancellationToken cancellationToken)
{
if (!_options.Enabled)
return SsoProblem("统一身份认证尚未启用。", StatusCodes.Status404NotFound);
var user = await CurrentUserAsync();
if (user is null || !user.IsEnabled || await userManager.IsLockedOutAsync(user))
return Unauthorized();
if ((await userManager.GetLoginsAsync(user))
.Any(x => x.LoginProvider == SsoAuthSchemes.LoginProvider))
{
return BindingConflict("当前账号已绑定统一身份账号,请先解绑后再更换绑定。");
}
var intentCode = WebEncoders.Base64UrlEncode(
RandomNumberGenerator.GetBytes(32));
await cache.SetStringAsync(
BindingIntentCacheKey(intentCode),
user.Id.ToString("D"),
new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
},
cancellationToken);
var loginUrl = Url.Action(
nameof(Login),
values: new
{
returnUrl = "/account",
bindingIntent = intentCode
})!;
return new SsoBindingStartResponse(loginUrl);
}
[Authorize]
[EnableRateLimiting("public-auth")]
[HttpPost("unbind")]
public async Task<IActionResult> Unbind(SsoUnbindRequest request)
{
var user = await CurrentUserAsync();
if (user is null || !user.IsEnabled || await userManager.IsLockedOutAsync(user))
return Unauthorized();
if (!await userManager.HasPasswordAsync(user))
return BindingConflict("当前账号没有本地密码,不能自行解绑,请联系管理员处理。");
if (!await userManager.CheckPasswordAsync(user, request.Password))
{
await userManager.AccessFailedAsync(user);
return InvalidLocalCredentials();
}
var login = (await userManager.GetLoginsAsync(user))
.SingleOrDefault(x => x.LoginProvider == SsoAuthSchemes.LoginProvider);
if (login is null)
return NoContent();
var result = await userManager.RemoveLoginAsync(
user,
login.LoginProvider,
login.ProviderKey);
if (!result.Succeeded)
return SsoProblem("解除统一身份绑定失败,请稍后重试。", StatusCodes.Status500InternalServerError);
await userManager.ResetAccessFailedCountAsync(user);
return NoContent();
}
internal static string NormalizeReturnUrl(string? returnUrl) =>
!string.IsNullOrWhiteSpace(returnUrl) &&
returnUrl.StartsWith('/') &&
!returnUrl.StartsWith("//", StringComparison.Ordinal)
? returnUrl
: "/dashboard";
private string BuildFrontendUrl(string path) =>
string.IsNullOrWhiteSpace(_options.FrontendBaseUrl)
? path
: _options.FrontendBaseUrl.TrimEnd('/') + path;
private RedirectResult RedirectToFrontendError(
string error,
string path = "/login") =>
Redirect(BuildFrontendUrl(path) +
$"?ssoError={Uri.EscapeDataString(error)}");
private static string ExchangeCacheKey(string code) => $"sso:exchange:{code}";
private static string BindingCacheKey(string code) => $"sso:binding:{code}";
private static string BindingIntentCacheKey(string code) =>
$"sso:binding-intent:{code}";
private async Task<ApplicationUser?> CurrentUserAsync()
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
return userId is null ? null : await userManager.FindByIdAsync(userId);
}
private async Task<string?> LinkSsoIdentityAsync(
ApplicationUser user,
string subject)
{
var subjectOwner = await userManager.FindByLoginAsync(
SsoAuthSchemes.LoginProvider,
subject);
if (subjectOwner is not null)
return subjectOwner.Id == user.Id ? null : "identity_already_bound";
if ((await userManager.GetLoginsAsync(user)).Any(x =>
x.LoginProvider == SsoAuthSchemes.LoginProvider &&
x.ProviderKey != subject))
{
return "account_already_bound";
}
var result = await userManager.AddLoginAsync(
user,
new UserLoginInfo(
SsoAuthSchemes.LoginProvider,
subject,
_options.DisplayName));
if (result.Succeeded)
return null;
subjectOwner = await userManager.FindByLoginAsync(
SsoAuthSchemes.LoginProvider,
subject);
return subjectOwner?.Id == user.Id ? null : "account_link_failed";
}
private string EffectiveCallbackUrl()
{
if (!string.IsNullOrWhiteSpace(_options.CallbackUrl))
return _options.CallbackUrl;
return $"{Request.Scheme}://{Request.Host}{Request.PathBase}/signin-keycloak";
}
private async Task<SsoBindingTicket?> ReadBindingTicketAsync(
string code,
CancellationToken cancellationToken)
{
var json = await cache.GetStringAsync(BindingCacheKey(code), cancellationToken);
if (json is null)
return null;
try
{
return JsonSerializer.Deserialize<SsoBindingTicket>(json);
}
catch (JsonException)
{
return null;
}
}
private UnauthorizedObjectResult InvalidLocalCredentials() =>
Unauthorized(new ProblemDetails
{
Title = "账户绑定失败",
Detail = "教务系统账号或密码不正确,或账号已停用。",
Status = StatusCodes.Status401Unauthorized
});
private ObjectResult BindingConflict(string detail) =>
SsoProblem(detail, StatusCodes.Status409Conflict);
private ObjectResult SsoProblem(string detail, int status) =>
StatusCode(status, new ProblemDetails
{
Title = "统一身份认证失败",
Detail = detail,
Status = status
});
}
public sealed record SsoSettingsResponse(
bool Enabled,
string DisplayName,
string CallbackUrl);
public sealed record SsoExchangeRequest(
[Required, MinLength(20), MaxLength(200)] string Code,
bool IsNativeApp = false);
public sealed record SsoBindingInfoResponse(
string ProviderDisplayName,
string ExternalUserName);
public sealed record SsoBindRequest(
[Required, MinLength(20), MaxLength(200)] string Code,
[Required, MaxLength(100)] string UserName,
[Required, MaxLength(100)] string Password,
bool IsNativeApp = false);
internal sealed record SsoBindingTicket(string Subject, string ExternalUserName);
public sealed record SsoAccountResponse(
bool Enabled,
string ProviderDisplayName,
bool IsBound,
string CallbackUrl);
public sealed record SsoBindingStartResponse(string LoginUrl);
public sealed record SsoUnbindRequest(
[Required, MaxLength(100)] string Password);
@@ -0,0 +1,158 @@
using System.ComponentModel.DataAnnotations;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Caching;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Jiaowu.Api.Controllers;
[ApiController]
[Authorize(Roles = SystemRoles.Student)]
[Route("api/student/profile")]
public sealed class StudentProfileController(
AppDbContext db,
ICurrentUserDataScope currentUserDataScope,
IAppCache cache) : ControllerBase
{
[HttpGet]
public async Task<ActionResult<StudentProfileDto>> Get(
CancellationToken cancellationToken)
{
var userId = currentUserDataScope.Current.UserId;
var profile = await db.Students.AsNoTracking()
.Where(x => x.UserId == userId)
.Select(x => new StudentProfileDto(
x.StudentNumber,
x.Name,
x.AdministrativeClass!.Name,
x.AdministrativeClass.Major!.Name,
x.AdministrativeClass.Major.College!.Name,
x.EnrollmentYear,
x.EnrollmentDate,
x.Status,
x.Gender,
x.DateOfBirth,
x.EnglishName,
x.IdCardNumber,
x.Nationality,
x.Ethnicity,
x.PoliticalStatus,
x.NativePlace,
x.HouseholdAddress,
x.CurrentAddress,
x.PostalCode,
x.Phone,
x.Email,
x.Qq,
x.WeChat,
x.EmergencyContactName,
x.EmergencyContactRelationship,
x.EmergencyContactPhone,
x.SpecialTags,
x.SpecialNeeds,
x.Biography))
.SingleOrDefaultAsync(cancellationToken);
return profile is null ? NotFound() : Ok(profile);
}
[HttpPut]
public async Task<IActionResult> Update(
StudentProfileUpdateRequest request,
CancellationToken cancellationToken)
{
var userId = currentUserDataScope.Current.UserId;
var student = await db.Students.SingleOrDefaultAsync(
x => x.UserId == userId,
cancellationToken);
if (student is null) return NotFound();
student.Gender = request.Gender;
student.DateOfBirth = request.DateOfBirth;
student.EnglishName = Normalize(request.EnglishName);
student.IdCardNumber = Normalize(request.IdCardNumber);
student.Nationality = Normalize(request.Nationality);
student.Ethnicity = Normalize(request.Ethnicity);
student.PoliticalStatus = Normalize(request.PoliticalStatus);
student.NativePlace = Normalize(request.NativePlace);
student.HouseholdAddress = Normalize(request.HouseholdAddress);
student.CurrentAddress = Normalize(request.CurrentAddress);
student.PostalCode = Normalize(request.PostalCode);
student.Phone = Normalize(request.Phone);
student.Email = Normalize(request.Email);
student.Qq = Normalize(request.Qq);
student.WeChat = Normalize(request.WeChat);
student.EmergencyContactName = Normalize(request.EmergencyContactName);
student.EmergencyContactRelationship = Normalize(
request.EmergencyContactRelationship);
student.EmergencyContactPhone = Normalize(request.EmergencyContactPhone);
student.SpecialTags = Normalize(request.SpecialTags);
student.SpecialNeeds = Normalize(request.SpecialNeeds);
student.Biography = Normalize(request.Biography);
await db.SaveChangesAsync(cancellationToken);
await cache.RemoveByTagAsync(AppCacheTags.Analytics, cancellationToken);
return NoContent();
}
private static string? Normalize(string? value) =>
string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
public sealed record StudentProfileDto(
string StudentNumber,
string Name,
string ClassName,
string MajorName,
string CollegeName,
int EnrollmentYear,
DateOnly EnrollmentDate,
StudentStatus Status,
Gender Gender,
DateOnly? DateOfBirth,
string? EnglishName,
string? IdCardNumber,
string? Nationality,
string? Ethnicity,
string? PoliticalStatus,
string? NativePlace,
string? HouseholdAddress,
string? CurrentAddress,
string? PostalCode,
string? Phone,
string? Email,
string? Qq,
string? WeChat,
string? EmergencyContactName,
string? EmergencyContactRelationship,
string? EmergencyContactPhone,
string? SpecialTags,
string? SpecialNeeds,
string? Biography);
public sealed record StudentProfileUpdateRequest(
Gender Gender,
DateOnly? DateOfBirth,
[MaxLength(100)] string? EnglishName,
[MaxLength(30)] string? IdCardNumber,
[MaxLength(50)] string? Nationality,
[MaxLength(50)] string? Ethnicity,
[MaxLength(50)] string? PoliticalStatus,
[MaxLength(100)] string? NativePlace,
[MaxLength(300)] string? HouseholdAddress,
[MaxLength(300)] string? CurrentAddress,
[MaxLength(20)] string? PostalCode,
[MaxLength(30)] string? Phone,
[EmailAddress, MaxLength(100)] string? Email,
[MaxLength(30)] string? Qq,
[MaxLength(60)] string? WeChat,
[MaxLength(50)] string? EmergencyContactName,
[MaxLength(30)] string? EmergencyContactRelationship,
[MaxLength(30)] string? EmergencyContactPhone,
[MaxLength(300)] string? SpecialTags,
[MaxLength(1000)] string? SpecialNeeds,
[MaxLength(1000)] string? Biography);
@@ -0,0 +1,28 @@
using System.Reflection;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Jiaowu.Api.Controllers;
[ApiController]
[Route("api/system")]
public sealed class SystemController : ControllerBase
{
[AllowAnonymous]
[HttpGet("version")]
[ProducesResponseType<SystemVersionResponse>(StatusCodes.Status200OK)]
public SystemVersionResponse GetVersion()
{
var assembly = typeof(SystemController).Assembly;
var informationalVersion = assembly
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?
.InformationalVersion;
var version = informationalVersion?.Split('+', 2)[0]
?? assembly.GetName().Version?.ToString(3)
?? "unknown";
return new SystemVersionResponse(version);
}
}
public sealed record SystemVersionResponse(string Version);
@@ -0,0 +1,44 @@
using Jiaowu.Api.Domain.Common;
namespace Jiaowu.Api.Domain.Academic;
public sealed class OtherExamBatch : EntityBase
{
public string? ExamCode { get; set; }
public required string Name { get; set; }
public string? Organizer { get; set; }
public DateOnly ExamDate { get; set; }
public OtherExamMetricKind MetricKind { get; set; }
public decimal? MaxScore { get; set; }
public string? LevelOptions { get; set; }
public OtherExamBatchStatus Status { get; set; } = OtherExamBatchStatus.Draft;
public int PublicationCount { get; set; }
public DateTime? PublishedAt { get; set; }
public ICollection<OtherExamResult> Results { get; set; } = [];
}
public sealed class OtherExamResult : EntityBase
{
public Guid OtherExamBatchId { get; set; }
public OtherExamBatch? OtherExamBatch { get; set; }
public Guid StudentId { get; set; }
public Student? Student { get; set; }
public int AttemptNumber { get; set; } = 1;
public decimal? Score { get; set; }
public string? Level { get; set; }
public bool? IsPassed { get; set; }
public string? Notes { get; set; }
}
public enum OtherExamMetricKind
{
PassFail = 1,
Level = 2,
Score = 3
}
public enum OtherExamBatchStatus
{
Draft = 1,
Published = 2
}
@@ -30,8 +30,25 @@ public sealed class Student : EntityBase
public DateOnly EnrollmentDate { get; set; }
public StudentStatus Status { get; set; } = StudentStatus.Active;
public DateOnly? DateOfBirth { get; set; }
public string? EnglishName { get; set; }
public string? IdCardNumber { get; set; }
public string? Nationality { get; set; }
public string? Ethnicity { get; set; }
public string? PoliticalStatus { get; set; }
public string? NativePlace { get; set; }
public string? HouseholdAddress { get; set; }
public string? CurrentAddress { get; set; }
public string? PostalCode { get; set; }
public string? Phone { get; set; }
public string? Email { get; set; }
public string? Qq { get; set; }
public string? WeChat { get; set; }
public string? EmergencyContactName { get; set; }
public string? EmergencyContactRelationship { get; set; }
public string? EmergencyContactPhone { get; set; }
public string? SpecialTags { get; set; }
public string? SpecialNeeds { get; set; }
public string? Biography { get; set; }
public string? Notes { get; set; }
public Guid? UserId { get; set; }
}
@@ -20,6 +20,7 @@ public sealed class ScheduleEntry : EntityBase
public SchedulePlan? SchedulePlan { get; set; }
public Guid TeachingTaskId { get; set; }
public TeachingTask? TeachingTask { get; set; }
public ScheduleEntryKind Kind { get; set; } = ScheduleEntryKind.Lecture;
public Guid? ClassroomId { get; set; }
public Classroom? Classroom { get; set; }
public int DayOfWeek { get; set; }
@@ -129,3 +130,9 @@ public enum WeekPattern
Odd = 2,
Even = 3
}
public enum ScheduleEntryKind
{
Lecture = 1,
Experiment = 2
}
@@ -0,0 +1,22 @@
namespace Jiaowu.Api.Domain.Identity;
public enum AuthenticationClientType
{
Web = 0,
App = 1
}
public sealed class RefreshSession
{
public Guid Id { get; set; } = Guid.NewGuid();
public Guid UserId { get; set; }
public ApplicationUser? User { get; set; }
public required string TokenHash { get; set; }
public AuthenticationClientType ClientType { get; set; }
public required string SecurityStamp { get; set; }
public DateTime ExpiresAt { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public DateTime LastRefreshedAt { get; set; } = DateTime.UtcNow;
public DateTime? RevokedAt { get; set; }
public Guid? ReplacedBySessionId { get; set; }
}
@@ -0,0 +1,180 @@
using System.Security.Cryptography;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
namespace Jiaowu.Api.Infrastructure.Auth;
public interface IAuthSessionService
{
Task<AuthSessionResult> CreateAsync(
ApplicationUser user,
IEnumerable<string> roles,
AuthenticationClientType clientType,
CancellationToken cancellationToken = default);
Task<AuthSessionResult?> RefreshAsync(
string refreshToken,
CancellationToken cancellationToken = default);
Task RevokeAsync(
string refreshToken,
CancellationToken cancellationToken = default);
}
public sealed record AuthSessionResult(
string AccessToken,
DateTime AccessTokenExpiresAt,
string RefreshToken,
DateTime SessionExpiresAt,
ApplicationUser User,
IReadOnlyList<string> Roles);
public sealed class AuthSessionService(
AppDbContext db,
UserManager<ApplicationUser> userManager,
ITokenService tokenService,
IOptions<JwtOptions> options) : IAuthSessionService
{
private readonly JwtOptions _options = options.Value;
public async Task<AuthSessionResult> CreateAsync(
ApplicationUser user,
IEnumerable<string> roles,
AuthenticationClientType clientType,
CancellationToken cancellationToken = default)
{
var roleList = roles.ToList();
var now = DateTime.UtcNow;
var rawRefreshToken = CreateRefreshToken();
var session = new RefreshSession
{
UserId = user.Id,
TokenHash = HashToken(rawRefreshToken),
ClientType = clientType,
SecurityStamp = user.SecurityStamp ?? string.Empty,
CreatedAt = now,
LastRefreshedAt = now,
ExpiresAt = now.Add(GetIdleTimeout(clientType))
};
await RemoveExpiredSessionsAsync(user.Id, now, cancellationToken);
db.RefreshSessions.Add(session);
await db.SaveChangesAsync(cancellationToken);
return BuildResult(user, roleList, rawRefreshToken, session.ExpiresAt);
}
public async Task<AuthSessionResult?> RefreshAsync(
string refreshToken,
CancellationToken cancellationToken = default)
{
var tokenHash = HashToken(refreshToken);
var now = DateTime.UtcNow;
var current = await db.RefreshSessions
.Include(x => x.User)
.SingleOrDefaultAsync(x => x.TokenHash == tokenHash, cancellationToken);
var user = current?.User;
if (current is null || user is null || current.RevokedAt.HasValue ||
current.ExpiresAt <= now || !user.IsEnabled ||
await userManager.IsLockedOutAsync(user) ||
!string.Equals(current.SecurityStamp, user.SecurityStamp ?? string.Empty,
StringComparison.Ordinal))
{
return null;
}
var newRawToken = CreateRefreshToken();
var replacement = new RefreshSession
{
UserId = user.Id,
TokenHash = HashToken(newRawToken),
ClientType = current.ClientType,
SecurityStamp = current.SecurityStamp,
CreatedAt = now,
LastRefreshedAt = now,
ExpiresAt = now.Add(GetIdleTimeout(current.ClientType))
};
var rotated = await db.ExecuteInRetriableTransactionAsync(
async transaction =>
{
db.ChangeTracker.Clear();
var updated = await db.RefreshSessions
.Where(x => x.Id == current.Id && x.RevokedAt == null && x.ExpiresAt > now)
.ExecuteUpdateAsync(setters => setters
.SetProperty(x => x.RevokedAt, now)
.SetProperty(x => x.ReplacedBySessionId, replacement.Id),
cancellationToken);
if (updated != 1)
{
await transaction.RollbackAsync(cancellationToken);
return false;
}
db.RefreshSessions.Add(replacement);
await db.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
return true;
},
cancellationToken);
if (!rotated) return null;
var roles = await userManager.GetRolesAsync(user);
return BuildResult(user, roles.ToList(), newRawToken, replacement.ExpiresAt);
}
public async Task RevokeAsync(
string refreshToken,
CancellationToken cancellationToken = default)
{
var tokenHash = HashToken(refreshToken);
var now = DateTime.UtcNow;
await db.RefreshSessions
.Where(x => x.TokenHash == tokenHash && x.RevokedAt == null)
.ExecuteUpdateAsync(
setters => setters.SetProperty(x => x.RevokedAt, now),
cancellationToken);
}
private AuthSessionResult BuildResult(
ApplicationUser user,
IReadOnlyList<string> roles,
string refreshToken,
DateTime sessionExpiresAt)
{
var accessToken = tokenService.Create(user, roles);
return new AuthSessionResult(
accessToken.Token,
accessToken.ExpiresAt,
refreshToken,
sessionExpiresAt,
user,
roles);
}
private TimeSpan GetIdleTimeout(AuthenticationClientType clientType) =>
TimeSpan.FromMinutes(clientType == AuthenticationClientType.App
? _options.AppIdleMinutes
: _options.WebIdleMinutes);
private async Task RemoveExpiredSessionsAsync(
Guid userId,
DateTime now,
CancellationToken cancellationToken)
{
var retentionCutoff = now.AddDays(-7);
await db.RefreshSessions
.Where(x => x.UserId == userId &&
(x.ExpiresAt < now || x.RevokedAt < retentionCutoff))
.ExecuteDeleteAsync(cancellationToken);
}
private static string CreateRefreshToken() =>
Convert.ToBase64String(RandomNumberGenerator.GetBytes(48));
private static string HashToken(string token) =>
Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(token)));
}
@@ -6,5 +6,7 @@ public sealed class JwtOptions
public string Issuer { get; set; } = "Jiaowu.Api";
public string Audience { get; set; } = "Jiaowu.Web";
public string Key { get; set; } = string.Empty;
public int ExpireMinutes { get; set; } = 480;
public int AccessTokenMinutes { get; set; } = 10;
public int WebIdleMinutes { get; set; } = 30;
public int AppIdleMinutes { get; set; } = 3 * 24 * 60;
}
@@ -0,0 +1,24 @@
namespace Jiaowu.Api.Infrastructure.Auth;
public sealed class SsoOptions
{
public const string SectionName = "Sso";
public bool Enabled { get; set; }
public string DisplayName { get; set; } = "学校统一身份认证";
public string Authority { get; set; } = string.Empty;
public string ClientId { get; set; } = string.Empty;
public string ClientSecret { get; set; } = string.Empty;
public string UserNameClaim { get; set; } = "preferred_username";
public bool RequireHttpsMetadata { get; set; } = true;
public bool LinkExistingUsersByUserName { get; set; } = true;
public string FrontendBaseUrl { get; set; } = string.Empty;
public string CallbackUrl { get; set; } = string.Empty;
}
public static class SsoAuthSchemes
{
public const string Keycloak = "Keycloak";
public const string ExternalCookie = "KeycloakExternal";
public const string LoginProvider = "Keycloak";
}
@@ -9,14 +9,16 @@ namespace Jiaowu.Api.Infrastructure.Auth;
public interface ITokenService
{
string Create(ApplicationUser user, IEnumerable<string> roles);
AccessTokenResult Create(ApplicationUser user, IEnumerable<string> roles);
}
public sealed record AccessTokenResult(string Token, DateTime ExpiresAt);
public sealed class TokenService(IOptions<JwtOptions> options) : ITokenService
{
private readonly JwtOptions _options = options.Value;
public string Create(ApplicationUser user, IEnumerable<string> roles)
public AccessTokenResult Create(ApplicationUser user, IEnumerable<string> roles)
{
var claims = new List<Claim>
{
@@ -37,13 +39,16 @@ public sealed class TokenService(IOptions<JwtOptions> options) : ITokenService
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.Key)),
SecurityAlgorithms.HmacSha256);
var expiresAt = DateTime.UtcNow.AddMinutes(_options.AccessTokenMinutes);
var token = new JwtSecurityToken(
issuer: _options.Issuer,
audience: _options.Audience,
claims: claims,
expires: DateTime.UtcNow.AddMinutes(_options.ExpireMinutes),
expires: expiresAt,
signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
return new AccessTokenResult(
new JwtSecurityTokenHandler().WriteToken(token),
expiresAt);
}
}
@@ -0,0 +1,281 @@
using System.Data.Common;
using System.Diagnostics;
using System.Diagnostics.Metrics;
using System.Security.Cryptography;
using System.Text;
using Microsoft.EntityFrameworkCore.Diagnostics;
namespace Jiaowu.Api.Infrastructure.Observability;
public sealed class DatabaseCommandTelemetryInterceptor(
ObservabilityOptions options,
ILogger<DatabaseCommandTelemetryInterceptor> logger)
: DbCommandInterceptor
{
public const string ActivitySourceName = "Jiaowu.Api.Database";
public const string MeterName = "Jiaowu.Api.Database";
private static readonly ActivitySource ActivitySource =
new(ActivitySourceName);
private static readonly Meter Meter = new(MeterName);
private static readonly Histogram<double> CommandDuration =
Meter.CreateHistogram<double>(
"jiaowu.db.command.duration",
"ms",
"EF Core database command duration");
private static readonly Counter<long> SlowCommandCount =
Meter.CreateCounter<long>(
"jiaowu.db.command.slow",
"{command}",
"EF Core commands exceeding the configured slow-query threshold");
private static readonly Counter<long> FailedCommandCount =
Meter.CreateCounter<long>(
"jiaowu.db.command.failed",
"{command}",
"Failed EF Core database commands");
public override DbDataReader ReaderExecuted(
DbCommand command,
CommandExecutedEventData eventData,
DbDataReader result)
{
Observe(command, eventData.Duration, "reader");
return result;
}
public override ValueTask<DbDataReader> ReaderExecutedAsync(
DbCommand command,
CommandExecutedEventData eventData,
DbDataReader result,
CancellationToken cancellationToken = default)
{
Observe(command, eventData.Duration, "reader");
return ValueTask.FromResult(result);
}
public override int NonQueryExecuted(
DbCommand command,
CommandExecutedEventData eventData,
int result)
{
Observe(command, eventData.Duration, "nonquery");
return result;
}
public override ValueTask<int> NonQueryExecutedAsync(
DbCommand command,
CommandExecutedEventData eventData,
int result,
CancellationToken cancellationToken = default)
{
Observe(command, eventData.Duration, "nonquery");
return ValueTask.FromResult(result);
}
public override object? ScalarExecuted(
DbCommand command,
CommandExecutedEventData eventData,
object? result)
{
Observe(command, eventData.Duration, "scalar");
return result;
}
public override ValueTask<object?> ScalarExecutedAsync(
DbCommand command,
CommandExecutedEventData eventData,
object? result,
CancellationToken cancellationToken = default)
{
Observe(command, eventData.Duration, "scalar");
return ValueTask.FromResult(result);
}
public override void CommandFailed(
DbCommand command,
CommandErrorEventData eventData) =>
Observe(
command,
eventData.Duration,
"failed",
eventData.Exception.GetType().Name);
public override Task CommandFailedAsync(
DbCommand command,
CommandErrorEventData eventData,
CancellationToken cancellationToken = default)
{
Observe(
command,
eventData.Duration,
"failed",
eventData.Exception.GetType().Name);
return Task.CompletedTask;
}
public override void CommandCanceled(
DbCommand command,
CommandEndEventData eventData) =>
Observe(command, eventData.Duration, "canceled", "canceled");
public override Task CommandCanceledAsync(
DbCommand command,
CommandEndEventData eventData,
CancellationToken cancellationToken = default)
{
Observe(command, eventData.Duration, "canceled", "canceled");
return Task.CompletedTask;
}
private void Observe(
DbCommand command,
TimeSpan duration,
string commandKind,
string? errorType = null)
{
if (!options.Enabled) return;
var queryName = GetQueryName(command.CommandText);
var statementHash = GetStatementHash(command.CommandText);
var provider = GetProviderName(command);
var traceId = Activity.Current?.TraceId.ToString() ?? "none";
var tags = new TagList
{
{ "db.system.name", provider },
{ "db.operation.name", commandKind },
{ "db.query.name", queryName }
};
if (errorType is not null)
tags.Add("error.type", errorType);
var durationMilliseconds = duration.TotalMilliseconds;
CommandDuration.Record(durationMilliseconds, tags);
if (errorType is not null)
FailedCommandCount.Add(1, tags);
using var activity = ActivitySource.StartActivity(
ActivityKind.Client,
Activity.Current?.Context ?? default,
startTime: DateTimeOffset.UtcNow - duration,
name: queryName);
if (activity is not null)
{
activity.SetTag("db.system.name", provider);
activity.SetTag("db.operation.name", commandKind);
activity.SetTag("db.query.name", queryName);
activity.SetTag("db.statement.hash", statementHash);
activity.SetTag(
"db.namespace",
EmptyToNull(command.Connection?.Database));
if (options.IncludeSqlText)
{
activity.SetTag(
"db.query.text",
Truncate(command.CommandText, options.MaximumSqlTextLength));
}
if (errorType is not null)
{
activity.SetTag("error.type", errorType);
activity.SetStatus(ActivityStatusCode.Error, errorType);
}
activity.SetEndTime(DateTime.UtcNow);
}
if (errorType is not null)
{
logger.LogError(
"Database command failed after {DurationMs:F1} ms: " +
"{QueryName} ({CommandKind}, {Provider}, hash {StatementHash}, " +
"error {ErrorType}, trace {TraceId}).",
durationMilliseconds,
queryName,
commandKind,
provider,
statementHash,
errorType,
traceId);
return;
}
if (durationMilliseconds < options.SlowQueryThresholdMilliseconds)
return;
SlowCommandCount.Add(1, tags);
if (options.IncludeSqlText)
{
logger.LogWarning(
"Slow database command took {DurationMs:F1} ms: " +
"{QueryName} ({CommandKind}, {Provider}, hash {StatementHash}, " +
"trace {TraceId}). " +
"SQL template: {SqlTemplate}",
durationMilliseconds,
queryName,
commandKind,
provider,
statementHash,
traceId,
Truncate(command.CommandText, options.MaximumSqlTextLength));
}
else
{
logger.LogWarning(
"Slow database command took {DurationMs:F1} ms: " +
"{QueryName} ({CommandKind}, {Provider}, hash {StatementHash}, " +
"trace {TraceId}).",
durationMilliseconds,
queryName,
commandKind,
provider,
statementHash,
traceId);
}
}
internal static string GetQueryName(string commandText)
{
using var reader = new StringReader(commandText);
while (reader.ReadLine() is { } line)
{
var trimmed = line.Trim();
if (trimmed.Length == 0) continue;
if (trimmed.StartsWith("-- ", StringComparison.Ordinal))
return Truncate(trimmed[3..].Trim(), 120);
return $"{FirstToken(trimmed)}:{GetStatementHash(commandText)}";
}
return $"unknown:{GetStatementHash(commandText)}";
}
internal static string GetStatementHash(string commandText)
{
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(commandText));
return Convert.ToHexString(bytes.AsSpan(0, 6)).ToLowerInvariant();
}
private static string FirstToken(string value)
{
var end = value.IndexOfAny([' ', '\t', '\r', '\n', '(']);
var token = end < 0 ? value : value[..end];
return token.Length == 0
? "command"
: token.ToLowerInvariant();
}
private static string GetProviderName(DbCommand command)
{
var typeName = command.GetType().FullName ?? command.GetType().Name;
if (typeName.Contains("MySql", StringComparison.OrdinalIgnoreCase))
return "mysql";
if (typeName.Contains("Sqlite", StringComparison.OrdinalIgnoreCase))
return "sqlite";
return "other_sql";
}
private static string? EmptyToNull(string? value) =>
string.IsNullOrWhiteSpace(value) ? null : value;
private static string Truncate(string value, int maximumLength) =>
value.Length <= maximumLength
? value
: value[..maximumLength];
}
@@ -0,0 +1,12 @@
namespace Jiaowu.Api.Infrastructure.Observability;
public sealed class ObservabilityOptions
{
public const string SectionName = "Observability";
public bool Enabled { get; set; } = true;
public string ServiceName { get; set; } = "jiaowu-api";
public int SlowQueryThresholdMilliseconds { get; set; } = 500;
public bool IncludeSqlText { get; set; }
public int MaximumSqlTextLength { get; set; } = 2000;
}
@@ -0,0 +1,556 @@
using System.Globalization;
using System.Net.Http.Headers;
using System.Text.Json;
using Microsoft.Extensions.Caching.Memory;
namespace Jiaowu.Api.Infrastructure.Observability;
public sealed class PerformanceReportService(
HttpClient httpClient,
IMemoryCache cache,
PerformanceReportingOptions options,
ObservabilityOptions observability,
ILogger<PerformanceReportService> logger)
{
public async Task<PerformanceReport> GetAsync(
string? range,
CancellationToken cancellationToken)
{
var rangeSpec = PerformanceRange.TryParse(range);
if (rangeSpec is null)
throw new ArgumentOutOfRangeException(
nameof(range),
"性能报表范围仅支持 15m、1h、24h 或 7d。");
if (!options.Enabled ||
string.IsNullOrWhiteSpace(options.PrometheusBaseUrl))
{
return PerformanceReport.NotConfigured(
rangeSpec.Key,
options.GrafanaBaseUrl);
}
var cacheKey = $"performance-report:{rangeSpec.Key}";
if (cache.TryGetValue<PerformanceReport>(cacheKey, out var cached))
return cached!;
PerformanceReport report;
try
{
report = await LoadAsync(rangeSpec, cancellationToken);
}
catch (Exception exception) when (
!cancellationToken.IsCancellationRequested)
{
logger.LogWarning(
exception,
"Performance report source is unavailable for range {Range}.",
rangeSpec.Key);
report = PerformanceReport.Unavailable(
rangeSpec.Key,
options.GrafanaBaseUrl);
}
cache.Set(
cacheKey,
report,
TimeSpan.FromSeconds(options.CacheSeconds));
return report;
}
private async Task<PerformanceReport> LoadAsync(
PerformanceRange range,
CancellationToken cancellationToken)
{
var now = DateTime.UtcNow;
var from = now - range.Duration;
var requestCountSelector = Selector(
options.RequestDurationMetric + "_count",
(options.ServiceLabel, "=", observability.ServiceName));
var requestBucketSelector = Selector(
options.RequestDurationMetric + "_bucket",
(options.ServiceLabel, "=", observability.ServiceName));
var errorCountSelector = Selector(
options.RequestDurationMetric + "_count",
(options.ServiceLabel, "=", observability.ServiceName),
("http_response_status_code", "=~", "5.."));
var databaseCountSelector = Selector(
options.DatabaseDurationMetric + "_count",
(options.ServiceLabel, "=", observability.ServiceName));
var databaseBucketSelector = Selector(
options.DatabaseDurationMetric + "_bucket",
(options.ServiceLabel, "=", observability.ServiceName));
var slowDatabaseSelector = Selector(
options.SlowDatabaseMetric,
(options.ServiceLabel, "=", observability.ServiceName));
var failedDatabaseSelector = Selector(
options.FailedDatabaseMetric,
(options.ServiceLabel, "=", observability.ServiceName));
var requestCountTask = QueryScalarAsync(
$"sum(increase({requestCountSelector}[{range.PrometheusRange}]))",
now,
cancellationToken);
var serverErrorCountTask = QueryScalarAsync(
$"sum(increase({errorCountSelector}[{range.PrometheusRange}]))",
now,
cancellationToken);
var requestP95Task = QueryScalarAsync(
"histogram_quantile(0.95, " +
$"sum by (le) (rate({requestBucketSelector}[{range.RateWindow}]))) " +
"* 1000",
now,
cancellationToken);
var databaseP95Task = QueryScalarAsync(
"histogram_quantile(0.95, " +
$"sum by (le) (rate({databaseBucketSelector}[{range.RateWindow}])))",
now,
cancellationToken);
var slowCountTask = QueryScalarAsync(
$"sum(increase({slowDatabaseSelector}[{range.PrometheusRange}]))",
now,
cancellationToken);
var failedCountTask = QueryScalarAsync(
$"sum(increase({failedDatabaseSelector}[{range.PrometheusRange}]))",
now,
cancellationToken);
var requestTimelineTask = QueryRangeAsync(
$"sum(rate({requestCountSelector}[{range.RateWindow}]))",
from,
now,
range.StepSeconds,
cancellationToken);
var latencyTimelineTask = QueryRangeAsync(
"histogram_quantile(0.95, " +
$"sum by (le) (rate({requestBucketSelector}[{range.RateWindow}]))) " +
"* 1000",
from,
now,
range.StepSeconds,
cancellationToken);
var routeLatencyTask = QueryVectorAsync(
"histogram_quantile(0.95, " +
$"sum by (le, http_route) (rate({requestBucketSelector}" +
$"[{range.RateWindow}]))) * 1000",
now,
cancellationToken);
var routeCountTask = QueryVectorAsync(
$"sum by (http_route) (increase({requestCountSelector}" +
$"[{range.PrometheusRange}]))",
now,
cancellationToken);
var routeErrorTask = QueryVectorAsync(
$"sum by (http_route) (increase({errorCountSelector}" +
$"[{range.PrometheusRange}]))",
now,
cancellationToken);
var queryLatencyTask = QueryVectorAsync(
"histogram_quantile(0.95, " +
$"sum by (le, db_query_name) (rate({databaseBucketSelector}" +
$"[{range.RateWindow}])))",
now,
cancellationToken);
var queryCountTask = QueryVectorAsync(
$"sum by (db_query_name) (increase({databaseCountSelector}" +
$"[{range.PrometheusRange}]))",
now,
cancellationToken);
var querySlowTask = QueryVectorAsync(
$"sum by (db_query_name) (increase({slowDatabaseSelector}" +
$"[{range.PrometheusRange}]))",
now,
cancellationToken);
await Task.WhenAll(
requestCountTask,
serverErrorCountTask,
requestP95Task,
databaseP95Task,
slowCountTask,
failedCountTask,
requestTimelineTask,
latencyTimelineTask,
routeLatencyTask,
routeCountTask,
routeErrorTask,
queryLatencyTask,
queryCountTask,
querySlowTask);
var requestCount = await requestCountTask;
var serverErrorCount = await serverErrorCountTask;
double? errorRate = requestCount is > 0 && serverErrorCount.HasValue
? serverErrorCount.Value / requestCount.Value * 100
: requestCount == 0
? 0
: null;
var timeline = MergeTimeline(
await requestTimelineTask,
await latencyTimelineTask);
var endpoints = MergeRanking(
await routeLatencyTask,
await routeCountTask,
await routeErrorTask,
"http_route");
var databaseQueries = MergeRanking(
await queryLatencyTask,
await queryCountTask,
await querySlowTask,
"db_query_name");
return new PerformanceReport(
"ready",
range.Key,
from,
now,
DateTime.UtcNow,
"prometheus",
EmptyToNull(options.GrafanaBaseUrl),
null,
new PerformanceHeadline(
Round(requestCount),
Round(await requestP95Task),
Round(errorRate),
Round(await databaseP95Task),
Round(await slowCountTask),
Round(await failedCountTask)),
timeline,
endpoints,
databaseQueries);
}
private async Task<double?> QueryScalarAsync(
string query,
DateTime time,
CancellationToken cancellationToken)
{
var vector = await QueryVectorAsync(
query,
time,
cancellationToken);
return vector.FirstOrDefault()?.Value;
}
private async Task<IReadOnlyList<PrometheusSample>> QueryVectorAsync(
string query,
DateTime time,
CancellationToken cancellationToken)
{
var uri = BuildUri(
"api/v1/query",
("query", query),
("time", ToUnixSeconds(time).ToString(
CultureInfo.InvariantCulture)));
using var document = await SendAsync(uri, cancellationToken);
var data = document.RootElement.GetProperty("data");
var result = data.GetProperty("result");
var samples = new List<PrometheusSample>();
foreach (var item in result.EnumerateArray())
{
var labels = ReadLabels(item.GetProperty("metric"));
if (!TryReadValue(item.GetProperty("value"), out var value))
continue;
samples.Add(new PrometheusSample(labels, value));
}
return samples;
}
private async Task<IReadOnlyList<PerformanceSeriesPoint>> QueryRangeAsync(
string query,
DateTime from,
DateTime to,
int stepSeconds,
CancellationToken cancellationToken)
{
var uri = BuildUri(
"api/v1/query_range",
("query", query),
("start", ToUnixSeconds(from).ToString(
CultureInfo.InvariantCulture)),
("end", ToUnixSeconds(to).ToString(
CultureInfo.InvariantCulture)),
("step", stepSeconds.ToString(CultureInfo.InvariantCulture)));
using var document = await SendAsync(uri, cancellationToken);
var result = document.RootElement
.GetProperty("data")
.GetProperty("result");
var first = result.EnumerateArray().FirstOrDefault();
if (first.ValueKind == JsonValueKind.Undefined ||
!first.TryGetProperty("values", out var values))
return [];
var points = new List<PerformanceSeriesPoint>();
foreach (var value in values.EnumerateArray())
{
if (!TryReadValue(value, out var measurement)) continue;
var timestamp = value[0].GetDouble();
points.Add(new PerformanceSeriesPoint(
DateTimeOffset.FromUnixTimeMilliseconds(
checked((long)(timestamp * 1000))).UtcDateTime,
measurement));
}
return points;
}
private async Task<JsonDocument> SendAsync(
Uri uri,
CancellationToken cancellationToken)
{
using var request = new HttpRequestMessage(HttpMethod.Get, uri);
if (!string.IsNullOrWhiteSpace(options.BearerToken))
{
request.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", options.BearerToken);
}
using var response = await httpClient.SendAsync(
request,
HttpCompletionOption.ResponseHeadersRead,
cancellationToken);
response.EnsureSuccessStatusCode();
await using var stream = await response.Content.ReadAsStreamAsync(
cancellationToken);
var document = await JsonDocument.ParseAsync(
stream,
cancellationToken: cancellationToken);
if (!document.RootElement.TryGetProperty("status", out var status) ||
status.GetString() != "success")
{
document.Dispose();
throw new InvalidOperationException(
"Prometheus 返回了非成功查询状态。");
}
return document;
}
private Uri BuildUri(
string relativePath,
params (string Key, string Value)[] parameters)
{
var baseUri = new Uri(
options.PrometheusBaseUrl.TrimEnd('/') + "/",
UriKind.Absolute);
var query = string.Join(
"&",
parameters.Select(parameter =>
$"{Uri.EscapeDataString(parameter.Key)}=" +
$"{Uri.EscapeDataString(parameter.Value)}"));
return new Uri(baseUri, $"{relativePath}?{query}");
}
private static string Selector(
string metric,
params (string Label, string Operator, string Value)[] filters)
{
var matchers = string.Join(
",",
filters.Select(filter =>
$"{filter.Label}{filter.Operator}\"" +
$"{EscapePrometheusValue(filter.Value)}\""));
return $"{metric}{{{matchers}}}";
}
private static string EscapePrometheusValue(string value) =>
value.Replace("\\", "\\\\", StringComparison.Ordinal)
.Replace("\"", "\\\"", StringComparison.Ordinal)
.Replace("\r", "\\r", StringComparison.Ordinal)
.Replace("\n", "\\n", StringComparison.Ordinal);
private static IReadOnlyDictionary<string, string> ReadLabels(
JsonElement metric)
{
var result = new Dictionary<string, string>(
StringComparer.Ordinal);
foreach (var property in metric.EnumerateObject())
result[property.Name] = property.Value.GetString() ?? "";
return result;
}
private static bool TryReadValue(
JsonElement value,
out double measurement)
{
measurement = 0;
if (value.ValueKind != JsonValueKind.Array ||
value.GetArrayLength() < 2)
return false;
var raw = value[1].GetString();
return double.TryParse(
raw,
NumberStyles.Float,
CultureInfo.InvariantCulture,
out measurement) &&
double.IsFinite(measurement);
}
private static IReadOnlyList<PerformanceTimelinePoint> MergeTimeline(
IReadOnlyList<PerformanceSeriesPoint> requestRate,
IReadOnlyList<PerformanceSeriesPoint> latency)
{
var points = new SortedDictionary<DateTime, PerformanceTimelinePoint>();
foreach (var point in requestRate)
{
points[point.Timestamp] = new PerformanceTimelinePoint(
point.Timestamp,
Math.Round(point.Value, 3),
null);
}
foreach (var point in latency)
{
points.TryGetValue(point.Timestamp, out var existing);
points[point.Timestamp] = new PerformanceTimelinePoint(
point.Timestamp,
existing?.RequestsPerSecond,
Math.Round(point.Value, 2));
}
return points.Values.ToArray();
}
private static IReadOnlyList<PerformanceRankingItem> MergeRanking(
IReadOnlyList<PrometheusSample> latency,
IReadOnlyList<PrometheusSample> count,
IReadOnlyList<PrometheusSample> exceptional,
string label)
{
var names = latency
.Concat(count)
.Concat(exceptional)
.Select(item => item.Labels.GetValueOrDefault(label))
.Where(name => !string.IsNullOrWhiteSpace(name))
.Distinct(StringComparer.Ordinal)
.ToArray();
var items = names.Select(name =>
{
var latencyValue = FindValue(latency, label, name);
var countValue = FindValue(count, label, name);
var exceptionalValue = FindValue(exceptional, label, name);
return new PerformanceRankingItem(
name!,
Round(latencyValue),
Round(countValue),
Round(exceptionalValue));
});
return items
.OrderByDescending(item => item.P95Milliseconds ?? -1)
.ThenByDescending(item => item.RequestCount ?? -1)
.Take(10)
.ToArray();
}
private static double? FindValue(
IReadOnlyList<PrometheusSample> samples,
string label,
string? name) =>
samples.FirstOrDefault(item =>
item.Labels.GetValueOrDefault(label) == name)?.Value;
private static double ToUnixSeconds(DateTime value) =>
new DateTimeOffset(
DateTime.SpecifyKind(value, DateTimeKind.Utc)).ToUnixTimeMilliseconds()
/ 1000d;
private static double? Round(double? value) =>
value.HasValue && double.IsFinite(value.Value)
? Math.Round(value.Value, 2)
: null;
private static string? EmptyToNull(string? value) =>
string.IsNullOrWhiteSpace(value) ? null : value;
private sealed record PrometheusSample(
IReadOnlyDictionary<string, string> Labels,
double Value);
private sealed record PerformanceSeriesPoint(
DateTime Timestamp,
double Value);
}
public sealed record PerformanceHeadline(
double? RequestCount,
double? RequestP95Milliseconds,
double? ServerErrorRatePercent,
double? DatabaseP95Milliseconds,
double? SlowDatabaseCommandCount,
double? FailedDatabaseCommandCount);
public sealed record PerformanceTimelinePoint(
DateTime Timestamp,
double? RequestsPerSecond,
double? RequestP95Milliseconds);
public sealed record PerformanceRankingItem(
string Name,
double? P95Milliseconds,
double? RequestCount,
double? ExceptionalCount);
public sealed record PerformanceReport(
string Status,
string Range,
DateTime? From,
DateTime? To,
DateTime GeneratedAt,
string DataSource,
string? DashboardUrl,
string? Detail,
PerformanceHeadline? Headline,
IReadOnlyList<PerformanceTimelinePoint> Timeline,
IReadOnlyList<PerformanceRankingItem> Endpoints,
IReadOnlyList<PerformanceRankingItem> DatabaseQueries)
{
public static PerformanceReport NotConfigured(
string range,
string? dashboardUrl) =>
Empty(
"not_configured",
range,
dashboardUrl,
"尚未配置 Prometheus 数据源。请先部署指标存储并设置 " +
"PerformanceReporting__PrometheusBaseUrl。");
public static PerformanceReport Unavailable(
string range,
string? dashboardUrl) =>
Empty(
"unavailable",
range,
dashboardUrl,
"性能数据源暂时不可用。系统业务不受影响,请检查 Prometheus 与网络配置。");
private static PerformanceReport Empty(
string status,
string range,
string? dashboardUrl,
string detail) =>
new(
status,
range,
null,
null,
DateTime.UtcNow,
"prometheus",
string.IsNullOrWhiteSpace(dashboardUrl) ? null : dashboardUrl,
detail,
null,
[],
[],
[]);
}
internal sealed record PerformanceRange(
string Key,
TimeSpan Duration,
string PrometheusRange,
string RateWindow,
int StepSeconds)
{
public static PerformanceRange? TryParse(string? value) =>
value?.Trim().ToLowerInvariant() switch
{
"15m" => new("15m", TimeSpan.FromMinutes(15), "15m", "1m", 30),
"1h" => new("1h", TimeSpan.FromHours(1), "1h", "5m", 60),
"24h" => new("24h", TimeSpan.FromHours(24), "24h", "15m", 900),
"7d" => new("7d", TimeSpan.FromDays(7), "7d", "1h", 3600),
_ => null
};
}
@@ -0,0 +1,31 @@
using System.Text.RegularExpressions;
namespace Jiaowu.Api.Infrastructure.Observability;
public sealed partial class PerformanceReportingOptions
{
public const string SectionName = "PerformanceReporting";
public bool Enabled { get; set; }
public string PrometheusBaseUrl { get; set; } = "";
public string BearerToken { get; set; } = "";
public string GrafanaBaseUrl { get; set; } = "";
public int CacheSeconds { get; set; } = 30;
public int TimeoutSeconds { get; set; } = 10;
public string ServiceLabel { get; set; } = "service_name";
public string RequestDurationMetric { get; set; } =
"http_server_request_duration_seconds";
public string DatabaseDurationMetric { get; set; } =
"jiaowu_db_command_duration_milliseconds";
public string SlowDatabaseMetric { get; set; } =
"jiaowu_db_command_slow_total";
public string FailedDatabaseMetric { get; set; } =
"jiaowu_db_command_failed_total";
public static bool IsMetricOrLabelName(string value) =>
!string.IsNullOrWhiteSpace(value) &&
PrometheusNamePattern().IsMatch(value);
[GeneratedRegex("^[a-zA-Z_:][a-zA-Z0-9_:]*$")]
private static partial Regex PrometheusNamePattern();
}
@@ -66,6 +66,8 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
public DbSet<GradeRecord> GradeRecords => Set<GradeRecord>();
public DbSet<GradeItem> GradeItems => Set<GradeItem>();
public DbSet<GradeItemScore> GradeItemScores => Set<GradeItemScore>();
public DbSet<OtherExamBatch> OtherExamBatches => Set<OtherExamBatch>();
public DbSet<OtherExamResult> OtherExamResults => Set<OtherExamResult>();
public DbSet<AttendanceSheet> AttendanceSheets => Set<AttendanceSheet>();
public DbSet<AttendanceRecord> AttendanceRecords => Set<AttendanceRecord>();
public DbSet<AttendanceCheckInAttempt> AttendanceCheckInAttempts =>
@@ -127,6 +129,7 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
Set<BackgroundJobOutboxMessage>();
public DbSet<AppUpdateRelease> AppUpdateReleases =>
Set<AppUpdateRelease>();
public DbSet<RefreshSession> RefreshSessions => Set<RefreshSession>();
protected override void ConfigureConventions(
ModelConfigurationBuilder configurationBuilder)
@@ -163,6 +166,21 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
entity.Property(x => x.Description).HasMaxLength(100);
});
builder.Entity<RefreshSession>(entity =>
{
entity.Property(x => x.TokenHash).HasMaxLength(64);
entity.Property(x => x.SecurityStamp).HasMaxLength(100);
entity.Property(x => x.ClientType)
.HasConversion<string>()
.HasMaxLength(20);
entity.HasIndex(x => x.TokenHash).IsUnique();
entity.HasIndex(x => new { x.UserId, x.ExpiresAt });
entity.HasOne(x => x.User)
.WithMany()
.HasForeignKey(x => x.UserId)
.OnDelete(DeleteBehavior.Cascade);
});
ConfigureCatalog<Campus>(builder);
ConfigureCatalog<College>(builder);
ConfigureCatalog<Major>(builder);
@@ -241,8 +259,25 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
{
entity.Property(x => x.StudentNumber).HasMaxLength(30);
entity.Property(x => x.Name).HasMaxLength(50);
entity.Property(x => x.EnglishName).HasMaxLength(100);
entity.Property(x => x.IdCardNumber).HasMaxLength(30);
entity.Property(x => x.Nationality).HasMaxLength(50);
entity.Property(x => x.Ethnicity).HasMaxLength(50);
entity.Property(x => x.PoliticalStatus).HasMaxLength(50);
entity.Property(x => x.NativePlace).HasMaxLength(100);
entity.Property(x => x.HouseholdAddress).HasMaxLength(300);
entity.Property(x => x.CurrentAddress).HasMaxLength(300);
entity.Property(x => x.PostalCode).HasMaxLength(20);
entity.Property(x => x.Phone).HasMaxLength(30);
entity.Property(x => x.Email).HasMaxLength(100);
entity.Property(x => x.Qq).HasMaxLength(30);
entity.Property(x => x.WeChat).HasMaxLength(60);
entity.Property(x => x.EmergencyContactName).HasMaxLength(50);
entity.Property(x => x.EmergencyContactRelationship).HasMaxLength(30);
entity.Property(x => x.EmergencyContactPhone).HasMaxLength(30);
entity.Property(x => x.SpecialTags).HasMaxLength(300);
entity.Property(x => x.SpecialNeeds).HasMaxLength(1000);
entity.Property(x => x.Biography).HasMaxLength(1000);
entity.Property(x => x.Notes).HasMaxLength(500);
entity.HasIndex(x => x.StudentNumber).IsUnique();
entity.HasIndex(x => new { x.AdministrativeClassId, x.Status });
@@ -416,6 +451,9 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
builder.Entity<ScheduleEntry>(entity =>
{
entity.Property(x => x.Kind)
.HasDefaultValue(ScheduleEntryKind.Lecture)
.HasSentinel((ScheduleEntryKind)0);
entity.Property(x => x.Notes).HasMaxLength(500);
entity.HasIndex(x => new
{
@@ -767,7 +805,8 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
entity.Property(x => x.Name).HasMaxLength(60);
entity.Property(x => x.Weight).HasPrecision(5, 1);
entity.Property(x => x.SourceType)
.HasDefaultValue(GradeItemSourceType.Manual);
.HasDefaultValue(GradeItemSourceType.Manual)
.HasSentinel((GradeItemSourceType)0);
entity.HasIndex(x => new { x.GradeSheetId, x.SortOrder });
entity.HasOne(x => x.GradeSheet)
.WithMany(x => x.Items)
@@ -1151,6 +1190,27 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
entity.HasOne(x => x.GradeRecord).WithMany()
.HasForeignKey(x => x.GradeRecordId).OnDelete(DeleteBehavior.Restrict);
});
builder.Entity<OtherExamBatch>(entity =>
{
entity.Property(x => x.ExamCode).HasMaxLength(60);
entity.Property(x => x.Name).HasMaxLength(150);
entity.Property(x => x.Organizer).HasMaxLength(150);
entity.Property(x => x.LevelOptions).HasMaxLength(500);
entity.Property(x => x.MaxScore).HasPrecision(8, 2);
entity.HasIndex(x => new { x.Status, x.ExamDate });
});
builder.Entity<OtherExamResult>(entity =>
{
entity.Property(x => x.Score).HasPrecision(8, 2);
entity.Property(x => x.Level).HasMaxLength(50);
entity.Property(x => x.Notes).HasMaxLength(500);
entity.HasIndex(x => new { x.OtherExamBatchId, x.StudentId, x.AttemptNumber }).IsUnique();
entity.HasIndex(x => new { x.StudentId, x.OtherExamBatchId });
entity.HasOne(x => x.OtherExamBatch).WithMany(x => x.Results)
.HasForeignKey(x => x.OtherExamBatchId).OnDelete(DeleteBehavior.Cascade);
entity.HasOne(x => x.Student).WithMany()
.HasForeignKey(x => x.StudentId).OnDelete(DeleteBehavior.Restrict);
});
builder.Entity<WarningRule>(entity =>
{
entity.Property(x => x.Name).HasMaxLength(100);
@@ -76,6 +76,14 @@ public sealed class DevelopmentSqliteMigrator(
"20260728_40_experiment_grade_management";
private const string AppUpdateReleasesMigration =
"20260729_41_app_update_releases";
private const string IntegratedExperimentSchedulingMigration =
"20260802_42_integrated_experiment_scheduling";
private const string RefreshSessionsMigration =
"20260803_43_refresh_sessions";
private const string StudentPersonalProfileMigration =
"20260803_44_student_personal_profile";
private const string OtherExamResultsMigration =
"20260808_45_other_exam_results";
public async Task MigrateAsync(CancellationToken cancellationToken = default)
{
@@ -577,6 +585,60 @@ public sealed class DevelopmentSqliteMigrator(
AppUpdateReleasesMigration,
AppUpdateReleasesStatements,
cancellationToken);
var scheduleEntryKindExists = await db.Database
.SqlQueryRaw<int>(
"""
SELECT COUNT(*) AS "Value"
FROM pragma_table_info('ScheduleEntries')
WHERE name = 'Kind'
""")
.AnyAsync(value => value > 0, cancellationToken);
await ApplyMigrationAsync(
IntegratedExperimentSchedulingMigration,
scheduleEntryKindExists
? []
: IntegratedExperimentSchedulingStatements,
cancellationToken);
await ApplyMigrationAsync(
RefreshSessionsMigration,
RefreshSessionsStatements,
cancellationToken);
var studentPersonalProfileExists = await db.Database
.SqlQueryRaw<int>(
"""
SELECT COUNT(*) AS "Value"
FROM pragma_table_info('Students')
WHERE name = 'SpecialTags'
""")
.AnyAsync(value => value > 0, cancellationToken);
await ApplyMigrationAsync(
StudentPersonalProfileMigration,
studentPersonalProfileExists ? [] : StudentPersonalProfileStatements,
cancellationToken);
var otherExamCodeExists = await db.Database
.SqlQueryRaw<int>(
"""
SELECT COUNT(*) AS "Value"
FROM pragma_table_info('OtherExamBatches')
WHERE name = 'ExamCode'
""")
.AnyAsync(value => value > 0, cancellationToken);
var otherExamBatchExists = await db.Database
.SqlQueryRaw<int>(
"""
SELECT COUNT(*) AS "Value"
FROM sqlite_master
WHERE type = 'table' AND name = 'OtherExamBatches'
""")
.AnyAsync(value => value > 0, cancellationToken);
await ApplyMigrationAsync(
OtherExamResultsMigration,
!otherExamBatchExists
? OtherExamResultsStatements.Skip(1)
: otherExamCodeExists
? OtherExamResultsStatements.Skip(1)
: OtherExamResultsStatements,
cancellationToken);
}
private async Task ApplyMigrationAsync(
@@ -2088,6 +2150,66 @@ public sealed class DevelopmentSqliteMigrator(
"""
];
private static readonly string[] RefreshSessionsStatements =
[
"""
CREATE TABLE IF NOT EXISTS "RefreshSessions" (
"Id" TEXT NOT NULL CONSTRAINT "PK_RefreshSessions" PRIMARY KEY,
"UserId" TEXT NOT NULL,
"TokenHash" TEXT NOT NULL,
"ClientType" TEXT NOT NULL,
"SecurityStamp" TEXT NOT NULL,
"ExpiresAt" TEXT NOT NULL,
"CreatedAt" TEXT NOT NULL,
"LastRefreshedAt" TEXT NOT NULL,
"RevokedAt" TEXT NULL,
"ReplacedBySessionId" TEXT NULL,
CONSTRAINT "FK_RefreshSessions_AspNetUsers_UserId"
FOREIGN KEY ("UserId") REFERENCES "AspNetUsers" ("Id") ON DELETE CASCADE
);
""",
"""
CREATE UNIQUE INDEX IF NOT EXISTS "IX_RefreshSessions_TokenHash"
ON "RefreshSessions" ("TokenHash");
""",
"""
CREATE INDEX IF NOT EXISTS "IX_RefreshSessions_UserId_ExpiresAt"
ON "RefreshSessions" ("UserId", "ExpiresAt");
"""
];
private static readonly string[] StudentPersonalProfileStatements =
[
"""ALTER TABLE "Students" ADD COLUMN "Biography" TEXT NULL;""",
"""ALTER TABLE "Students" ADD COLUMN "CurrentAddress" TEXT NULL;""",
"""ALTER TABLE "Students" ADD COLUMN "EmergencyContactName" TEXT NULL;""",
"""ALTER TABLE "Students" ADD COLUMN "EmergencyContactPhone" TEXT NULL;""",
"""ALTER TABLE "Students" ADD COLUMN "EmergencyContactRelationship" TEXT NULL;""",
"""ALTER TABLE "Students" ADD COLUMN "EnglishName" TEXT NULL;""",
"""ALTER TABLE "Students" ADD COLUMN "Ethnicity" TEXT NULL;""",
"""ALTER TABLE "Students" ADD COLUMN "HouseholdAddress" TEXT NULL;""",
"""ALTER TABLE "Students" ADD COLUMN "IdCardNumber" TEXT NULL;""",
"""ALTER TABLE "Students" ADD COLUMN "Nationality" TEXT NULL;""",
"""ALTER TABLE "Students" ADD COLUMN "NativePlace" TEXT NULL;""",
"""ALTER TABLE "Students" ADD COLUMN "PoliticalStatus" TEXT NULL;""",
"""ALTER TABLE "Students" ADD COLUMN "PostalCode" TEXT NULL;""",
"""ALTER TABLE "Students" ADD COLUMN "Qq" TEXT NULL;""",
"""ALTER TABLE "Students" ADD COLUMN "SpecialNeeds" TEXT NULL;""",
"""ALTER TABLE "Students" ADD COLUMN "SpecialTags" TEXT NULL;""",
"""ALTER TABLE "Students" ADD COLUMN "WeChat" TEXT NULL;"""
];
private static readonly string[] OtherExamResultsStatements =
[
"""ALTER TABLE "OtherExamBatches" ADD COLUMN "ExamCode" TEXT NULL;""",
"""CREATE TABLE IF NOT EXISTS "OtherExamBatches" ("Id" TEXT NOT NULL CONSTRAINT "PK_OtherExamBatches" PRIMARY KEY, "ExamCode" TEXT NULL, "Name" TEXT NOT NULL, "Organizer" TEXT NULL, "ExamDate" TEXT NOT NULL, "MetricKind" INTEGER NOT NULL, "MaxScore" TEXT NULL, "LevelOptions" TEXT NULL, "Status" INTEGER NOT NULL, "PublicationCount" INTEGER NOT NULL, "PublishedAt" TEXT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL);""",
"""CREATE INDEX IF NOT EXISTS "IX_OtherExamBatches_Status_ExamDate" ON "OtherExamBatches" ("Status", "ExamDate");""",
"""CREATE TABLE IF NOT EXISTS "OtherExamResults" ("Id" TEXT NOT NULL CONSTRAINT "PK_OtherExamResults" PRIMARY KEY, "OtherExamBatchId" TEXT NOT NULL, "StudentId" TEXT NOT NULL, "AttemptNumber" INTEGER NOT NULL, "Score" TEXT NULL, "Level" TEXT NULL, "IsPassed" INTEGER NULL, "Notes" TEXT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, CONSTRAINT "FK_OtherExamResults_OtherExamBatches" FOREIGN KEY ("OtherExamBatchId") REFERENCES "OtherExamBatches" ("Id") ON DELETE CASCADE, CONSTRAINT "FK_OtherExamResults_Students" FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id") ON DELETE RESTRICT);""",
"""DROP INDEX IF EXISTS "IX_OtherExamResults_OtherExamBatchId_StudentId_AttemptNumber";""",
"""CREATE UNIQUE INDEX IF NOT EXISTS "IX_OtherExamResults_OtherExamBatchId_StudentId" ON "OtherExamResults" ("OtherExamBatchId", "StudentId");""",
"""CREATE INDEX IF NOT EXISTS "IX_OtherExamResults_StudentId_OtherExamBatchId" ON "OtherExamResults" ("StudentId", "OtherExamBatchId");"""
];
private static readonly string[] ApprovalTableStatements =
[
"""CREATE TABLE "CourseExemptions" ("Id" TEXT NOT NULL CONSTRAINT "PK_CourseExemptions" PRIMARY KEY, "StudentId" TEXT NOT NULL, "TeachingTaskId" TEXT NOT NULL, "Reason" TEXT NOT NULL, "Status" INTEGER NOT NULL, "ReviewComment" TEXT NULL, "SubmittedAt" TEXT NOT NULL, "ReviewedAt" TEXT NULL, "ReviewedByUserId" TEXT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, CONSTRAINT "FK_CourseExemptions_Students" FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id") ON DELETE RESTRICT, CONSTRAINT "FK_CourseExemptions_TeachingTasks" FOREIGN KEY ("TeachingTaskId") REFERENCES "TeachingTasks" ("Id") ON DELETE RESTRICT);""",
@@ -2714,4 +2836,12 @@ public sealed class DevelopmentSqliteMigrator(
ON "ExperimentGradeItemScores" ("ExperimentGradeItemId");
"""
];
private static readonly string[] IntegratedExperimentSchedulingStatements =
[
"""
ALTER TABLE "ScheduleEntries"
ADD COLUMN "Kind" INTEGER NOT NULL DEFAULT 1;
"""
];
}
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
/// <inheritdoc />
public partial class IntegratedExperimentScheduling : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "Kind",
table: "ScheduleEntries",
type: "int",
nullable: false,
defaultValue: 1);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Kind",
table: "ScheduleEntries");
}
}
}
@@ -0,0 +1,60 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
/// <inheritdoc />
public partial class RefreshSessions : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "RefreshSessions",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
UserId = table.Column<Guid>(type: "char(36)", nullable: false),
TokenHash = table.Column<string>(type: "varchar(64)", maxLength: 64, nullable: false),
ClientType = table.Column<string>(type: "varchar(20)", maxLength: 20, nullable: false),
SecurityStamp = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
ExpiresAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
LastRefreshedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
RevokedAt = table.Column<DateTime>(type: "datetime(6)", nullable: true),
ReplacedBySessionId = table.Column<Guid>(type: "char(36)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_RefreshSessions", x => x.Id);
table.ForeignKey(
name: "FK_RefreshSessions_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_RefreshSessions_TokenHash",
table: "RefreshSessions",
column: "TokenHash",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_RefreshSessions_UserId_ExpiresAt",
table: "RefreshSessions",
columns: new[] { "UserId", "ExpiresAt" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "RefreshSessions");
}
}
}
@@ -0,0 +1,205 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
/// <inheritdoc />
public partial class StudentPersonalProfile : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Biography",
table: "Students",
type: "varchar(1000)",
maxLength: 1000,
nullable: true);
migrationBuilder.AddColumn<string>(
name: "CurrentAddress",
table: "Students",
type: "varchar(300)",
maxLength: 300,
nullable: true);
migrationBuilder.AddColumn<string>(
name: "EmergencyContactName",
table: "Students",
type: "varchar(50)",
maxLength: 50,
nullable: true);
migrationBuilder.AddColumn<string>(
name: "EmergencyContactPhone",
table: "Students",
type: "varchar(30)",
maxLength: 30,
nullable: true);
migrationBuilder.AddColumn<string>(
name: "EmergencyContactRelationship",
table: "Students",
type: "varchar(30)",
maxLength: 30,
nullable: true);
migrationBuilder.AddColumn<string>(
name: "EnglishName",
table: "Students",
type: "varchar(100)",
maxLength: 100,
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Ethnicity",
table: "Students",
type: "varchar(50)",
maxLength: 50,
nullable: true);
migrationBuilder.AddColumn<string>(
name: "HouseholdAddress",
table: "Students",
type: "varchar(300)",
maxLength: 300,
nullable: true);
migrationBuilder.AddColumn<string>(
name: "IdCardNumber",
table: "Students",
type: "varchar(30)",
maxLength: 30,
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Nationality",
table: "Students",
type: "varchar(50)",
maxLength: 50,
nullable: true);
migrationBuilder.AddColumn<string>(
name: "NativePlace",
table: "Students",
type: "varchar(100)",
maxLength: 100,
nullable: true);
migrationBuilder.AddColumn<string>(
name: "PoliticalStatus",
table: "Students",
type: "varchar(50)",
maxLength: 50,
nullable: true);
migrationBuilder.AddColumn<string>(
name: "PostalCode",
table: "Students",
type: "varchar(20)",
maxLength: 20,
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Qq",
table: "Students",
type: "varchar(30)",
maxLength: 30,
nullable: true);
migrationBuilder.AddColumn<string>(
name: "SpecialNeeds",
table: "Students",
type: "varchar(1000)",
maxLength: 1000,
nullable: true);
migrationBuilder.AddColumn<string>(
name: "SpecialTags",
table: "Students",
type: "varchar(300)",
maxLength: 300,
nullable: true);
migrationBuilder.AddColumn<string>(
name: "WeChat",
table: "Students",
type: "varchar(60)",
maxLength: 60,
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Biography",
table: "Students");
migrationBuilder.DropColumn(
name: "CurrentAddress",
table: "Students");
migrationBuilder.DropColumn(
name: "EmergencyContactName",
table: "Students");
migrationBuilder.DropColumn(
name: "EmergencyContactPhone",
table: "Students");
migrationBuilder.DropColumn(
name: "EmergencyContactRelationship",
table: "Students");
migrationBuilder.DropColumn(
name: "EnglishName",
table: "Students");
migrationBuilder.DropColumn(
name: "Ethnicity",
table: "Students");
migrationBuilder.DropColumn(
name: "HouseholdAddress",
table: "Students");
migrationBuilder.DropColumn(
name: "IdCardNumber",
table: "Students");
migrationBuilder.DropColumn(
name: "Nationality",
table: "Students");
migrationBuilder.DropColumn(
name: "NativePlace",
table: "Students");
migrationBuilder.DropColumn(
name: "PoliticalStatus",
table: "Students");
migrationBuilder.DropColumn(
name: "PostalCode",
table: "Students");
migrationBuilder.DropColumn(
name: "Qq",
table: "Students");
migrationBuilder.DropColumn(
name: "SpecialNeeds",
table: "Students");
migrationBuilder.DropColumn(
name: "SpecialTags",
table: "Students");
migrationBuilder.DropColumn(
name: "WeChat",
table: "Students");
}
}
}
@@ -0,0 +1,97 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
/// <inheritdoc />
public partial class OtherExamResults : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "OtherExamBatches",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
Name = table.Column<string>(type: "varchar(150)", maxLength: 150, nullable: false),
Organizer = table.Column<string>(type: "varchar(150)", maxLength: 150, nullable: true),
ExamDate = table.Column<DateTime>(type: "date", nullable: false),
MetricKind = table.Column<int>(type: "int", nullable: false),
MaxScore = table.Column<decimal>(type: "decimal(8,2)", precision: 8, scale: 2, nullable: true),
LevelOptions = table.Column<string>(type: "varchar(500)", maxLength: 500, nullable: true),
Status = table.Column<int>(type: "int", nullable: false),
PublicationCount = table.Column<int>(type: "int", nullable: false),
PublishedAt = table.Column<DateTime>(type: "datetime(6)", nullable: true),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_OtherExamBatches", x => x.Id);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "OtherExamResults",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
OtherExamBatchId = table.Column<Guid>(type: "char(36)", nullable: false),
StudentId = table.Column<Guid>(type: "char(36)", nullable: false),
AttemptNumber = table.Column<int>(type: "int", nullable: false),
Score = table.Column<decimal>(type: "decimal(8,2)", precision: 8, scale: 2, nullable: true),
Level = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: true),
IsPassed = table.Column<bool>(type: "tinyint(1)", nullable: true),
Notes = table.Column<string>(type: "varchar(500)", maxLength: 500, nullable: true),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_OtherExamResults", x => x.Id);
table.ForeignKey(
name: "FK_OtherExamResults_OtherExamBatches_OtherExamBatchId",
column: x => x.OtherExamBatchId,
principalTable: "OtherExamBatches",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_OtherExamResults_Students_StudentId",
column: x => x.StudentId,
principalTable: "Students",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_OtherExamBatches_Status_ExamDate",
table: "OtherExamBatches",
columns: new[] { "Status", "ExamDate" });
migrationBuilder.CreateIndex(
name: "IX_OtherExamResults_OtherExamBatchId_StudentId_AttemptNumber",
table: "OtherExamResults",
columns: new[] { "OtherExamBatchId", "StudentId", "AttemptNumber" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_OtherExamResults_StudentId_OtherExamBatchId",
table: "OtherExamResults",
columns: new[] { "StudentId", "OtherExamBatchId" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "OtherExamResults");
migrationBuilder.DropTable(
name: "OtherExamBatches");
}
}
}
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
/// <inheritdoc />
public partial class OtherExamIdentityAndImport : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "ExamCode",
table: "OtherExamBatches",
type: "varchar(60)",
maxLength: 60,
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "ExamCode",
table: "OtherExamBatches");
}
}
}
@@ -3278,6 +3278,107 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.ToTable("OfficialDocumentDownloads");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.OtherExamBatch", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("ExamCode")
.HasMaxLength(60)
.HasColumnType("varchar(60)");
b.Property<DateTime>("ExamDate")
.HasColumnType("date");
b.Property<string>("LevelOptions")
.HasMaxLength(500)
.HasColumnType("varchar(500)");
b.Property<decimal?>("MaxScore")
.HasPrecision(8, 2)
.HasColumnType("decimal(8,2)");
b.Property<int>("MetricKind")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(150)
.HasColumnType("varchar(150)");
b.Property<string>("Organizer")
.HasMaxLength(150)
.HasColumnType("varchar(150)");
b.Property<int>("PublicationCount")
.HasColumnType("int");
b.Property<DateTime?>("PublishedAt")
.HasColumnType("datetime(6)");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("Status", "ExamDate");
b.ToTable("OtherExamBatches");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.OtherExamResult", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<int>("AttemptNumber")
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<bool?>("IsPassed")
.HasColumnType("tinyint(1)");
b.Property<string>("Level")
.HasMaxLength(50)
.HasColumnType("varchar(50)");
b.Property<string>("Notes")
.HasMaxLength(500)
.HasColumnType("varchar(500)");
b.Property<Guid>("OtherExamBatchId")
.HasColumnType("char(36)");
b.Property<decimal?>("Score")
.HasPrecision(8, 2)
.HasColumnType("decimal(8,2)");
b.Property<Guid>("StudentId")
.HasColumnType("char(36)");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("StudentId", "OtherExamBatchId");
b.HasIndex("OtherExamBatchId", "StudentId", "AttemptNumber")
.IsUnique();
b.ToTable("OtherExamResults");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.ScheduleEntry", b =>
{
b.Property<Guid>("Id")
@@ -3296,6 +3397,11 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.Property<int>("EndWeek")
.HasColumnType("int");
b.Property<int>("Kind")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasDefaultValue(1);
b.Property<string>("Notes")
.HasMaxLength(500)
.HasColumnType("varchar(500)");
@@ -3487,9 +3593,17 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.Property<Guid>("AdministrativeClassId")
.HasColumnType("char(36)");
b.Property<string>("Biography")
.HasMaxLength(1000)
.HasColumnType("varchar(1000)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("CurrentAddress")
.HasMaxLength(300)
.HasColumnType("varchar(300)");
b.Property<DateTime?>("DateOfBirth")
.HasColumnType("date");
@@ -3497,20 +3611,56 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("EmergencyContactName")
.HasMaxLength(50)
.HasColumnType("varchar(50)");
b.Property<string>("EmergencyContactPhone")
.HasMaxLength(30)
.HasColumnType("varchar(30)");
b.Property<string>("EmergencyContactRelationship")
.HasMaxLength(30)
.HasColumnType("varchar(30)");
b.Property<string>("EnglishName")
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<DateTime>("EnrollmentDate")
.HasColumnType("date");
b.Property<int>("EnrollmentYear")
.HasColumnType("int");
b.Property<string>("Ethnicity")
.HasMaxLength(50)
.HasColumnType("varchar(50)");
b.Property<int>("Gender")
.HasColumnType("int");
b.Property<string>("HouseholdAddress")
.HasMaxLength(300)
.HasColumnType("varchar(300)");
b.Property<string>("IdCardNumber")
.HasMaxLength(30)
.HasColumnType("varchar(30)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("varchar(50)");
b.Property<string>("Nationality")
.HasMaxLength(50)
.HasColumnType("varchar(50)");
b.Property<string>("NativePlace")
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("Notes")
.HasMaxLength(500)
.HasColumnType("varchar(500)");
@@ -3519,6 +3669,26 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
.HasMaxLength(30)
.HasColumnType("varchar(30)");
b.Property<string>("PoliticalStatus")
.HasMaxLength(50)
.HasColumnType("varchar(50)");
b.Property<string>("PostalCode")
.HasMaxLength(20)
.HasColumnType("varchar(20)");
b.Property<string>("Qq")
.HasMaxLength(30)
.HasColumnType("varchar(30)");
b.Property<string>("SpecialNeeds")
.HasMaxLength(1000)
.HasColumnType("varchar(1000)");
b.Property<string>("SpecialTags")
.HasMaxLength(300)
.HasColumnType("varchar(300)");
b.Property<int>("Status")
.HasColumnType("int");
@@ -3533,6 +3703,10 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.Property<Guid?>("UserId")
.HasColumnType("char(36)");
b.Property<string>("WeChat")
.HasMaxLength(60)
.HasColumnType("varchar(60)");
b.HasKey("Id");
b.HasIndex("EnrollmentYear");
@@ -4129,6 +4303,55 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.ToTable("AspNetUsers", (string)null);
});
modelBuilder.Entity("Jiaowu.Api.Domain.Identity.RefreshSession", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("ClientType")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("varchar(20)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<DateTime>("ExpiresAt")
.HasColumnType("datetime(6)");
b.Property<DateTime>("LastRefreshedAt")
.HasColumnType("datetime(6)");
b.Property<Guid?>("ReplacedBySessionId")
.HasColumnType("char(36)");
b.Property<DateTime?>("RevokedAt")
.HasColumnType("datetime(6)");
b.Property<string>("SecurityStamp")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("TokenHash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<Guid>("UserId")
.HasColumnType("char(36)");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.HasIndex("UserId", "ExpiresAt");
b.ToTable("RefreshSessions");
});
modelBuilder.Entity("Jiaowu.Api.Domain.System.AppUpdateRelease", b =>
{
b.Property<Guid>("Id")
@@ -5476,6 +5699,25 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.Navigation("OfficialDocument");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.OtherExamResult", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.OtherExamBatch", "OtherExamBatch")
.WithMany("Results")
.HasForeignKey("OtherExamBatchId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Jiaowu.Api.Domain.Academic.Student", "Student")
.WithMany()
.HasForeignKey("StudentId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("OtherExamBatch");
b.Navigation("Student");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.ScheduleEntry", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.Classroom", "Classroom")
@@ -5738,6 +5980,17 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.Navigation("AcademicTerm");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Identity.RefreshSession", b =>
{
b.HasOne("Jiaowu.Api.Domain.Identity.ApplicationUser", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
{
b.HasOne("Jiaowu.Api.Domain.Identity.ApplicationRole", null)
@@ -5962,6 +6215,11 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.Navigation("Downloads");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.OtherExamBatch", b =>
{
b.Navigation("Results");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.SchedulePlan", b =>
{
b.Navigation("Entries");
@@ -74,97 +74,62 @@ public sealed class AutomaticScheduleGenerator(AppDbContext db)
{
cancellationToken.ThrowIfCancellationRequested();
constraints.TryGetValue(task.Id, out var constraint);
if (!TeachingTaskHours.TryResolveRegularWeeklyHours(
task.Course!,
task.StartWeek,
task.EndWeek,
out var requiredWeeklyHours))
var taskCompleted = true;
foreach (var kind in new[]
{
messages.Add(
$"{task.TaskNumber} · {task.Name} 的普通排课学时不能按授课周次整除,请调整教学任务周次。");
processedTasks++;
if (reportProgress is not null)
ScheduleEntryKind.Lecture,
ScheduleEntryKind.Experiment
})
{
await reportProgress(
new(tasks.Count, processedTasks, created, completedTasks),
cancellationToken);
}
continue;
}
var targetHours = TeachingTaskHours.TargetHours(task.Course!, kind);
var scheduledHours = entries
.Where(x => x.TeachingTaskId == task.Id)
.Sum(x => x.PeriodCount);
if (scheduledHours > requiredWeeklyHours)
.Where(x =>
x.TeachingTaskId == task.Id &&
x.Kind == kind)
.Sum(TeachingTaskHours.ScheduledHours);
var label = kind == ScheduleEntryKind.Experiment ? "实验课" : "理论课";
if (scheduledHours > targetHours)
{
messages.Add(
$"{task.TaskNumber} · {task.Name} 已安排每周 {scheduledHours} 学时," +
$"普通课表只需 {requiredWeeklyHours} 学时;请删除已包含的实践学时。");
processedTasks++;
if (reportProgress is not null)
{
await reportProgress(
new(tasks.Count, processedTasks, created, completedTasks),
cancellationToken);
}
continue;
}
var remainingHours = requiredWeeklyHours - scheduledHours;
if (remainingHours == 0)
{
completedTasks++;
processedTasks++;
if (reportProgress is not null)
{
await reportProgress(
new(tasks.Count, processedTasks, created, completedTasks),
cancellationToken);
}
$"{task.TaskNumber} · {task.Name} 的{label}已安排 {scheduledHours} 学时," +
$"超过课程规定的 {targetHours} 学时,请先删除多余课次。");
taskCompleted = false;
continue;
}
var remainingHours = targetHours - scheduledHours;
while (remainingHours > 0)
{
var desiredBlock = remainingHours >= 2 ? 2 : 1;
var candidate = FindBestCandidate(
var candidate = FindBestCandidateForHours(
plan.Id,
task,
constraint,
desiredBlock,
kind,
remainingHours,
activePeriods,
classrooms,
entries,
cancellationToken);
if (candidate is null && desiredBlock > 1)
{
candidate = FindBestCandidate(
plan.Id,
task,
constraint,
1,
activePeriods,
classrooms,
entries,
cancellationToken);
}
if (candidate is null) break;
db.ScheduleEntries.Add(candidate);
entries.Add(candidate);
created++;
remainingHours -= candidate.PeriodCount;
remainingHours -= TeachingTaskHours.ScheduledHours(candidate);
}
if (remainingHours == 0)
{
completedTasks++;
}
else
if (remainingHours > 0)
{
messages.Add(
$"{task.TaskNumber} · {task.Name} 仍有 {remainingHours} 学时无法安排,请检查教师/班级冲突或场地与时间约束。");
$"{task.TaskNumber} · {task.Name} 仍有 {remainingHours} 个{label}学时无法安排," +
(kind == ScheduleEntryKind.Experiment
? "请检查实验室/机房容量、教师班级冲突或时间约束。"
: "请检查教师/班级冲突或场地与时间约束。"));
taskCompleted = false;
}
}
if (taskCompleted) completedTasks++;
processedTasks++;
if (reportProgress is not null)
@@ -185,11 +150,51 @@ public sealed class AutomaticScheduleGenerator(AppDbContext db)
processedTasks);
}
private static ScheduleEntry? FindBestCandidateForHours(
Guid planId,
TeachingTask task,
TeachingTaskScheduleConstraint? constraint,
ScheduleEntryKind kind,
int remainingHours,
HashSet<int> activePeriods,
IReadOnlyList<Classroom> classrooms,
IReadOnlyList<ScheduleEntry> entries,
CancellationToken cancellationToken)
{
var weekCount = task.EndWeek - task.StartWeek + 1;
foreach (var periodCount in remainingHours >= 2
? new[] { 2, 1 }
: new[] { 1 })
{
var maxOccurrences = Math.Min(
weekCount,
remainingHours / periodCount);
for (var occurrences = maxOccurrences; occurrences >= 1; occurrences--)
{
var candidate = FindBestCandidate(
planId,
task,
constraint,
kind,
periodCount,
occurrences,
activePeriods,
classrooms,
entries,
cancellationToken);
if (candidate is not null) return candidate;
}
}
return null;
}
private static ScheduleEntry? FindBestCandidate(
Guid planId,
TeachingTask task,
TeachingTaskScheduleConstraint? constraint,
ScheduleEntryKind kind,
int periodCount,
int occurrenceCount,
HashSet<int> activePeriods,
IReadOnlyList<Classroom> classrooms,
IReadOnlyList<ScheduleEntry> entries,
@@ -198,11 +203,15 @@ public sealed class AutomaticScheduleGenerator(AppDbContext db)
var allowedDays = ParseAllowedDays(constraint?.AllowedDayOfWeeks);
var firstPeriod = constraint?.EarliestPeriod ?? activePeriods.Min();
var lastPeriod = constraint?.LatestPeriod ?? activePeriods.Max();
var rooms = EligibleRooms(task, constraint, classrooms);
var rooms = EligibleRooms(task, constraint, kind, classrooms);
if ((constraint?.RequiresClassroom ?? true) && rooms.Count == 0)
return null;
var candidates = new List<(ScheduleEntry Entry, int Score)>();
for (var startWeek = task.StartWeek;
startWeek + occurrenceCount - 1 <= task.EndWeek;
startWeek++)
{
foreach (var day in allowedDays)
{
cancellationToken.ThrowIfCancellationRequested();
@@ -212,7 +221,8 @@ public sealed class AutomaticScheduleGenerator(AppDbContext db)
if (Enumerable.Range(start, periodCount).Any(period => !activePeriods.Contains(period)))
continue;
var roomOptions = constraint?.RequiresClassroom == false
var roomOptions = kind != ScheduleEntryKind.Experiment &&
constraint?.RequiresClassroom == false
? new Classroom?[] { null }
: rooms.Cast<Classroom?>().ToArray();
foreach (var room in roomOptions)
@@ -222,14 +232,17 @@ public sealed class AutomaticScheduleGenerator(AppDbContext db)
SchedulePlanId = planId,
TeachingTaskId = task.Id,
TeachingTask = task,
Kind = kind,
ClassroomId = room?.Id,
DayOfWeek = day,
StartPeriod = start,
PeriodCount = periodCount,
StartWeek = task.StartWeek,
EndWeek = task.EndWeek,
StartWeek = startWeek,
EndWeek = startWeek + occurrenceCount - 1,
WeekPattern = WeekPattern.All,
Notes = "自动排课"
Notes = kind == ScheduleEntryKind.Experiment
? "自动排课 · 实验课"
: "自动排课 · 理论课"
};
if (entries.Any(existing =>
ScheduleConflictDetector.TimeOverlaps(existing, proposed) &&
@@ -240,11 +253,13 @@ public sealed class AutomaticScheduleGenerator(AppDbContext db)
x.TeachingTaskId == task.Id && x.DayOfWeek == day);
var dayLoad = entries.Count(x => x.DayOfWeek == day);
var roomWaste = room is null ? 0 : Math.Max(0, room.Capacity - task.Capacity);
var score = sameTaskDay * 1000 + dayLoad * 10 + start + roomWaste / 10;
var score = sameTaskDay * 1000 + dayLoad * 10 + start +
roomWaste / 10 + startWeek;
candidates.Add((proposed, score));
}
}
}
}
return candidates
.OrderBy(x => x.Score)
.ThenBy(x => x.Entry.DayOfWeek)
@@ -256,9 +271,11 @@ public sealed class AutomaticScheduleGenerator(AppDbContext db)
private static IReadOnlyList<Classroom> EligibleRooms(
TeachingTask task,
TeachingTaskScheduleConstraint? constraint,
ScheduleEntryKind kind,
IReadOnlyList<Classroom> classrooms)
{
if (constraint?.RequiresClassroom == false) return [];
if (kind != ScheduleEntryKind.Experiment &&
constraint?.RequiresClassroom == false) return [];
var allowedRoomIds = constraint?.AllowedClassrooms
.Select(x => x.ClassroomId)
.ToHashSet() ?? [];
@@ -273,10 +290,17 @@ public sealed class AutomaticScheduleGenerator(AppDbContext db)
room.Building!.CampusId == requiredCampusId) &&
(constraint?.RequiredBuildingId is not Guid requiredBuildingId ||
room.BuildingId == requiredBuildingId) &&
(allowedRoomIds.Count == 0 || allowedRoomIds.Contains(room.Id)))
(allowedRoomIds.Count == 0 || allowedRoomIds.Contains(room.Id)) &&
(kind != ScheduleEntryKind.Experiment || IsExperimentRoom(room.RoomType)))
.ToList();
}
private static bool IsExperimentRoom(string roomType) =>
roomType.Contains("实验", StringComparison.OrdinalIgnoreCase) ||
roomType.Contains("实训", StringComparison.OrdinalIgnoreCase) ||
roomType.Contains("机房", StringComparison.OrdinalIgnoreCase) ||
roomType.Contains("语音", StringComparison.OrdinalIgnoreCase);
private static int[] ParseAllowedDays(string? value)
{
if (string.IsNullOrWhiteSpace(value)) return [1, 2, 3, 4, 5];
@@ -191,57 +191,30 @@ public sealed class SchedulePlanPublisher(AppDbContext db)
CoursePracticeHours = x.Course.PracticeHours
})
.ToListAsync(cancellationToken);
var invalidHours = requiredTasks.FirstOrDefault(task =>
!TeachingTaskHours.TryResolveRegularWeeklyHours(
task.CourseTotalHours,
task.CoursePracticeHours,
task.StartWeek,
task.EndWeek,
out _));
if (invalidHours is not null)
{
throw new SchedulePublishValidationException(
$"{invalidHours.TaskNumber} · {invalidHours.Name} 的普通排课学时" +
"不能按授课周次整除,请先调整教学任务周次。");
}
var requiredWeeklyHours = requiredTasks
.Select(task =>
{
TeachingTaskHours.TryResolveRegularWeeklyHours(
task.CourseTotalHours,
task.CoursePracticeHours,
task.StartWeek,
task.EndWeek,
out var hours);
return new
{
Task = task,
Hours = hours
};
})
.ToList();
var scheduledHours = plan.Entries
.GroupBy(x => x.TeachingTaskId)
.ToDictionary(group => group.Key, group => group.Sum(x => x.PeriodCount));
var incomplete = requiredWeeklyHours.FirstOrDefault(item =>
scheduledHours.GetValueOrDefault(item.Task.Id) < item.Hours);
if (incomplete is not null)
.GroupBy(x => new { x.TeachingTaskId, x.Kind })
.ToDictionary(
group => (group.Key.TeachingTaskId, group.Key.Kind),
group => group.Sum(TeachingTaskHours.ScheduledHours));
foreach (var task in requiredTasks)
{
var targets = new[]
{
(Kind: ScheduleEntryKind.Lecture,
Hours: Math.Max(0, task.CourseTotalHours - task.CoursePracticeHours),
Label: "理论课"),
(Kind: ScheduleEntryKind.Experiment,
Hours: Math.Max(0, task.CoursePracticeHours),
Label: "实验课")
};
foreach (var target in targets)
{
var actual = scheduledHours.GetValueOrDefault((task.Id, target.Kind));
if (actual == target.Hours) continue;
throw new SchedulePublishValidationException(
$"{incomplete.Task.TaskNumber} · {incomplete.Task.Name} 尚未达到每周 " +
$"{incomplete.Hours} 个普通排课学时,不能发布。");
$"{task.TaskNumber} · {task.Name} 的{target.Label}应安排 " +
$"{target.Hours} 学时,当前已安排 {actual} 学时,不能发布。");
}
var excessive = requiredWeeklyHours.FirstOrDefault(item =>
scheduledHours.GetValueOrDefault(item.Task.Id) > item.Hours);
if (excessive is not null)
{
var actualHours = scheduledHours.GetValueOrDefault(excessive.Task.Id);
throw new SchedulePublishValidationException(
$"{excessive.Task.TaskNumber} · {excessive.Task.Name} 已安排每周 " +
$"{actualHours} 学时,普通课表应为 {excessive.Hours} 学时;" +
"请删除已包含的实践学时后再发布。");
}
await reportProgress(3, "检查教师、行政班和教室冲突", cancellationToken);
@@ -275,7 +248,8 @@ public sealed class SchedulePlanPublisher(AppDbContext db)
Fail(entry, "排课周次不在教学任务的授课周次内");
constraints.TryGetValue(entry.TeachingTaskId, out var constraint);
var requiresClassroom = constraint?.RequiresClassroom ?? true;
var requiresClassroom = entry.Kind == ScheduleEntryKind.Experiment ||
constraint?.RequiresClassroom != false;
if (requiresClassroom && entry.ClassroomId is null)
Fail(entry, "该课程需要占用教室");
if (!requiresClassroom && entry.ClassroomId is not null)
@@ -296,6 +270,9 @@ public sealed class SchedulePlanPublisher(AppDbContext db)
{
if (classroom is null || !classroom.IsEnabled)
Fail(entry, "所选教室不存在或已停用");
if (entry.Kind == ScheduleEntryKind.Experiment &&
!IsExperimentRoom(classroom.RoomType))
Fail(entry, $"实验课不能安排在“{classroom.RoomType}”类型的场地");
if (constraint?.RequiredCampusId is Guid campusId &&
classroom.Building!.CampusId != campusId)
Fail(entry, "所选教室不在指定校区");
@@ -328,6 +305,12 @@ public sealed class SchedulePlanPublisher(AppDbContext db)
.Select(int.Parse)
.ToHashSet();
private static bool IsExperimentRoom(string roomType) =>
roomType.Contains("实验", StringComparison.OrdinalIgnoreCase) ||
roomType.Contains("实训", StringComparison.OrdinalIgnoreCase) ||
roomType.Contains("机房", StringComparison.OrdinalIgnoreCase) ||
roomType.Contains("语音", StringComparison.OrdinalIgnoreCase);
[DoesNotReturn]
private static void Fail(ScheduleEntry entry, string message)
{
@@ -16,10 +16,35 @@ public static class TeachingTaskHours
public static int TargetHours(
Course course,
TeachingTaskSchedulingMode schedulingMode) =>
schedulingMode == TeachingTaskSchedulingMode.Flexible
? course.TotalHours
course.TotalHours;
public static int TargetHours(Course course, ScheduleEntryKind kind) =>
kind == ScheduleEntryKind.Experiment
? Math.Max(0, course.PracticeHours)
: RegularScheduleHours(course);
public static int ScheduledHours(ScheduleEntry entry) =>
ScheduledHours(
entry.StartWeek,
entry.EndWeek,
entry.WeekPattern,
entry.PeriodCount);
public static int ScheduledHours(
int startWeek,
int endWeek,
WeekPattern weekPattern,
int periodCount)
{
if (endWeek < startWeek || periodCount <= 0) return 0;
var occurrences = Enumerable.Range(startWeek, endWeek - startWeek + 1)
.Count(week =>
weekPattern == WeekPattern.All ||
weekPattern == WeekPattern.Odd && week % 2 == 1 ||
weekPattern == WeekPattern.Even && week % 2 == 0);
return occurrences * periodCount;
}
public static bool TryResolveRegularWeeklyHours(
Course course,
int startWeek,
@@ -62,14 +87,8 @@ public static class TeachingTaskHours
if (schedulingMode == TeachingTaskSchedulingMode.Standard)
{
if (targetHours == 0)
{
return $"课程“{course.Name}”的 {course.TotalHours} 学时均为实践学时," +
"无需进入普通课表;请将授课方式设为“非排时课程”,并在实验管理中安排。";
}
return $"课程“{course.Name}”总学时为 {course.TotalHours},其中实践学时 " +
$"{course.PracticeHours},普通课表应安排 {targetHours} 学时;当前第 " +
$"{course.PracticeHours};理论课和实验课均应进入课表。当前第 " +
$"{startWeek}—{endWeek} 周、每周 {weeklyHours} 学时,共 " +
$"{plannedHours} 学时。请调整授课周次或周学时。";
}
@@ -28,6 +28,7 @@ public sealed class TimetableDataService(AppDbContext db)
allowUnpublishedPlan,
cancellationToken);
var slots = await db.ScheduleTimeSlots.AsNoTracking()
.TagWith("Timetable.LoadTimeSlots")
.Where(x => x.AcademicTermId == term.Id && x.IsEnabled)
.OrderBy(x => x.PeriodNumber)
.Select(x => new TimetableSlotDto(
@@ -76,6 +77,7 @@ public sealed class TimetableDataService(AppDbContext db)
}
entries = await source
.TagWith("Timetable.LoadScheduleEntries")
.OrderBy(x => x.DayOfWeek)
.ThenBy(x => x.StartPeriod)
.ThenBy(x => x.TeachingTask!.Course!.Code)
@@ -104,7 +106,14 @@ public sealed class TimetableDataService(AppDbContext db)
false,
null,
null,
x.UpdatedAt))
x.UpdatedAt,
false,
null,
null,
null,
null,
null,
x.Kind))
.ToListAsync(cancellationToken);
}
@@ -283,6 +292,7 @@ public sealed class TimetableDataService(AppDbContext db)
}
return await source
.TagWith("Timetable.LoadFlexibleCourses")
.OrderBy(x => x.Course!.Code)
.ThenBy(x => x.TaskNumber)
.Select(x => new FlexibleCourseDto(
@@ -326,9 +336,11 @@ public sealed class TimetableDataService(AppDbContext db)
legacyQuery, resourceType, resourceId, studentId);
var legacySessions = await legacyQuery
.TagWith("Timetable.LoadLegacyExamEntries")
.OrderBy(x => x.ExamDate)
.ThenBy(x => x.StartPeriod)
.Select(x => new ExamSessionProjection(
x.Id,
x.Id,
x.TeachingTaskId,
x.TeachingTask!.TaskNumber,
@@ -356,71 +368,58 @@ public sealed class TimetableDataService(AppDbContext db)
MapToEntryDto(x, slotLookup)));
// ── Mixed-room sessions (ExamRoomAssignment) ──
// Load all mixed rooms for this term into memory, then filter
var allMixedRooms = await db.ExamRooms.AsNoTracking()
.Where(room =>
room.ExamPlan!.AcademicTermId == academicTermId &&
room.ExamPlan.Status == ExamPlanStatus.Published)
.Include(room => room.ExamPlan)
.Include(room => room.Classroom)
.ThenInclude(c => c!.Building)
.ThenInclude(b => b!.Campus)
.Include(room => room.Invigilators)
.ThenInclude(i => i.Teacher)
.Include(room => room.SessionLinks)
.ThenInclude(link => link.ExamSession)
.ThenInclude(s => s!.TeachingTask)
.ThenInclude(t => t!.Course)
.Include(room => room.SessionLinks)
.ThenInclude(link => link.ExamSession)
.ThenInclude(s => s!.TeachingTask)
.ThenInclude(t => t!.Teachers)
.ThenInclude(tt => tt.Teacher)
.Include(room => room.SessionLinks)
.ThenInclude(link => link.ExamSession)
.ThenInclude(s => s!.TeachingTask)
.ThenInclude(t => t!.Classes)
.ThenInclude(tc => tc.AdministrativeClass)
.Include(room => room.Seats)
// Start from room/session links so the resource predicate stays in SQL.
// Loading every room, seat and roster for the term made a single
// timetable request scale with the entire exam plan.
var mixedQuery = db.ExamRoomSessions.AsNoTracking()
.Where(link =>
link.ExamRoom!.ExamPlan!.AcademicTermId == academicTermId &&
link.ExamRoom.ExamPlan.Status == ExamPlanStatus.Published);
mixedQuery = ApplyMixedResourceFilter(
mixedQuery, resourceType, resourceId, studentId);
var mixedSessions = await mixedQuery
.TagWith("Timetable.LoadMixedExamEntries")
.AsSplitQuery()
.ToListAsync(cancellationToken);
foreach (var room in allMixedRooms)
{
foreach (var link in room.SessionLinks)
{
var session = link.ExamSession;
if (session == null || session.TeachingTask == null) continue;
// Apply resource filter in memory
if (!MatchesMixedResource(
room, session, resourceType, resourceId, studentId))
continue;
result.Add(MapToEntryDto(new ExamSessionProjection(
room.Id,
session.TeachingTaskId,
session.TeachingTask.TaskNumber,
session.TeachingTask.Name,
session.TeachingTask.Course!.Code,
session.TeachingTask.Course.Name,
session.TeachingTask.Teachers
.OrderBy(link => link.ExamRoom!.ExamDate)
.ThenBy(link => link.ExamRoom!.StartPeriod)
.ThenBy(link => link.ExamSession!.TeachingTask!.Course!.Code)
.Select(link => new ExamSessionProjection(
link.ExamSessionId,
link.ExamRoomId,
link.ExamSession!.TeachingTaskId,
link.ExamSession.TeachingTask!.TaskNumber,
link.ExamSession.TeachingTask.Name,
link.ExamSession.TeachingTask.Course!.Code,
link.ExamSession.TeachingTask.Course.Name,
link.ExamSession.TeachingTask.Teachers
.OrderByDescending(t => t.IsPrimary)
.Select(t => t.Teacher!.Name).ToList(),
session.TeachingTask.Classes
link.ExamSession.TeachingTask.Classes
.Select(c => c.AdministrativeClass!.Name).ToList(),
room.Classroom!.Name,
room.Classroom.Building!.Name,
room.Classroom.Building.Campus!.Name,
room.ExamDate,
room.StartPeriod,
room.PeriodCount,
room.ExamPlan!.Name,
room.Invigilators
link.ExamRoom!.Classroom!.Name,
link.ExamRoom.Classroom.Building!.Name,
link.ExamRoom.Classroom.Building.Campus!.Name,
link.ExamRoom.ExamDate,
link.ExamRoom.StartPeriod,
link.ExamRoom.PeriodCount,
link.ExamRoom.ExamPlan!.Name,
link.ExamRoom.Invigilators
.Select(i => i.Teacher!.Name).ToList(),
null,
room.UpdatedAt), slotLookup));
link.ExamRoom.UpdatedAt))
.ToListAsync(cancellationToken);
if (resourceType == TimetableResourceType.Class && !studentId.HasValue)
{
result.AddRange(mixedSessions
.GroupBy(x => x.ExamSessionId)
.Select(group => MapClassExamEntryDto(group, slotLookup)));
}
else
{
result.AddRange(mixedSessions.Select(x =>
MapToEntryDto(x, slotLookup)));
}
return result;
@@ -439,6 +438,7 @@ public sealed class TimetableDataService(AppDbContext db)
db,
studentId.Value);
var sessions = await db.ExperimentSessions.AsNoTracking()
.TagWith("Timetable.LoadExperimentEntries")
.AsSplitQuery()
.Where(x =>
x.ExperimentProject!.TeachingTask!.AcademicTermId == term.Id &&
@@ -535,9 +535,8 @@ public sealed class TimetableDataService(AppDbContext db)
return date.AddDays(1 - dayOfWeek);
}
private static bool MatchesMixedResource(
ExamRoomAssignment room,
ExamSession session,
private static IQueryable<ExamRoomSession> ApplyMixedResourceFilter(
IQueryable<ExamRoomSession> source,
TimetableResourceType resourceType,
Guid resourceId,
Guid? studentId)
@@ -545,20 +544,27 @@ public sealed class TimetableDataService(AppDbContext db)
switch (resourceType)
{
case TimetableResourceType.Classroom:
return room.ClassroomId == resourceId;
return source.Where(link =>
link.ExamRoom!.ClassroomId == resourceId);
case TimetableResourceType.Teacher:
return room.Invigilators.Any(i => i.TeacherId == resourceId) ||
session.TeachingTask!.Teachers.Any(
t => t.TeacherId == resourceId);
return source.Where(link =>
link.ExamRoom!.Invigilators.Any(i =>
i.TeacherId == resourceId) ||
link.ExamSession!.TeachingTask!.Teachers.Any(t =>
t.TeacherId == resourceId));
case TimetableResourceType.Class:
if (studentId.HasValue)
return session.TeachingTask!.Classes.Any(c =>
c.AdministrativeClassId == resourceId) ||
room.Seats.Any(s => s.StudentId == studentId.Value);
return session.TeachingTask!.Classes.Any(c =>
c.AdministrativeClassId == resourceId);
{
return source.Where(link =>
link.ExamRoom!.Seats.Any(s =>
s.StudentId == studentId.Value &&
s.ExamSessionId == link.ExamSessionId));
}
return source.Where(link =>
link.ExamSession!.TeachingTask!.Classes.Any(c =>
c.AdministrativeClassId == resourceId));
default:
return true;
return source;
}
}
@@ -608,7 +614,7 @@ public sealed class TimetableDataService(AppDbContext db)
new[] { "监考:" + string.Join("、", x.InvigilatorNames) })
: x.TeacherNames;
return new TimetableEntryDto(
x.Id,
x.ExamRoomId,
x.TeachingTaskId,
x.TaskNumber,
x.TaskName,
@@ -631,8 +637,42 @@ public sealed class TimetableDataService(AppDbContext db)
x.UpdatedAt);
}
private static TimetableEntryDto MapClassExamEntryDto(
IEnumerable<ExamSessionProjection> sessions,
IReadOnlyDictionary<int, TimetableSlotDto> slotLookup)
{
var rooms = sessions.ToList();
var first = rooms[0];
var roomCount = rooms
.Select(x => x.ExamRoomId)
.Distinct()
.Count();
var buildingNames = rooms
.Select(x => x.BuildingName)
.Distinct()
.ToList();
var campusNames = rooms
.Select(x => x.CampusName)
.Distinct()
.ToList();
var entry = MapToEntryDto(first, slotLookup);
return entry with
{
Id = first.ExamSessionId,
TeacherNames = first.TeacherNames,
ClassroomName = roomCount == 1
? first.ClassroomName
: $"分散至 {roomCount} 个考场",
BuildingName = buildingNames.Count == 1 ? buildingNames[0] : null,
CampusName = campusNames.Count == 1 ? campusNames[0] : null,
UpdatedAt = rooms.Max(x => x.UpdatedAt),
ExamRoomCount = roomCount
};
}
private sealed record ExamSessionProjection(
Guid Id,
Guid ExamSessionId,
Guid ExamRoomId,
Guid TeachingTaskId,
string TaskNumber,
string TaskName,
@@ -762,7 +802,9 @@ public sealed record TimetableEntryDto(
string? ExperimentProjectCode = null,
string? ExperimentProjectName = null,
DateOnly? ExperimentDate = null,
ExperimentArrangementMode? ExperimentArrangementMode = null);
ExperimentArrangementMode? ExperimentArrangementMode = null,
ScheduleEntryKind Kind = ScheduleEntryKind.Lecture,
int ExamRoomCount = 1);
public sealed record FlexibleCourseDto(
Guid Id,
@@ -173,7 +173,7 @@ public static class TimetableExcelExporter
$"{Location(entry)}\n" +
$"{entry.ExamDate:yyyy-MM-dd} · 第 {entry.StartPeriod}-" +
$"{entry.StartPeriod + entry.PeriodCount - 1} 节"
: $"{entry.CourseName}\n" +
: $"{(entry.Kind == Domain.Academic.ScheduleEntryKind.Experiment ? "" : "")}{entry.CourseName}\n" +
$"{string.Join('、', entry.TeacherNames)}\n" +
$"{Location(entry)}\n" +
$"{entry.StartWeek}-{entry.EndWeek} 周";
+7
View File
@@ -2,6 +2,7 @@
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Version>2.3.0-rc3</Version>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<SpaRoot>$([System.IO.Path]::GetFullPath('$(MSBuildProjectDirectory)/../../web'))</SpaRoot>
@@ -22,6 +23,7 @@
<ItemGroup>
<PackageReference Include="ClosedXML" Version="0.105.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.10" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="10.0.10" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.10" />
<PackageReference Include="Microsoft.Extensions.Caching.Hybrid" Version="10.1.0" />
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="10.0.10" />
@@ -31,6 +33,11 @@
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.10" />
<PackageReference Include="MySql.EntityFrameworkCore" Version="10.0.7" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.17.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.17.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.17.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.17.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.17.0" />
<PackageReference Include="QRCoder" Version="1.8.0" />
<PackageReference Include="RabbitMQ.Client" Version="7.2.1" />
<PackageReference Include="SkiaSharp" Version="3.119.2" />
+190 -3
View File
@@ -7,18 +7,25 @@ using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Caching;
using Jiaowu.Api.Infrastructure.Exams;
using Jiaowu.Api.Infrastructure.Middleware;
using Jiaowu.Api.Infrastructure.Observability;
using Jiaowu.Api.Infrastructure.OfficialDocuments;
using Jiaowu.Api.Infrastructure.Operations;
using Jiaowu.Api.Infrastructure.Persistence;
using Jiaowu.Api.Infrastructure.Scheduling;
using Jiaowu.Api.Infrastructure.Timetables;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
using System.Threading.RateLimiting;
EnvironmentFile.Load();
@@ -78,9 +85,38 @@ var backgroundJobOptions = builder.Configuration
var operationsOptions = builder.Configuration
.GetSection(OperationsOptions.SectionName)
.Get<OperationsOptions>() ?? new OperationsOptions();
var observabilityOptions = builder.Configuration
.GetSection(ObservabilityOptions.SectionName)
.Get<ObservabilityOptions>() ?? new ObservabilityOptions();
var performanceReportingOptions = builder.Configuration
.GetSection(PerformanceReportingOptions.SectionName)
.Get<PerformanceReportingOptions>() ?? new PerformanceReportingOptions();
var rabbitMqOptions = builder.Configuration
.GetSection(RabbitMqOptions.SectionName)
.Get<RabbitMqOptions>() ?? new RabbitMqOptions();
var ssoOptions = builder.Configuration
.GetSection(SsoOptions.SectionName)
.Get<SsoOptions>() ?? new SsoOptions();
if (ssoOptions.Enabled &&
(string.IsNullOrWhiteSpace(ssoOptions.ClientId) ||
!Uri.TryCreate(ssoOptions.Authority, UriKind.Absolute, out var ssoAuthority) ||
ssoAuthority.Scheme is not ("http" or "https") ||
(ssoOptions.RequireHttpsMetadata && ssoAuthority.Scheme != "https") ||
string.IsNullOrWhiteSpace(ssoOptions.UserNameClaim) ||
(!string.IsNullOrWhiteSpace(ssoOptions.CallbackUrl) &&
(!Uri.TryCreate(ssoOptions.CallbackUrl, UriKind.Absolute, out var callbackUrl) ||
callbackUrl.Scheme is not ("http" or "https") ||
!callbackUrl.AbsolutePath.EndsWith(
"/signin-keycloak",
StringComparison.OrdinalIgnoreCase))) ||
(!string.IsNullOrWhiteSpace(ssoOptions.FrontendBaseUrl) &&
(!Uri.TryCreate(ssoOptions.FrontendBaseUrl, UriKind.Absolute, out var frontendBaseUrl) ||
frontendBaseUrl.Scheme is not ("http" or "https")))))
{
throw new InvalidOperationException(
"启用 Sso 时必须配置有效的 Authority、ClientId、UserNameClaim、CallbackUrl 和 FrontendBaseUrlCallbackUrl 必须以 /signin-keycloak 结尾,生产元数据地址必须使用 HTTPS。");
}
if (string.IsNullOrWhiteSpace(officialDocumentOptions.InstitutionName) ||
string.IsNullOrWhiteSpace(officialDocumentOptions.IssuingOffice) ||
@@ -110,6 +146,46 @@ if (databaseOptions.CommandTimeoutSeconds is < 5 or > 300)
"Database:CommandTimeoutSeconds 必须在 5 到 300 秒之间。");
}
if (string.IsNullOrWhiteSpace(observabilityOptions.ServiceName) ||
observabilityOptions.ServiceName.Length > 100 ||
observabilityOptions.SlowQueryThresholdMilliseconds is < 1 or > 60000 ||
observabilityOptions.MaximumSqlTextLength is < 256 or > 20000)
{
throw new InvalidOperationException(
"Observability 服务名、慢查询阈值或 SQL 文本长度超出允许范围。");
}
if (performanceReportingOptions.CacheSeconds is < 5 or > 300 ||
performanceReportingOptions.TimeoutSeconds is < 1 or > 60 ||
performanceReportingOptions.BearerToken.Length > 8000 ||
!PerformanceReportingOptions.IsMetricOrLabelName(
performanceReportingOptions.ServiceLabel) ||
!PerformanceReportingOptions.IsMetricOrLabelName(
performanceReportingOptions.RequestDurationMetric) ||
!PerformanceReportingOptions.IsMetricOrLabelName(
performanceReportingOptions.DatabaseDurationMetric) ||
!PerformanceReportingOptions.IsMetricOrLabelName(
performanceReportingOptions.SlowDatabaseMetric) ||
!PerformanceReportingOptions.IsMetricOrLabelName(
performanceReportingOptions.FailedDatabaseMetric) ||
(performanceReportingOptions.Enabled &&
!IsHttpUrl(performanceReportingOptions.PrometheusBaseUrl)) ||
(!string.IsNullOrWhiteSpace(performanceReportingOptions.GrafanaBaseUrl) &&
!IsHttpUrl(performanceReportingOptions.GrafanaBaseUrl)))
{
throw new InvalidOperationException(
"PerformanceReporting 数据源、超时、缓存或指标名称配置无效。");
}
var otlpEndpoint = builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"];
if (!string.IsNullOrWhiteSpace(otlpEndpoint) &&
(!Uri.TryCreate(otlpEndpoint, UriKind.Absolute, out var parsedOtlpEndpoint) ||
parsedOtlpEndpoint.Scheme is not ("http" or "https")))
{
throw new InvalidOperationException(
"OTEL_EXPORTER_OTLP_ENDPOINT 必须是有效的 HTTP 或 HTTPS 绝对地址。");
}
if (cacheOptions.ReferenceExpirationMinutes is < 1 or > 1440 ||
cacheOptions.TimetableExpirationMinutes is < 1 or > 1440 ||
cacheOptions.AnalyticsExpirationMinutes is < 1 or > 1440 ||
@@ -193,11 +269,23 @@ builder.Services.AddSingleton(cacheOptions);
builder.Services.AddSingleton(officialDocumentOptions);
builder.Services.AddSingleton(backgroundJobOptions);
builder.Services.AddSingleton(operationsOptions);
builder.Services.AddSingleton(observabilityOptions);
builder.Services.AddSingleton(performanceReportingOptions);
builder.Services.AddSingleton(rabbitMqOptions);
builder.Services.AddSingleton<DatabaseCommandTelemetryInterceptor>();
builder.Services.AddMemoryCache();
builder.Services.AddHttpClient<PerformanceReportService>((services, client) =>
{
var reporting = services.GetRequiredService<PerformanceReportingOptions>();
client.Timeout = TimeSpan.FromSeconds(reporting.TimeoutSeconds);
});
builder.Services.Configure<OfficialDocumentOptions>(
builder.Configuration.GetSection(OfficialDocumentOptions.SectionName));
builder.Services.AddDbContextPool<AppDbContext>(options =>
builder.Services.AddDbContextPool<AppDbContext>((services, options) =>
{
options.AddInterceptors(
services.GetRequiredService<DatabaseCommandTelemetryInterceptor>());
if (databaseOptions.Provider.Equals("SQLite", StringComparison.OrdinalIgnoreCase))
{
var sqliteConnectionString = builder.Configuration.GetConnectionString("SQLite")
@@ -240,12 +328,38 @@ builder.Services.AddDbContextPool<AppDbContext>(options =>
});
});
if (observabilityOptions.Enabled &&
!string.IsNullOrWhiteSpace(otlpEndpoint))
{
builder.Services
.AddOpenTelemetry()
.ConfigureResource(resource =>
resource.AddService(observabilityOptions.ServiceName))
.WithMetrics(metrics => metrics
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddRuntimeInstrumentation()
.AddMeter(DatabaseCommandTelemetryInterceptor.MeterName))
.WithTracing(tracing => tracing
.AddAspNetCoreInstrumentation(options =>
options.Filter = context =>
!context.Request.Path.StartsWithSegments("/health/live"))
.AddHttpClientInstrumentation()
.AddSource(DatabaseCommandTelemetryInterceptor.ActivitySourceName))
.WithMetrics(metrics => metrics.AddOtlpExporter())
.WithTracing(tracing => tracing.AddOtlpExporter());
}
var redisConnectionString = builder.Configuration.GetConnectionString("Redis");
if (cacheOptions.Enabled && !string.IsNullOrWhiteSpace(redisConnectionString))
{
builder.Services.AddStackExchangeRedisCache(options =>
options.Configuration = redisConnectionString);
}
else
{
builder.Services.AddDistributedMemoryCache();
}
builder.Services.AddHybridCache(options =>
{
options.MaximumKeyLength = 512;
@@ -276,11 +390,22 @@ if (Encoding.UTF8.GetByteCount(jwtOptions.Key) < 32 ||
throw new InvalidOperationException(
"Jwt:Key 必须配置为至少 32 字节的随机生产密钥,不能使用示例值。");
}
if (jwtOptions.AccessTokenMinutes is < 1 or > 30 ||
jwtOptions.WebIdleMinutes is < 5 or > 1440 ||
jwtOptions.AppIdleMinutes is < 60 or > 43200 ||
jwtOptions.AccessTokenMinutes > jwtOptions.WebIdleMinutes)
{
throw new InvalidOperationException(
"Jwt 访问令牌或 Web/App 空闲有效期配置超出允许范围。");
}
builder.Services.Configure<JwtOptions>(
builder.Configuration.GetSection(JwtOptions.SectionName));
builder.Services.Configure<SsoOptions>(
builder.Configuration.GetSection(SsoOptions.SectionName));
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<ITokenService, TokenService>();
builder.Services.AddScoped<IAuthSessionService, AuthSessionService>();
builder.Services.AddScoped<ICurrentUserDataScope, CurrentUserDataScope>();
builder.Services.AddScoped<DatabaseInitializer>();
builder.Services.AddScoped<DemoDataSeeder>();
@@ -323,8 +448,12 @@ builder.Services.AddHostedService<BackgroundJobOutboxPublisher>();
builder.Services.AddSingleton<IOfficialDocumentPdfGenerator, OfficialDocumentPdfGenerator>();
builder.Services.AddScoped<OfficialDocumentService>();
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
var authentication = builder.Services
.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
@@ -339,7 +468,51 @@ builder.Services
Encoding.UTF8.GetBytes(jwtOptions.Key)),
ClockSkew = TimeSpan.FromMinutes(1)
};
})
.AddCookie(SsoAuthSchemes.ExternalCookie, options =>
{
options.Cookie.Name = "__Host-jiaowu-sso";
options.Cookie.HttpOnly = true;
options.Cookie.SameSite = SameSiteMode.Lax;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
});
if (ssoOptions.Enabled)
{
authentication.AddOpenIdConnect(SsoAuthSchemes.Keycloak, options =>
{
options.Authority = ssoOptions.Authority.TrimEnd('/');
options.ClientId = ssoOptions.ClientId;
options.ClientSecret = ssoOptions.ClientSecret;
options.SignInScheme = SsoAuthSchemes.ExternalCookie;
options.ResponseType = "code";
options.UsePkce = true;
options.SaveTokens = false;
options.RequireHttpsMetadata = ssoOptions.RequireHttpsMetadata;
options.CallbackPath = "/signin-keycloak";
options.GetClaimsFromUserInfoEndpoint = true;
options.MapInboundClaims = false;
options.ClaimActions.MapUniqueJsonKey(
ssoOptions.UserNameClaim,
ssoOptions.UserNameClaim);
options.TokenValidationParameters.NameClaimType = ssoOptions.UserNameClaim;
options.Events.OnRedirectToIdentityProvider = context =>
{
if (!string.IsNullOrWhiteSpace(ssoOptions.CallbackUrl))
context.ProtocolMessage.RedirectUri = ssoOptions.CallbackUrl;
return Task.CompletedTask;
};
options.Events.OnRemoteFailure = context =>
{
context.HandleResponse();
var loginUrl = string.IsNullOrWhiteSpace(ssoOptions.FrontendBaseUrl)
? "/login"
: ssoOptions.FrontendBaseUrl.TrimEnd('/') + "/login";
context.Response.Redirect(loginUrl + "?ssoError=authentication_failed");
return Task.CompletedTask;
};
});
}
builder.Services.AddAuthorization();
builder.Services.AddRateLimiter(options =>
{
@@ -354,6 +527,16 @@ builder.Services.AddRateLimiter(options =>
QueueLimit = 0,
AutoReplenishment = true
}));
options.AddPolicy("token-refresh", context =>
RateLimitPartition.GetFixedWindowLimiter(
context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
_ => new FixedWindowRateLimiterOptions
{
PermitLimit = 600,
Window = TimeSpan.FromMinutes(1),
QueueLimit = 0,
AutoReplenishment = true
}));
options.AddPolicy("official-verification", context =>
RateLimitPartition.GetFixedWindowLimiter(
context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
@@ -616,4 +799,8 @@ static async Task<IResult> CheckMessagingHealthAsync(
}
}
static bool IsHttpUrl(string value) =>
Uri.TryCreate(value, UriKind.Absolute, out var uri) &&
uri.Scheme is "http" or "https";
public partial class Program;
+7 -1
View File
@@ -10,7 +10,13 @@
},
"Jwt": {
"Key": "jiaowu-development-secret-key-change-before-production",
"ExpireMinutes": 480
"AccessTokenMinutes": 10,
"WebIdleMinutes": 30,
"AppIdleMinutes": 4320
},
"Sso": {
"FrontendBaseUrl": "http://localhost:5173",
"CallbackUrl": "http://localhost:5255/signin-keycloak"
},
"Cors": {
"Origins": [
+35 -1
View File
@@ -19,6 +19,26 @@
"AnalyticsLocalExpirationSeconds": 30,
"MaximumPayloadKilobytes": 2048
},
"Observability": {
"Enabled": true,
"ServiceName": "jiaowu-api",
"SlowQueryThresholdMilliseconds": 500,
"IncludeSqlText": false,
"MaximumSqlTextLength": 2000
},
"PerformanceReporting": {
"Enabled": false,
"PrometheusBaseUrl": "",
"BearerToken": "",
"GrafanaBaseUrl": "",
"CacheSeconds": 30,
"TimeoutSeconds": 10,
"ServiceLabel": "service_name",
"RequestDurationMetric": "http_server_request_duration_seconds",
"DatabaseDurationMetric": "jiaowu_db_command_duration_milliseconds",
"SlowDatabaseMetric": "jiaowu_db_command_slow_total",
"FailedDatabaseMetric": "jiaowu_db_command_failed_total"
},
"Operations": {
"BackupDirectory": "data/backups",
"BackupWarningHours": 24,
@@ -57,7 +77,21 @@
"Issuer": "Jiaowu.Api",
"Audience": "Jiaowu.Web",
"Key": "",
"ExpireMinutes": 60
"AccessTokenMinutes": 10,
"WebIdleMinutes": 30,
"AppIdleMinutes": 4320
},
"Sso": {
"Enabled": false,
"DisplayName": "学校统一身份认证",
"Authority": "",
"ClientId": "",
"ClientSecret": "",
"UserNameClaim": "preferred_username",
"RequireHttpsMetadata": true,
"LinkExistingUsersByUserName": true,
"FrontendBaseUrl": "",
"CallbackUrl": ""
},
"Cors": {
"Origins": [
+22 -3
View File
@@ -107,7 +107,7 @@ public sealed class AuthControllerTests
var controller = new AuthController(
db,
userManager,
new StubTokenService(),
new StubAuthSessionService(),
NoOpAppCache.Instance);
var request = new StudentActivationRequest(
student.Name,
@@ -143,8 +143,27 @@ public sealed class AuthControllerTests
protected override bool ShouldRetryOn(Exception exception) => false;
}
private sealed class StubTokenService : ITokenService
private sealed class StubAuthSessionService : IAuthSessionService
{
public string Create(ApplicationUser user, IEnumerable<string> roles) => string.Empty;
public Task<AuthSessionResult> CreateAsync(
ApplicationUser user,
IEnumerable<string> roles,
AuthenticationClientType clientType,
CancellationToken cancellationToken = default) =>
Task.FromResult(new AuthSessionResult(
string.Empty,
DateTime.UtcNow.AddMinutes(10),
"test-refresh-token-value-with-sufficient-length",
DateTime.UtcNow.AddMinutes(30),
user,
roles.ToList()));
public Task<AuthSessionResult?> RefreshAsync(
string refreshToken,
CancellationToken cancellationToken = default) => Task.FromResult<AuthSessionResult?>(null);
public Task RevokeAsync(
string refreshToken,
CancellationToken cancellationToken = default) => Task.CompletedTask;
}
}
@@ -0,0 +1,133 @@
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Identity;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace Jiaowu.Api.Tests;
public sealed class AuthSessionServiceTests
{
[Fact]
public async Task Web_session_rotates_refresh_token_and_rejects_reuse()
{
await using var fixture = await SessionFixture.CreateAsync();
var issued = await fixture.Service.CreateAsync(
fixture.User,
[SystemRoles.Student],
AuthenticationClientType.Web);
Assert.InRange(
issued.SessionExpiresAt,
DateTime.UtcNow.AddMinutes(29),
DateTime.UtcNow.AddMinutes(31));
var stored = await fixture.Db.RefreshSessions.SingleAsync();
Assert.NotEqual(issued.RefreshToken, stored.TokenHash);
var refreshed = await fixture.Service.RefreshAsync(issued.RefreshToken);
Assert.NotNull(refreshed);
Assert.NotEqual(issued.RefreshToken, refreshed.RefreshToken);
Assert.Null(await fixture.Service.RefreshAsync(issued.RefreshToken));
Assert.Equal(1, await fixture.Db.RefreshSessions.CountAsync(x => x.RevokedAt == null));
}
[Fact]
public async Task App_session_uses_three_day_sliding_window()
{
await using var fixture = await SessionFixture.CreateAsync();
var issued = await fixture.Service.CreateAsync(
fixture.User,
[SystemRoles.Student],
AuthenticationClientType.App);
Assert.InRange(
issued.SessionExpiresAt,
DateTime.UtcNow.AddDays(3).AddMinutes(-1),
DateTime.UtcNow.AddDays(3).AddMinutes(1));
}
private sealed class SessionFixture : IAsyncDisposable
{
private readonly SqliteConnection _connection;
private readonly ServiceProvider _provider;
private readonly AsyncServiceScope _scope;
private SessionFixture(
SqliteConnection connection,
ServiceProvider provider,
AsyncServiceScope scope,
AppDbContext db,
ApplicationUser user,
IAuthSessionService service)
{
_connection = connection;
_provider = provider;
_scope = scope;
Db = db;
User = user;
Service = service;
}
public AppDbContext Db { get; }
public ApplicationUser User { get; }
public IAuthSessionService Service { get; }
public static async Task<SessionFixture> CreateAsync()
{
var connection = new SqliteConnection("Data Source=:memory:");
await connection.OpenAsync();
var services = new ServiceCollection();
services.AddLogging();
services.AddDbContext<AppDbContext>(options => options.UseSqlite(connection));
services.Configure<JwtOptions>(options =>
{
options.Issuer = "tests";
options.Audience = "tests-web";
options.Key = "a-test-signing-key-that-is-at-least-32-bytes-long";
options.AccessTokenMinutes = 10;
options.WebIdleMinutes = 30;
options.AppIdleMinutes = 4320;
});
services
.AddIdentityCore<ApplicationUser>()
.AddRoles<ApplicationRole>()
.AddEntityFrameworkStores<AppDbContext>();
services.AddScoped<ITokenService, TokenService>();
services.AddScoped<IAuthSessionService, AuthSessionService>();
var provider = services.BuildServiceProvider();
var scope = provider.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.Database.EnsureCreatedAsync();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var user = new ApplicationUser
{
UserName = "session-user",
DisplayName = "会话测试用户",
IsEnabled = true,
LockoutEnabled = true
};
Assert.True((await userManager.CreateAsync(user, "SessionUser@123")).Succeeded);
return new SessionFixture(
connection,
provider,
scope,
db,
user,
scope.ServiceProvider.GetRequiredService<IAuthSessionService>());
}
public async ValueTask DisposeAsync()
{
await _scope.DisposeAsync();
await _provider.DisposeAsync();
await _connection.DisposeAsync();
}
}
}
@@ -1,6 +1,7 @@
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Infrastructure.Persistence;
using Jiaowu.Api.Infrastructure.Scheduling;
using Jiaowu.Api.Infrastructure.Teaching;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
@@ -157,6 +158,21 @@ public sealed class AutomaticScheduleGeneratorTests
EndDate = new DateOnly(2027, 1, 15)
};
var college = new College { Code = "LAB", Name = "实验学院" };
var campus = new Campus { Code = "LAB-CAMPUS", Name = "实验校区" };
var building = new Building
{
Code = "LAB-BUILDING",
Name = "实验楼",
Campus = campus
};
var laboratory = new Classroom
{
Code = "LAB-101",
Name = "实验室 101",
Building = building,
Capacity = 40,
RoomType = "实验室"
};
var course = new Course
{
Code = "LAB-01",
@@ -185,7 +201,7 @@ public sealed class AutomaticScheduleGeneratorTests
Name = "实验学时拆分测试",
Version = "V1"
};
db.AddRange(term, college, course, task, plan);
db.AddRange(term, college, campus, building, laboratory, course, task, plan);
db.ScheduleTimeSlots.AddRange(
new ScheduleTimeSlot
{
@@ -203,22 +219,22 @@ public sealed class AutomaticScheduleGeneratorTests
StartsAt = new TimeOnly(8, 55),
EndsAt = new TimeOnly(9, 40)
});
db.TeachingTaskScheduleConstraints.Add(
new TeachingTaskScheduleConstraint
{
TeachingTask = task,
RequiresClassroom = false
});
await db.SaveChangesAsync();
var result = await new AutomaticScheduleGenerator(db)
.GenerateAsync(plan, CancellationToken.None);
Assert.Equal(1, result.CreatedEntries);
Assert.Equal(2, result.CreatedEntries);
Assert.Equal(1, result.CompletedTasks);
Assert.Equal(
1,
(await db.ScheduleEntries.SingleAsync()).PeriodCount);
var entries = await db.ScheduleEntries.OrderBy(x => x.Kind).ToListAsync();
Assert.Equal(2, entries.Count);
Assert.Contains(entries, x =>
x.Kind == ScheduleEntryKind.Lecture &&
TeachingTaskHours.ScheduledHours(x) == 16);
Assert.Contains(entries, x =>
x.Kind == ScheduleEntryKind.Experiment &&
x.ClassroomId == laboratory.Id &&
TeachingTaskHours.ScheduledHours(x) == 16);
}
[Fact]
@@ -0,0 +1,88 @@
using System.Diagnostics.Metrics;
using Jiaowu.Api.Infrastructure.Observability;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
namespace Jiaowu.Api.Tests;
public sealed class DatabaseCommandTelemetryInterceptorTests
{
[Fact]
public void Query_name_uses_tag_without_exposing_statement_text()
{
const string sql =
"-- Timetable.LoadMixedExamEntries\n" +
"SELECT * FROM ExamRooms WHERE SecretValue = @p0";
var queryName =
DatabaseCommandTelemetryInterceptor.GetQueryName(sql);
Assert.Equal("Timetable.LoadMixedExamEntries", queryName);
Assert.DoesNotContain("SecretValue", queryName);
Assert.DoesNotContain("@p0", queryName);
}
[Fact]
public void Untagged_query_name_is_stable_hash_not_statement_text()
{
const string sql =
"SELECT * FROM Students WHERE StudentNumber = @studentNumber";
var first = DatabaseCommandTelemetryInterceptor.GetQueryName(sql);
var second = DatabaseCommandTelemetryInterceptor.GetQueryName(sql);
Assert.Equal(first, second);
Assert.StartsWith("select:", first);
Assert.DoesNotContain("Students", first);
Assert.DoesNotContain("StudentNumber", first);
}
[Fact]
public async Task Ef_command_records_duration_metric()
{
await using var connection =
new SqliteConnection("Data Source=:memory:");
await connection.OpenAsync();
var setupOptions = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlite(connection)
.Options;
await using (var setupDb = new AppDbContext(setupOptions))
await setupDb.Database.EnsureCreatedAsync();
double? recordedDuration = null;
using var listener = new MeterListener
{
InstrumentPublished = (instrument, meterListener) =>
{
if (instrument.Meter.Name ==
DatabaseCommandTelemetryInterceptor.MeterName &&
instrument.Name == "jiaowu.db.command.duration")
{
meterListener.EnableMeasurementEvents(instrument);
}
}
};
listener.SetMeasurementEventCallback<double>(
(_, measurement, _, _) => recordedDuration = measurement);
listener.Start();
var interceptor = new DatabaseCommandTelemetryInterceptor(
new ObservabilityOptions(),
NullLogger<DatabaseCommandTelemetryInterceptor>.Instance);
var queryOptions = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlite(connection)
.AddInterceptors(interceptor)
.Options;
await using var db = new AppDbContext(queryOptions);
await db.AcademicTerms
.TagWith("Observability.Tests.TermCount")
.CountAsync();
Assert.NotNull(recordedDuration);
Assert.True(recordedDuration >= 0);
}
}
@@ -1,6 +1,7 @@
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Infrastructure.Exams;
using Jiaowu.Api.Infrastructure.Persistence;
using Jiaowu.Api.Infrastructure.Timetables;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
@@ -55,6 +56,48 @@ public sealed class ExamArrangementServiceTests
Assert.Contains("1个教学班场次处理完成", result.Message);
Assert.Contains("1名监考教师", result.Message);
Assert.Contains("程序设计", result.Message);
plan = await db.ExamPlans.SingleAsync(x => x.Id == plan.Id);
plan.Status = ExamPlanStatus.Published;
await db.SaveChangesAsync();
db.ChangeTracker.Clear();
var timetableService = new TimetableDataService(db);
var classroomTimetable = await timetableService.BuildAsync(
TimetableResourceType.Classroom,
seed.LargeClassroom.Id,
seed.Term.Id,
null,
false,
null,
null,
CancellationToken.None);
var unrelatedClassroomTimetable = await timetableService.BuildAsync(
TimetableResourceType.Classroom,
seed.SmallClassroom.Id,
seed.Term.Id,
null,
false,
null,
null,
CancellationToken.None);
var invigilatorTimetable = await timetableService.BuildAsync(
TimetableResourceType.Teacher,
room.Invigilators.Single().TeacherId,
seed.Term.Id,
null,
false,
null,
null,
CancellationToken.None);
Assert.Equal(
"程序设计",
Assert.Single(classroomTimetable!.ExamEntries).CourseName);
Assert.Empty(unrelatedClassroomTimetable!.ExamEntries);
Assert.Contains(
"监考:监考教师",
Assert.Single(invigilatorTimetable!.ExamEntries).TeacherNames);
}
[Fact]
@@ -108,6 +151,46 @@ public sealed class ExamArrangementServiceTests
Assert.Equal(6, await db.ExamSeats.CountAsync());
Assert.Contains("2个教学班混排至2个考场", result.Message);
Assert.Contains("自动包含同组1个场次", result.Message);
plan = await db.ExamPlans.SingleAsync(x => x.Id == plan.Id);
plan.Status = ExamPlanStatus.Published;
await db.SaveChangesAsync();
db.ChangeTracker.Clear();
var student = await db.Students.AsNoTracking()
.OrderBy(x => x.StudentNumber)
.FirstAsync();
var timetableService = new TimetableDataService(db);
var classTimetable = await timetableService.BuildAsync(
TimetableResourceType.Class,
student.AdministrativeClassId,
seed.Term.Id,
null,
false,
null,
null,
CancellationToken.None);
var studentTimetable = await timetableService.BuildAsync(
TimetableResourceType.Class,
student.AdministrativeClassId,
seed.Term.Id,
null,
false,
student.Id,
new TimetableStudentDto(student.StudentNumber, student.Name),
CancellationToken.None);
var classExam = Assert.Single(classTimetable!.ExamEntries);
Assert.Equal(first.Id, classExam.Id);
Assert.Equal(2, classExam.ExamRoomCount);
Assert.Equal("分散至 2 个考场", classExam.ClassroomName);
Assert.DoesNotContain("监考:", classExam.TeacherNames);
var studentExam = Assert.Single(studentTimetable!.ExamEntries);
Assert.Equal(1, studentExam.ExamRoomCount);
Assert.Contains(
studentExam.ClassroomName,
new[] { seed.LargeClassroom.Name, seed.SmallClassroom.Name });
}
[Fact]
@@ -12,6 +12,112 @@ namespace Jiaowu.Api.Tests;
public sealed class ExperimentsControllerTests
{
[Fact]
public async Task BatchProjects_CreateSameDefinitionForSameCourseTasks()
{
await using var fixture = await ExperimentFixture.CreateAsync();
var controller = fixture.Controller(fixture.ManagerScope);
var result = await controller.CreateProjects(
fixture.BatchProjectRequest(
ExperimentArrangementMode.Centralized),
CancellationToken.None);
Assert.IsType<CreatedResult>(result);
var projects = await fixture.Db.ExperimentProjects
.OrderBy(x => x.TeachingTaskId)
.ToListAsync();
Assert.Equal(2, projects.Count);
Assert.Equal(2, projects.Select(x => x.TeachingTaskId).Distinct().Count());
Assert.All(projects, project =>
{
Assert.Equal("LAB-BATCH", project.Code);
Assert.Equal("公共实验任务", project.Name);
Assert.Equal(ExperimentProjectStatus.Draft, project.Status);
});
}
[Fact]
public async Task BatchSessions_RollsBackAllRowsWhenOneConflicts()
{
await using var fixture = await ExperimentFixture.CreateAsync();
var controller = fixture.Controller(fixture.ManagerScope);
await controller.CreateProjects(
fixture.BatchProjectRequest(
ExperimentArrangementMode.SelfScheduled),
CancellationToken.None);
var projectIds = await fixture.Db.ExperimentProjects
.OrderBy(x => x.TeachingTaskId)
.Select(x => x.Id)
.ToListAsync();
var result = await controller.CreateSessions(
new ExperimentSessionBatchRequest(
[
new ExperimentSessionBatchItem(
projectIds[0],
fixture.Classroom.Id,
fixture.Term.StartDate,
1,
2,
20,
null),
new ExperimentSessionBatchItem(
projectIds[1],
fixture.Classroom.Id,
fixture.Term.StartDate,
1,
2,
20,
null)
]),
CancellationToken.None);
Assert.IsType<ConflictObjectResult>(result);
fixture.Db.ChangeTracker.Clear();
Assert.Empty(await fixture.Db.ExperimentSessions.ToListAsync());
}
[Fact]
public async Task BatchSessions_CreatesRowsAtomicallyWhenAllAreValid()
{
await using var fixture = await ExperimentFixture.CreateAsync();
var controller = fixture.Controller(fixture.ManagerScope);
await controller.CreateProjects(
fixture.BatchProjectRequest(
ExperimentArrangementMode.SelfScheduled),
CancellationToken.None);
var projectIds = await fixture.Db.ExperimentProjects
.OrderBy(x => x.TeachingTaskId)
.Select(x => x.Id)
.ToListAsync();
var result = await controller.CreateSessions(
new ExperimentSessionBatchRequest(
[
new ExperimentSessionBatchItem(
projectIds[0],
fixture.Classroom.Id,
fixture.Term.StartDate,
1,
2,
20,
null),
new ExperimentSessionBatchItem(
projectIds[1],
fixture.SecondClassroom.Id,
fixture.Term.StartDate,
1,
2,
20,
null)
]),
CancellationToken.None);
Assert.IsType<CreatedResult>(result);
Assert.Equal(2, await fixture.Db.ExperimentSessions.CountAsync());
}
[Fact]
public async Task CentralizedProject_PublishesAndUsesTeachingTaskRoster()
{
@@ -421,6 +527,15 @@ public sealed class ExperimentsControllerTests
}
]
};
var secondTask = new TeachingTask
{
TaskNumber = "2099-1-CSLAB-02",
Name = "系统实验教学班 02",
AcademicTermId = term.Id,
CourseId = course.Id,
Capacity = 40,
Status = TeachingTaskStatus.Published
};
db.AddRange(
manager,
studentUser,
@@ -435,7 +550,8 @@ public sealed class ExperimentsControllerTests
teacher,
term,
course,
task);
task,
secondTask);
for (var period = 1; period <= 12; period++)
{
db.ScheduleTimeSlots.Add(new ScheduleTimeSlot
@@ -486,6 +602,21 @@ public sealed class ExperimentsControllerTests
Term.StartDate,
Term.StartDate.AddDays(14));
public ExperimentProjectBatchRequest BatchProjectRequest(
ExperimentArrangementMode mode) =>
new(
Db.TeachingTasks
.OrderBy(x => x.TaskNumber)
.Select(x => x.Id)
.ToList(),
"LAB-BATCH",
"公共实验任务",
mode,
"多个教学任务共用的实验内容。",
"携带校园卡。",
Term.StartDate,
Term.StartDate.AddDays(14));
public ExperimentSessionRequest SessionRequest(
int startPeriod,
int periodCount,
@@ -235,6 +235,39 @@ public sealed class MySqlMigrationTests
StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void MySql_experiment_batch_project_query_is_translatable()
{
using var db = new AppDbContext(CreateMySqlOptions());
var projectIds = new[]
{
Guid.Parse("11111111-1111-1111-1111-111111111111"),
Guid.Parse("22222222-2222-2222-2222-222222222222")
};
var accessibleTaskIds = db.TeachingTasks.Select(x => x.Id);
var sql = db.ExperimentProjects
.Where(x => accessibleTaskIds.Contains(x.TeachingTaskId))
.Include(x => x.TeachingTask)
.ThenInclude(x => x!.AcademicTerm)
.WhereIn(projectIds, x => x.Id)
.ToQueryString();
Assert.Contains(
"ExperimentProjects",
sql,
StringComparison.OrdinalIgnoreCase);
Assert.Contains(" IN (", sql, StringComparison.OrdinalIgnoreCase);
Assert.Contains(
projectIds[0].ToString(),
sql,
StringComparison.OrdinalIgnoreCase);
Assert.Contains(
projectIds[1].ToString(),
sql,
StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void MySql_index_names_fit_the_server_identifier_limit()
{
@@ -7,6 +7,7 @@ using Jiaowu.Api.Domain.System;
using Jiaowu.Api.Infrastructure.BackgroundJobs;
using Jiaowu.Api.Infrastructure.Caching;
using Jiaowu.Api.Infrastructure.Operations;
using Jiaowu.Api.Infrastructure.Observability;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
@@ -201,6 +202,7 @@ public sealed class OperationsControllerTests
var services = new ServiceCollection()
.AddLogging()
.AddMemoryCache()
.BuildServiceProvider();
var logger = services.GetRequiredService<
ILogger<DatabaseBackupService>>();
@@ -224,10 +226,19 @@ public sealed class OperationsControllerTests
configuration,
environment,
logger);
var performance = new PerformanceReportService(
new HttpClient(),
services.GetRequiredService<
Microsoft.Extensions.Caching.Memory.IMemoryCache>(),
new PerformanceReportingOptions(),
new ObservabilityOptions(),
services.GetRequiredService<
ILogger<PerformanceReportService>>());
var controller = new OperationsController(
db,
health,
backups,
performance,
operationsOptions);
return new OperationsFixture(services, db, controller, backups);
}
@@ -0,0 +1,188 @@
using System.Net;
using System.Text;
using Jiaowu.Api.Infrastructure.Observability;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging.Abstractions;
namespace Jiaowu.Api.Tests;
public sealed class PerformanceReportServiceTests
{
[Fact]
public async Task Configured_source_returns_cached_native_report()
{
var handler = new PrometheusHandler();
using var httpClient = new HttpClient(handler);
using var cache = new MemoryCache(new MemoryCacheOptions());
var service = new PerformanceReportService(
httpClient,
cache,
new PerformanceReportingOptions
{
Enabled = true,
PrometheusBaseUrl = "https://prometheus.test/",
BearerToken = "read-only-token",
GrafanaBaseUrl = "https://grafana.test/",
CacheSeconds = 30
},
new ObservabilityOptions { ServiceName = "jiaowu-api" },
NullLogger<PerformanceReportService>.Instance);
var first = await service.GetAsync("1h", CancellationToken.None);
var second = await service.GetAsync("1h", CancellationToken.None);
Assert.Equal("ready", first.Status);
Assert.Equal("prometheus", first.DataSource);
Assert.Equal("https://grafana.test/", first.DashboardUrl);
Assert.NotNull(first.Headline);
Assert.Equal(5, first.Headline.RequestCount);
Assert.Equal(2, first.Timeline.Count);
Assert.Equal(
"/api/timetables/classes/{classId}",
Assert.Single(first.Endpoints).Name);
Assert.Equal(
"Timetable.LoadScheduleEntries",
Assert.Single(first.DatabaseQueries).Name);
Assert.Same(first, second);
Assert.Equal(14, handler.RequestCount);
Assert.True(handler.AllRequestsAuthenticated);
}
[Fact]
public async Task Missing_source_returns_directed_empty_state()
{
using var cache = new MemoryCache(new MemoryCacheOptions());
var service = new PerformanceReportService(
new HttpClient(new RejectingHandler()),
cache,
new PerformanceReportingOptions(),
new ObservabilityOptions(),
NullLogger<PerformanceReportService>.Instance);
var report = await service.GetAsync("24h", CancellationToken.None);
Assert.Equal("not_configured", report.Status);
Assert.Contains("Prometheus", report.Detail);
Assert.Empty(report.Timeline);
}
[Fact]
public async Task Unsupported_range_is_rejected_before_querying_source()
{
using var cache = new MemoryCache(new MemoryCacheOptions());
var service = new PerformanceReportService(
new HttpClient(new RejectingHandler()),
cache,
new PerformanceReportingOptions(),
new ObservabilityOptions(),
NullLogger<PerformanceReportService>.Instance);
await Assert.ThrowsAsync<ArgumentOutOfRangeException>(() =>
service.GetAsync("30d", CancellationToken.None));
await Assert.ThrowsAsync<ArgumentOutOfRangeException>(() =>
service.GetAsync(null, CancellationToken.None));
}
[Fact]
public async Task Source_timeout_returns_unavailable_report()
{
using var cache = new MemoryCache(new MemoryCacheOptions());
var service = new PerformanceReportService(
new HttpClient(new TimeoutHandler()),
cache,
new PerformanceReportingOptions
{
Enabled = true,
PrometheusBaseUrl = "https://prometheus.test/"
},
new ObservabilityOptions(),
NullLogger<PerformanceReportService>.Instance);
var report = await service.GetAsync("1h", CancellationToken.None);
Assert.Equal("unavailable", report.Status);
Assert.Contains("暂时不可用", report.Detail);
}
private sealed class PrometheusHandler : HttpMessageHandler
{
private int requestCount;
private int authenticatedCount;
public int RequestCount => requestCount;
public bool AllRequestsAuthenticated =>
authenticatedCount == requestCount;
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
Interlocked.Increment(ref requestCount);
if (request.Headers.Authorization?.Scheme == "Bearer" &&
request.Headers.Authorization.Parameter == "read-only-token")
{
Interlocked.Increment(ref authenticatedCount);
}
var isRange = request.RequestUri!.AbsolutePath.EndsWith(
"/query_range",
StringComparison.Ordinal);
var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var json = isRange
? $$"""
{
"status": "success",
"data": {
"resultType": "matrix",
"result": [{
"metric": {},
"values": [
[{{now - 60}}, "2"],
[{{now}}, "3"]
]
}]
}
}
"""
: $$"""
{
"status": "success",
"data": {
"resultType": "vector",
"result": [{
"metric": {
"http_route": "/api/timetables/classes/{classId}",
"db_query_name": "Timetable.LoadScheduleEntries"
},
"value": [{{now}}, "5"]
}]
}
}
""";
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(
json,
Encoding.UTF8,
"application/json")
});
}
}
private sealed class RejectingHandler : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken) =>
throw new InvalidOperationException(
"未配置时不应访问外部数据源。");
}
private sealed class TimeoutHandler : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken) =>
throw new TaskCanceledException("Prometheus query timed out.");
}
}
@@ -32,40 +32,41 @@ public sealed class SchedulePublishJobProcessorTests
Assert.Equal(SchedulePlanStatus.Draft, result.PlanStatus);
Assert.Null(result.ActiveAcademicTermId);
Assert.Equal("检查未通过", result.CurrentStep);
Assert.Contains("尚未达到每周 2 个普通排课学时", result.ErrorMessage);
Assert.Contains("理论课应安排 32 学时,当前已安排 16 学时", result.ErrorMessage);
Assert.Null(result.PublishedAt);
}
[Fact]
public async Task Processor_excludes_practice_hours_for_existing_tasks()
public async Task Processor_requires_experiment_hours_in_regular_schedule()
{
var result = await RunPublishAsync(
weeklyHours: 2,
scheduledHours: 1,
practiceHours: 16);
practiceHours: 16,
experimentScheduledHours: 1);
Assert.Equal(SchedulePublishJobStatus.Succeeded, result.JobStatus);
Assert.Equal(SchedulePlanStatus.Published, result.PlanStatus);
}
[Fact]
public async Task Processor_rejects_practice_hours_already_added_to_draft()
public async Task Processor_rejects_missing_experiment_hours()
{
var result = await RunPublishAsync(
weeklyHours: 2,
scheduledHours: 2,
scheduledHours: 1,
practiceHours: 16);
Assert.Equal(SchedulePublishJobStatus.Failed, result.JobStatus);
Assert.Equal(SchedulePlanStatus.Draft, result.PlanStatus);
Assert.Contains("普通课表应为 1 学时", result.ErrorMessage);
Assert.Contains("删除已包含的实践学时", result.ErrorMessage);
Assert.Contains("实验课应安排 16 学时,当前已安排 0 学时", result.ErrorMessage);
}
private static async Task<PublishResult> RunPublishAsync(
int weeklyHours,
int scheduledHours,
int practiceHours = 0)
int practiceHours = 0,
int experimentScheduledHours = 0)
{
var databasePath = Path.Combine(
Path.GetTempPath(),
@@ -97,6 +98,21 @@ public sealed class SchedulePublishJobProcessorTests
EndDate = new DateOnly(2027, 1, 15)
};
var college = new College { Code = "PUB", Name = "发布测试学院" };
var campus = new Campus { Code = "PUB-CAMPUS", Name = "发布测试校区" };
var building = new Building
{
Code = "PUB-BUILDING",
Name = "实验楼",
Campus = campus
};
var laboratory = new Classroom
{
Code = "PUB-LAB",
Name = "发布测试实验室",
Building = building,
Capacity = 80,
RoomType = "实验室"
};
var course = new Course
{
Code = "PUB-01",
@@ -135,6 +151,21 @@ public sealed class SchedulePublishJobProcessorTests
EndWeek = 16,
WeekPattern = WeekPattern.All
});
if (experimentScheduledHours > 0)
{
plan.Entries.Add(new ScheduleEntry
{
TeachingTask = task,
Kind = ScheduleEntryKind.Experiment,
Classroom = laboratory,
DayOfWeek = 2,
StartPeriod = 1,
PeriodCount = experimentScheduledHours,
StartWeek = 1,
EndWeek = 16,
WeekPattern = WeekPattern.All
});
}
var job = new SchedulePublishJob
{
SchedulePlan = plan,
@@ -143,7 +174,16 @@ public sealed class SchedulePublishJobProcessorTests
CurrentStep = "等待后台检查"
};
jobId = job.Id;
db.AddRange(term, college, course, task, plan, job);
db.AddRange(
term,
college,
campus,
building,
laboratory,
course,
task,
plan,
job);
db.ScheduleTimeSlots.AddRange(
new ScheduleTimeSlot
{
@@ -189,7 +189,7 @@ public sealed class ScheduleSettingsControllerTests
});
Assert.Contains("测试教师", json);
Assert.Contains(classroom.Id.ToString(), json);
Assert.Contains("\"WeeklyHours\":3", json);
Assert.Contains("\"WeeklyHours\":4", json);
Assert.Contains("\"CoursePracticeHours\":16", json);
}
@@ -13,7 +13,7 @@ namespace Jiaowu.Api.Tests;
public sealed class SchedulesControllerTests
{
[Fact]
public async Task Manual_entry_rejects_hours_reserved_for_experiments()
public async Task Manual_entry_adds_experiment_hours_to_regular_schedule()
{
await using var connection = new SqliteConnection("Data Source=:memory:");
await connection.OpenAsync();
@@ -33,6 +33,21 @@ public sealed class SchedulesControllerTests
EndDate = new DateOnly(2027, 1, 17)
};
var college = new College { Code = "LAB", Name = "实验学院" };
var campus = new Campus { Code = "LAB-CAMPUS", Name = "实验校区" };
var building = new Building
{
Code = "LAB-BUILDING",
Name = "实验楼",
Campus = campus
};
var laboratory = new Classroom
{
Code = "LAB-201",
Name = "实验室 201",
Building = building,
Capacity = 40,
RoomType = "实验室"
};
var course = new Course
{
Code = "LAB-01",
@@ -71,7 +86,7 @@ public sealed class SchedulesControllerTests
EndWeek = 16,
WeekPattern = WeekPattern.All
});
db.AddRange(term, college, course, task, plan);
db.AddRange(term, college, campus, building, laboratory, course, task, plan);
db.ScheduleTimeSlots.AddRange(
new ScheduleTimeSlot
{
@@ -102,22 +117,22 @@ public sealed class SchedulesControllerTests
plan.Id,
new ScheduleEntryRequest(
task.Id,
null,
2,
laboratory.Id,
2,
1,
1,
1,
16,
WeekPattern.All,
null),
null,
ScheduleEntryKind.Experiment),
CancellationToken.None);
var problem = Assert.IsType<ObjectResult>(result);
var details = Assert.IsType<ValidationProblemDetails>(problem.Value);
Assert.Contains(
"实践学时请在实验管理中安排",
details.Detail);
Assert.Single(await db.ScheduleEntries.ToListAsync());
Assert.IsType<CreatedResult>(result);
var entries = await db.ScheduleEntries.OrderBy(x => x.Kind).ToListAsync();
Assert.Equal(2, entries.Count);
Assert.Equal(ScheduleEntryKind.Experiment, entries[1].Kind);
Assert.Equal(laboratory.Id, entries[1].ClassroomId);
}
[Fact]
@@ -0,0 +1,245 @@
using System.Text.Json;
using System.Security.Claims;
using Jiaowu.Api.Controllers;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
namespace Jiaowu.Api.Tests;
public sealed class SsoControllerTests
{
[Fact]
public async Task Bind_WithValidLocalCredentials_LinksKeycloakIdentityAndLogsIn()
{
await using var fixture = await BindingFixture.CreateAsync();
var code = new string('a', 32);
await fixture.StoreTicketAsync(code, "keycloak-subject", "external.name");
var result = await fixture.Controller.Bind(
new SsoBindRequest(code, fixture.User.UserName!, "LocalUser@123"),
CancellationToken.None);
var response = Assert.IsType<LoginResponse>(result.Value);
Assert.Equal("test-token", response.Token);
Assert.Equal(fixture.User.Id, response.User.Id);
var linkedUser = await fixture.UserManager.FindByLoginAsync(
SsoAuthSchemes.LoginProvider,
"keycloak-subject");
Assert.Equal(fixture.User.Id, linkedUser?.Id);
Assert.Null(await fixture.Cache.GetStringAsync($"sso:binding:{code}"));
}
[Fact]
public async Task Bind_WithWrongPassword_DoesNotLinkKeycloakIdentity()
{
await using var fixture = await BindingFixture.CreateAsync();
var code = new string('b', 32);
await fixture.StoreTicketAsync(code, "keycloak-subject", "external.name");
var result = await fixture.Controller.Bind(
new SsoBindRequest(code, fixture.User.UserName!, "WrongPassword@123"),
CancellationToken.None);
Assert.NotNull(result.Result);
Assert.Null(await fixture.UserManager.FindByLoginAsync(
SsoAuthSchemes.LoginProvider,
"keycloak-subject"));
var user = await fixture.UserManager.FindByIdAsync(fixture.User.Id.ToString());
Assert.Equal(1, user?.AccessFailedCount);
}
[Fact]
public async Task Account_ReportsCurrentKeycloakBindingAndConfiguredCallback()
{
await using var fixture = await BindingFixture.CreateAsync();
Assert.True((await fixture.UserManager.AddLoginAsync(
fixture.User,
new UserLoginInfo(
SsoAuthSchemes.LoginProvider,
"keycloak-subject",
"学校统一身份认证"))).Succeeded);
fixture.SignInController();
var result = await fixture.Controller.Account();
var response = Assert.IsType<SsoAccountResponse>(result.Value);
Assert.True(response.Enabled);
Assert.True(response.IsBound);
Assert.Equal(
"https://jiaowu.example.edu.cn/signin-keycloak",
response.CallbackUrl);
}
[Fact]
public async Task Unbind_WithCurrentPassword_RemovesOnlyKeycloakLogin()
{
await using var fixture = await BindingFixture.CreateAsync();
Assert.True((await fixture.UserManager.AddLoginAsync(
fixture.User,
new UserLoginInfo(
SsoAuthSchemes.LoginProvider,
"keycloak-subject",
"学校统一身份认证"))).Succeeded);
fixture.SignInController();
var result = await fixture.Controller.Unbind(
new SsoUnbindRequest("LocalUser@123"));
Assert.IsType<NoContentResult>(result);
Assert.Null(await fixture.UserManager.FindByLoginAsync(
SsoAuthSchemes.LoginProvider,
"keycloak-subject"));
Assert.True(await fixture.UserManager.CheckPasswordAsync(
fixture.User,
"LocalUser@123"));
}
[Theory]
[InlineData(null, "/dashboard")]
[InlineData("", "/dashboard")]
[InlineData("https://evil.example/path", "/dashboard")]
[InlineData("//evil.example/path", "/dashboard")]
[InlineData("/grades?term=2026-1", "/grades?term=2026-1")]
public void NormalizeReturnUrl_AllowsOnlyLocalApplicationPaths(
string? value,
string expected)
{
Assert.Equal(expected, SsoController.NormalizeReturnUrl(value));
}
private sealed class BindingFixture : IAsyncDisposable
{
private readonly SqliteConnection _connection;
private readonly ServiceProvider _provider;
private BindingFixture(
SqliteConnection connection,
ServiceProvider provider,
ApplicationUser user,
UserManager<ApplicationUser> userManager,
IDistributedCache cache,
SsoController controller)
{
_connection = connection;
_provider = provider;
User = user;
UserManager = userManager;
Cache = cache;
Controller = controller;
}
public ApplicationUser User { get; }
public UserManager<ApplicationUser> UserManager { get; }
public IDistributedCache Cache { get; }
public SsoController Controller { get; }
public void SignInController()
{
Controller.ControllerContext = new ControllerContext
{
HttpContext = new DefaultHttpContext
{
User = new ClaimsPrincipal(new ClaimsIdentity(
[new Claim(ClaimTypes.NameIdentifier, User.Id.ToString())],
"test"))
}
};
}
public static async Task<BindingFixture> CreateAsync()
{
var connection = new SqliteConnection("Data Source=:memory:");
await connection.OpenAsync();
var services = new ServiceCollection();
services.AddLogging();
services.AddDistributedMemoryCache();
services.AddDbContext<AppDbContext>(options => options.UseSqlite(connection));
services
.AddIdentityCore<ApplicationUser>()
.AddRoles<ApplicationRole>()
.AddEntityFrameworkStores<AppDbContext>();
var provider = services.BuildServiceProvider();
var db = provider.GetRequiredService<AppDbContext>();
await db.Database.EnsureCreatedAsync();
var userManager = provider.GetRequiredService<UserManager<ApplicationUser>>();
var user = new ApplicationUser
{
UserName = "local.user",
DisplayName = "本地用户",
IsEnabled = true,
LockoutEnabled = true
};
Assert.True((await userManager.CreateAsync(user, "LocalUser@123")).Succeeded);
var cache = provider.GetRequiredService<IDistributedCache>();
var controller = new SsoController(
userManager,
new StubAuthSessionService(),
cache,
Options.Create(new SsoOptions
{
Enabled = true,
DisplayName = "学校统一身份认证",
CallbackUrl = "https://jiaowu.example.edu.cn/signin-keycloak"
}),
NullLogger<SsoController>.Instance);
return new BindingFixture(
connection,
provider,
user,
userManager,
cache,
controller);
}
public Task StoreTicketAsync(
string code,
string subject,
string externalUserName) =>
Cache.SetStringAsync(
$"sso:binding:{code}",
JsonSerializer.Serialize(
new SsoBindingTicket(subject, externalUserName)));
public async ValueTask DisposeAsync()
{
await _provider.DisposeAsync();
await _connection.DisposeAsync();
}
}
private sealed class StubAuthSessionService : IAuthSessionService
{
public Task<AuthSessionResult> CreateAsync(
ApplicationUser user,
IEnumerable<string> roles,
AuthenticationClientType clientType,
CancellationToken cancellationToken = default) =>
Task.FromResult(new AuthSessionResult(
"test-token",
DateTime.UtcNow.AddMinutes(10),
"test-refresh-token-value-with-sufficient-length",
DateTime.UtcNow.AddMinutes(30),
user,
roles.ToList()));
public Task<AuthSessionResult?> RefreshAsync(
string refreshToken,
CancellationToken cancellationToken = default) => Task.FromResult<AuthSessionResult?>(null);
public Task RevokeAsync(
string refreshToken,
CancellationToken cancellationToken = default) => Task.CompletedTask;
}
}
@@ -0,0 +1,153 @@
using Jiaowu.Api.Controllers;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Caching;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace Jiaowu.Api.Tests;
public sealed class StudentProfileControllerTests
{
[Fact]
public async Task Student_can_update_profile_without_changing_identity_or_registration()
{
await using var connection = new SqliteConnection("Data Source=:memory:");
await connection.OpenAsync();
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlite(connection)
.Options;
await using var db = new AppDbContext(options);
await db.Database.EnsureCreatedAsync();
var user = new ApplicationUser
{
Id = Guid.NewGuid(),
UserName = "2026001",
NormalizedUserName = "2026001",
DisplayName = "原姓名"
};
var college = new College { Code = "CS", Name = "计算机学院" };
var major = new Major
{
Code = "080901",
Name = "计算机科学与技术",
CollegeId = college.Id,
DegreeType = "工学学士"
};
var administrativeClass = new AdministrativeClass
{
Code = "CS2026-01",
Name = "计科 2026-1 班",
MajorId = major.Id,
Grade = 2026
};
var student = new Student
{
StudentNumber = "2026001",
Name = "原姓名",
UserId = user.Id,
AdministrativeClassId = administrativeClass.Id,
EnrollmentYear = 2026,
EnrollmentDate = new DateOnly(2026, 9, 1),
Status = StudentStatus.Active
};
db.AddRange(user, college);
await db.SaveChangesAsync();
db.Add(major);
await db.SaveChangesAsync();
db.Add(administrativeClass);
await db.SaveChangesAsync();
db.Add(student);
await db.SaveChangesAsync();
var controller = new StudentProfileController(
db,
new StudentDataScope(user.Id),
new NoOpCache());
var request = new StudentProfileUpdateRequest(
Gender.Female,
new DateOnly(2008, 3, 12),
" Alice ",
"370000000000000000",
"中国",
"汉族",
"共青团员",
"山东济南",
"户籍地址",
"现住地址",
"250000",
"13800000000",
"student@example.edu.cn",
"123456",
"alice-wechat",
"家长",
"母亲",
"13900000000",
"听力支持, 走读",
"上课时需要靠前座位",
"个人简介");
Assert.IsType<NoContentResult>(await controller.Update(
request,
CancellationToken.None));
db.ChangeTracker.Clear();
var updated = await db.Students.SingleAsync();
Assert.Equal("2026001", updated.StudentNumber);
Assert.Equal("原姓名", updated.Name);
Assert.Equal(administrativeClass.Id, updated.AdministrativeClassId);
Assert.Equal(StudentStatus.Active, updated.Status);
Assert.Equal("Alice", updated.EnglishName);
Assert.Equal("13800000000", updated.Phone);
Assert.Equal("听力支持, 走读", updated.SpecialTags);
Assert.Equal("上课时需要靠前座位", updated.SpecialNeeds);
}
[Fact]
public async Task Missing_linked_student_returns_not_found()
{
await using var connection = new SqliteConnection("Data Source=:memory:");
await connection.OpenAsync();
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlite(connection)
.Options;
await using var db = new AppDbContext(options);
await db.Database.EnsureCreatedAsync();
var controller = new StudentProfileController(
db,
new StudentDataScope(Guid.NewGuid()),
new NoOpCache());
var result = await controller.Get(CancellationToken.None);
Assert.IsType<NotFoundResult>(result.Result);
}
private sealed class NoOpCache : IAppCache
{
public Task<T> GetOrCreateAsync<T>(
string key,
Func<CancellationToken, Task<T>> factory,
AppCacheProfile profile,
IReadOnlyCollection<string> tags,
CancellationToken cancellationToken) => factory(cancellationToken);
public ValueTask RemoveByTagAsync(
string tag,
CancellationToken cancellationToken = default) => ValueTask.CompletedTask;
}
private sealed class StudentDataScope(Guid userId) : ICurrentUserDataScope
{
public CurrentUserScope Current { get; } = new(
userId,
"测试学生",
null,
DataScope.Self,
new HashSet<string>([SystemRoles.Student]));
}
}
@@ -0,0 +1,20 @@
using System.Reflection;
using Jiaowu.Api.Controllers;
namespace Jiaowu.Api.Tests;
public sealed class SystemControllerTests
{
[Fact]
public void GetVersion_ReturnsConfiguredApplicationVersion()
{
var response = new SystemController().GetVersion();
var configuredVersion = typeof(SystemController).Assembly
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()!
.InformationalVersion
.Split('+', 2)[0];
Assert.Equal(configuredVersion, response.Version);
Assert.Matches(@"^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$", response.Version);
}
}
@@ -32,7 +32,7 @@ public sealed class TeachingTaskHoursTests
}
[Fact]
public void Standard_schedule_excludes_practice_hours()
public void Standard_schedule_includes_theory_and_experiment_hours()
{
var course = new Course
{
@@ -52,12 +52,12 @@ public sealed class TeachingTaskHoursTests
16,
out var weeklyHours));
Assert.Equal(3, weeklyHours);
Assert.Null(TeachingTaskHours.Validate(course, 1, 16, 3));
Assert.Null(TeachingTaskHours.Validate(course, 1, 16, 4));
var result = TeachingTaskHours.Validate(course, 1, 16, 4);
var result = TeachingTaskHours.Validate(course, 1, 16, 3);
Assert.NotNull(result);
Assert.Contains("普通课表应安排 48 学时", result);
Assert.Contains("实践学时 16", result);
Assert.Contains("理论课和实验课均应进入课表", result);
Assert.Contains("共 48 学时", result);
}
[Fact]
@@ -79,8 +79,6 @@ public sealed class TeachingTaskHoursTests
16,
1,
TeachingTaskSchedulingMode.Flexible));
Assert.Contains(
"无需进入普通课表",
TeachingTaskHours.Validate(course, 1, 16, 1)!);
Assert.Null(TeachingTaskHours.Validate(course, 1, 16, 1));
}
}
@@ -0,0 +1,123 @@
using ClosedXML.Excel;
using Jiaowu.Api.Controllers;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace Jiaowu.Api.Tests;
public sealed class TeachingTaskRosterProfileTests
{
[Fact]
public async Task Assigned_teacher_receives_contact_and_special_fields_in_roster_and_export()
{
await using var connection = new SqliteConnection("Data Source=:memory:");
await connection.OpenAsync();
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlite(connection)
.Options;
await using var db = new AppDbContext(options);
await db.Database.EnsureCreatedAsync();
var teacherUser = User("T001", "任课教师");
var studentUser = User("S001", "学生甲");
var college = new College { Code = "CS", Name = "计算机学院" };
var major = new Major
{
Code = "080901", Name = "计算机科学与技术",
CollegeId = college.Id, DegreeType = "工学学士"
};
var administrativeClass = new AdministrativeClass
{
Code = "CS2026-01", Name = "计科一班", MajorId = major.Id, Grade = 2026
};
var teacher = new Teacher
{
TeacherNumber = "T001", Name = "任课教师", CollegeId = college.Id,
UserId = teacherUser.Id
};
var student = new Student
{
StudentNumber = "S001", Name = "学生甲", UserId = studentUser.Id,
AdministrativeClassId = administrativeClass.Id,
EnrollmentYear = 2026, EnrollmentDate = new DateOnly(2026, 9, 1),
Phone = "13800000000", Email = "s@example.edu.cn", WeChat = "student-wechat",
EmergencyContactName = "家长", EmergencyContactRelationship = "母亲",
EmergencyContactPhone = "13900000000", SpecialTags = "走读",
SpecialNeeds = "需留意交通延误"
};
var term = new AcademicTerm
{
Code = "2026-1", Name = "2026-2027-1", AcademicYear = "2026-2027",
Season = TermSeason.Autumn, StartDate = new DateOnly(2026, 9, 1),
EndDate = new DateOnly(2027, 1, 20)
};
var course = new Course
{
Code = "CS101", Name = "程序设计", CollegeId = college.Id,
Credits = 4, TotalHours = 64, LectureHours = 48, PracticeHours = 16,
Nature = CourseNature.MajorRequired,
AssessmentMethod = AssessmentMethod.Examination
};
db.AddRange(teacherUser, studentUser, college);
await db.SaveChangesAsync();
db.AddRange(major, teacher, term, course);
await db.SaveChangesAsync();
db.Add(administrativeClass);
await db.SaveChangesAsync();
db.Add(student);
await db.SaveChangesAsync();
var task = new TeachingTask
{
TaskNumber = "2026-CS101-01", Name = "程序设计教学班",
AcademicTermId = term.Id, CourseId = course.Id, Capacity = 40,
Status = TeachingTaskStatus.Published,
Teachers = [new TeachingTaskTeacher { TeacherId = teacher.Id }],
Classes = [new TeachingTaskClass { AdministrativeClassId = administrativeClass.Id }]
};
db.Add(task);
await db.SaveChangesAsync();
var controller = new CourseSelectionsController(
db,
new TeacherDataScope(teacherUser.Id));
var rosterResult = Assert.IsType<OkObjectResult>(
await controller.GetTeachingTaskRoster(task.Id, CancellationToken.None));
var students = Assert.IsAssignableFrom<System.Collections.IEnumerable>(
rosterResult.Value!.GetType().GetProperty("Students")!.GetValue(rosterResult.Value));
var row = Assert.Single(students.Cast<object>());
Assert.Equal("13800000000", Property(row, "Phone"));
Assert.Equal("走读", Property(row, "SpecialTags"));
Assert.Equal("需留意交通延误", Property(row, "SpecialNeeds"));
var export = Assert.IsType<FileContentResult>(
await controller.ExportTeachingTaskRoster(task.Id, CancellationToken.None));
using var stream = new MemoryStream(export.FileContents);
using var workbook = new XLWorkbook(stream);
var sheet = workbook.Worksheet("教学班名单");
Assert.Equal("联系电话", sheet.Cell(1, 5).GetString());
Assert.Equal("特殊标记", sheet.Cell(1, 11).GetString());
Assert.Equal("13800000000", sheet.Cell(2, 5).GetString());
Assert.Equal("走读", sheet.Cell(2, 11).GetString());
}
private static string? Property(object value, string name) =>
value.GetType().GetProperty(name)!.GetValue(value)?.ToString();
private static ApplicationUser User(string userName, string displayName) => new()
{
Id = Guid.NewGuid(), UserName = userName,
NormalizedUserName = userName.ToUpperInvariant(), DisplayName = displayName
};
private sealed class TeacherDataScope(Guid userId) : ICurrentUserDataScope
{
public CurrentUserScope Current { get; } = new(
userId, "任课教师", null, DataScope.Self,
new HashSet<string>([SystemRoles.Teacher]));
}
}
+6 -2
View File
@@ -25,12 +25,16 @@ public sealed class TokenServiceTests
};
var service = new TokenService(options);
var token = new JwtSecurityTokenHandler().ReadJwtToken(
service.Create(user, [SystemRoles.Teacher]));
var result = service.Create(user, [SystemRoles.Teacher]);
var token = new JwtSecurityTokenHandler().ReadJwtToken(result.Token);
Assert.Contains(token.Claims, x =>
x.Type == ClaimTypes.Role && x.Value == SystemRoles.Teacher);
Assert.Contains(token.Claims, x =>
x.Type == ClaimTypes.Name && x.Value == "陈老师");
Assert.InRange(
result.ExpiresAt,
DateTime.UtcNow.AddMinutes(9),
DateTime.UtcNow.AddMinutes(11));
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "web",
"private": true,
"version": "1.0.0",
"version": "2.3.0-rc4",
"type": "module",
"scripts": {
"dev": "vite",
+2
View File
@@ -1,8 +1,10 @@
<script setup lang="ts">
import SiteFooter from './components/SiteFooter.vue'
import SmartLaunchScreen from './components/SmartLaunchScreen.vue'
</script>
<template>
<SmartLaunchScreen />
<RouterView />
<SiteFooter />
</template>
+39 -6
View File
@@ -1,23 +1,56 @@
import axios from 'axios'
import { goLogin } from '../utils/navigate'
import {
authStorageKeys,
clearAuthSession,
markActivity,
refreshAuthSession,
refreshIfNeeded,
} from '../auth/session'
const http = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL ?? '/api',
timeout: 15000,
})
http.interceptors.request.use((config) => {
const token = localStorage.getItem('jiaowu_token')
http.interceptors.request.use(async (config) => {
const isAuthenticationRequest =
config.url?.endsWith('/auth/login') ||
config.url?.endsWith('/auth/refresh') ||
config.url?.endsWith('/auth/logout') ||
config.url?.endsWith('/auth/sso/exchange') ||
config.url?.endsWith('/auth/sso/bind')
if (!isAuthenticationRequest) {
const activeToken = await refreshIfNeeded(true)
if (activeToken) markActivity()
}
const token = localStorage.getItem(authStorageKeys.token)
if (token) config.headers.Authorization = `Bearer ${token}`
return config
})
http.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401 && !error.config?.url?.endsWith('/auth/login')) {
localStorage.removeItem('jiaowu_token')
localStorage.removeItem('jiaowu_user')
async (error) => {
const isAuthenticationRequest =
error.config?.url?.endsWith('/auth/login') ||
error.config?.url?.endsWith('/auth/refresh') ||
error.config?.url?.endsWith('/auth/logout') ||
error.config?.url?.endsWith('/auth/sso/exchange') ||
error.config?.url?.endsWith('/auth/sso/bind')
const retryableConfig = error.config as
(typeof error.config & { _jiaowuRetried?: boolean }) | undefined
if (error.response?.status === 401 && !isAuthenticationRequest &&
!retryableConfig?._jiaowuRetried) {
const token = await refreshAuthSession()
if (token && retryableConfig) {
retryableConfig._jiaowuRetried = true
retryableConfig.headers.Authorization = `Bearer ${token}`
return http.request(retryableConfig)
}
}
if (error.response?.status === 401 && !isAuthenticationRequest) {
clearAuthSession()
goLogin(location.pathname + location.search + location.hash)
}
return Promise.reject(error)
+167
View File
@@ -0,0 +1,167 @@
import axios from 'axios'
import { Capacitor } from '@capacitor/core'
const TOKEN_KEY = 'jiaowu_token'
const REFRESH_TOKEN_KEY = 'jiaowu_refresh_token'
const ACCESS_EXPIRES_KEY = 'jiaowu_access_expires_at'
const SESSION_EXPIRES_KEY = 'jiaowu_session_expires_at'
const USER_KEY = 'jiaowu_user'
const LAST_ACTIVITY_KEY = 'jiaowu_last_activity_at'
const WEB_IDLE_MILLISECONDS = 30 * 60 * 1000
const REFRESH_AHEAD_MILLISECONDS = 60 * 1000
const WEB_SLIDING_TOUCH_MILLISECONDS = 60 * 1000
export interface AuthSessionPayload {
token: string
accessTokenExpiresAt: string
refreshToken: string
sessionExpiresAt: string
user: unknown
}
export const isNativeApp = () => Capacitor.isNativePlatform()
export function saveAuthSession(payload: AuthSessionPayload, recordActivity = true) {
localStorage.setItem(TOKEN_KEY, payload.token)
localStorage.setItem(REFRESH_TOKEN_KEY, payload.refreshToken)
localStorage.setItem(ACCESS_EXPIRES_KEY, payload.accessTokenExpiresAt)
localStorage.setItem(SESSION_EXPIRES_KEY, payload.sessionExpiresAt)
localStorage.setItem(USER_KEY, JSON.stringify(payload.user))
if (recordActivity) markActivity()
window.dispatchEvent(new Event('mingxu-auth-changed'))
}
export function clearAuthSession(notifyExpired = false) {
localStorage.removeItem(TOKEN_KEY)
localStorage.removeItem(REFRESH_TOKEN_KEY)
localStorage.removeItem(ACCESS_EXPIRES_KEY)
localStorage.removeItem(SESSION_EXPIRES_KEY)
localStorage.removeItem(USER_KEY)
localStorage.removeItem(LAST_ACTIVITY_KEY)
window.dispatchEvent(new Event('mingxu-auth-changed'))
if (notifyExpired) window.dispatchEvent(new Event('mingxu-session-expired'))
}
export function markActivity() {
localStorage.setItem(LAST_ACTIVITY_KEY, String(Date.now()))
}
export function hasExceededWebIdleTimeout(now = Date.now()) {
if (isNativeApp()) return false
const lastActivity = Number(localStorage.getItem(LAST_ACTIVITY_KEY) ?? 0)
return lastActivity > 0 && now - lastActivity >= WEB_IDLE_MILLISECONDS
}
export function hasLocallyExpired(now = Date.now()) {
const sessionExpiresAt = Date.parse(localStorage.getItem(SESSION_EXPIRES_KEY) ?? '')
return hasExceededWebIdleTimeout(now) ||
(Number.isFinite(sessionExpiresAt) && sessionExpiresAt <= now)
}
let refreshPromise: Promise<string | null> | null = null
export function refreshAuthSession(): Promise<string | null> {
if (refreshPromise) return refreshPromise
const refreshToken = localStorage.getItem(REFRESH_TOKEN_KEY)
if (!refreshToken || hasLocallyExpired()) {
clearAuthSession(true)
return Promise.resolve(null)
}
refreshPromise = axios.post<AuthSessionPayload>(
`${import.meta.env.VITE_API_BASE_URL ?? '/api'}/auth/refresh`,
{ refreshToken },
{ timeout: 15000 },
).then(({ data }) => {
saveAuthSession(data, false)
return data.token
}).catch((error: unknown) => {
const currentRefreshToken = localStorage.getItem(REFRESH_TOKEN_KEY)
if (currentRefreshToken && currentRefreshToken !== refreshToken) {
return localStorage.getItem(TOKEN_KEY)
}
if (axios.isAxiosError(error) &&
error.response &&
[400, 401, 403].includes(error.response.status)) {
clearAuthSession(true)
return null
}
throw error
}).finally(() => {
refreshPromise = null
})
return refreshPromise
}
export async function refreshIfNeeded(isCurrentRequestActivity = false) {
const token = localStorage.getItem(TOKEN_KEY)
if (!token) return null
if (hasLocallyExpired()) {
clearAuthSession(true)
return null
}
const expiresAt = Date.parse(localStorage.getItem(ACCESS_EXPIRES_KEY) ?? '')
const sessionExpiresAt = Date.parse(localStorage.getItem(SESSION_EXPIRES_KEY) ?? '')
const lastActivity = Number(localStorage.getItem(LAST_ACTIVITY_KEY) ?? 0)
const now = Date.now()
const hasRecentWebActivity = !isNativeApp() &&
(isCurrentRequestActivity || now - lastActivity <= WEB_SLIDING_TOUCH_MILLISECONDS)
const webSessionNeedsSlidingTouch = hasRecentWebActivity &&
Number.isFinite(sessionExpiresAt) &&
sessionExpiresAt - now <= WEB_IDLE_MILLISECONDS - WEB_SLIDING_TOUCH_MILLISECONDS
if (!Number.isFinite(expiresAt) ||
expiresAt - now <= REFRESH_AHEAD_MILLISECONDS ||
webSessionNeedsSlidingTouch) {
return refreshAuthSession()
}
return token
}
export function initializeAuthSession() {
if (!localStorage.getItem(TOKEN_KEY)) return
if (hasLocallyExpired()) {
clearAuthSession(true)
return
}
let lastActivityWrite = 0
const recordActivity = () => {
const now = Date.now()
if (now - lastActivityWrite < 5000) return
lastActivityWrite = now
markActivity()
}
const activityEvents: Array<keyof WindowEventMap> = [
'pointerdown',
'keydown',
'touchstart',
'scroll',
]
activityEvents.forEach(event =>
window.addEventListener(event, recordActivity, { passive: true }))
window.setInterval(() => {
if (!localStorage.getItem(TOKEN_KEY)) return
if (hasLocallyExpired()) {
clearAuthSession(true)
return
}
if (document.visibilityState === 'visible') {
void refreshIfNeeded().catch(() => undefined)
}
}, 30000)
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') {
void refreshIfNeeded(true).catch(() => undefined)
}
})
window.addEventListener('online', () =>
void refreshIfNeeded(true).catch(() => undefined))
}
export const authStorageKeys = {
token: TOKEN_KEY,
refreshToken: REFRESH_TOKEN_KEY,
user: USER_KEY,
}
+3
View File
@@ -42,6 +42,7 @@ declare module 'vue' {
ElResult: typeof import('element-plus/es')['ElResult']
ElSegmented: typeof import('element-plus/es')['ElSegmented']
ElSelect: typeof import('element-plus/es')['ElSelect']
ElSkeleton: typeof import('element-plus/es')['ElSkeleton']
ElSlider: typeof import('element-plus/es')['ElSlider']
ElSubMenu: typeof import('element-plus/es')['ElSubMenu']
ElSwitch: typeof import('element-plus/es')['ElSwitch']
@@ -52,9 +53,11 @@ declare module 'vue' {
ElTag: typeof import('element-plus/es')['ElTag']
ElTimeSelect: typeof import('element-plus/es')['ElTimeSelect']
ElUpload: typeof import('element-plus/es')['ElUpload']
PerformanceReportPanel: typeof import('./components/PerformanceReportPanel.vue')['default']
RichMessageContent: typeof import('./components/RichMessageContent.vue')['default']
RouterLink: typeof import('vue-router')['RouterLink']
RouterView: typeof import('vue-router')['RouterView']
SiteFooter: typeof import('./components/SiteFooter.vue')['default']
SmartLaunchScreen: typeof import('./components/SmartLaunchScreen.vue')['default']
}
export interface GlobalDirectives {
@@ -0,0 +1,762 @@
<script setup lang="ts">
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import { Connection, RefreshRight, TopRight } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts/core'
import { LineChart } from 'echarts/charts'
import {
GridComponent,
LegendComponent,
TooltipComponent,
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import http, { apiErrorMessage } from '../api/http'
echarts.use([
LineChart,
GridComponent,
LegendComponent,
TooltipComponent,
CanvasRenderer,
])
type ReportStatus = 'ready' | 'not_configured' | 'unavailable'
type ReportRange = '15m' | '1h' | '24h' | '7d'
interface PerformanceHeadline {
requestCount?: number
requestP95Milliseconds?: number
serverErrorRatePercent?: number
databaseP95Milliseconds?: number
slowDatabaseCommandCount?: number
failedDatabaseCommandCount?: number
}
interface TimelinePoint {
timestamp: string
requestsPerSecond?: number
requestP95Milliseconds?: number
}
interface RankingItem {
name: string
p95Milliseconds?: number
requestCount?: number
exceptionalCount?: number
}
interface PerformanceReport {
status: ReportStatus
range: ReportRange
from?: string
to?: string
generatedAt: string
dataSource: string
dashboardUrl?: string
detail?: string
headline?: PerformanceHeadline
timeline: TimelinePoint[]
endpoints: RankingItem[]
databaseQueries: RankingItem[]
}
const rangeOptions: { value: ReportRange; label: string }[] = [
{ value: '15m', label: '15 分钟' },
{ value: '1h', label: '1 小时' },
{ value: '24h', label: '24 小时' },
{ value: '7d', label: '7 天' },
]
const range = ref<ReportRange>('1h')
const loading = ref(true)
const report = ref<PerformanceReport>()
const chartElement = ref<HTMLElement>()
let chart: echarts.ECharts | undefined
let resizeObserver: ResizeObserver | undefined
const hasSamples = computed(() =>
Boolean(report.value?.headline) &&
(report.value?.timeline.length ?? 0) > 0,
)
const operatingNote = computed(() => {
const headline = report.value?.headline
if (!headline) return '等待指标样本'
if ((headline.failedDatabaseCommandCount ?? 0) > 0)
return '存在失败的数据库命令'
if ((headline.serverErrorRatePercent ?? 0) >= 1)
return '服务端错误率需要关注'
if ((headline.slowDatabaseCommandCount ?? 0) > 0)
return '存在超过阈值的慢查询'
return '当前采样窗口内未见明显异常'
})
function formatNumber(value?: number, digits = 0) {
if (value == null || !Number.isFinite(value)) return '—'
return value.toLocaleString('zh-CN', {
maximumFractionDigits: digits,
minimumFractionDigits: digits,
})
}
function formatTime(value?: string) {
if (!value) return '—'
return new Date(value).toLocaleString('zh-CN', {
hour12: false,
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
})
}
function formatAxisTime(value: string) {
return new Date(value).toLocaleString('zh-CN', {
hour12: false,
month: range.value === '7d' ? '2-digit' : undefined,
day: range.value === '7d' ? '2-digit' : undefined,
hour: '2-digit',
minute: '2-digit',
})
}
function metricWidth(value?: number, rows: RankingItem[] = []) {
if (value == null || value <= 0) return '0%'
const maximum = Math.max(
...rows.map((row) => row.p95Milliseconds ?? 0),
value,
)
return `${Math.max(4, value / maximum * 100)}%`
}
async function loadReport() {
loading.value = true
try {
const { data } = await http.get<PerformanceReport>(
'/operations/performance',
{ params: { range: range.value } },
)
report.value = data
await nextTick()
renderChart()
} catch (error) {
report.value = {
status: 'unavailable',
range: range.value,
generatedAt: new Date().toISOString(),
dataSource: 'prometheus',
detail: apiErrorMessage(error),
timeline: [],
endpoints: [],
databaseQueries: [],
}
ElMessage.error(apiErrorMessage(error))
disposeChart()
} finally {
loading.value = false
}
}
function renderChart() {
disposeChart()
if (!chartElement.value || !report.value?.timeline.length) return
chart = echarts.init(chartElement.value)
const times = report.value.timeline.map((point) =>
formatAxisTime(point.timestamp),
)
chart.setOption({
animationDuration: 420,
color: ['#1f7468', '#b47722'],
grid: { left: 50, right: 54, top: 54, bottom: 38 },
legend: {
top: 4,
left: 0,
itemWidth: 18,
itemHeight: 3,
textStyle: {
color: '#53636d',
fontFamily: '"Cascadia Mono", Consolas, monospace',
fontSize: 10,
},
},
tooltip: {
trigger: 'axis',
backgroundColor: 'rgba(30, 41, 50, 0.94)',
borderWidth: 0,
textStyle: { color: '#fff', fontSize: 12 },
valueFormatter: (value: unknown) =>
typeof value === 'number' ? value.toFixed(2) : '—',
},
xAxis: {
type: 'category',
boundaryGap: false,
data: times,
axisLine: { lineStyle: { color: '#cbd4d7' } },
axisTick: { show: false },
axisLabel: { color: '#79878f', fontSize: 10, hideOverlap: true },
},
yAxis: [
{
type: 'value',
name: '请求 / 秒',
nameTextStyle: { color: '#63727b', fontSize: 10 },
splitLine: { lineStyle: { color: '#e8edef', type: 'dashed' } },
axisLabel: { color: '#79878f', fontSize: 10 },
},
{
type: 'value',
name: 'P95 / ms',
nameTextStyle: { color: '#8b6b36', fontSize: 10 },
splitLine: { show: false },
axisLabel: { color: '#8b6b36', fontSize: 10 },
},
],
series: [
{
name: '请求速率',
type: 'line',
smooth: 0.22,
symbol: 'none',
lineStyle: { width: 2 },
areaStyle: { color: 'rgba(31, 116, 104, 0.10)' },
data: report.value.timeline.map(
(point) => point.requestsPerSecond ?? null,
),
},
{
name: '接口 P95',
type: 'line',
yAxisIndex: 1,
smooth: 0.22,
symbol: 'none',
lineStyle: { width: 1.5 },
data: report.value.timeline.map(
(point) => point.requestP95Milliseconds ?? null,
),
},
],
})
resizeObserver = new ResizeObserver(() => chart?.resize())
resizeObserver.observe(chartElement.value)
}
function disposeChart() {
resizeObserver?.disconnect()
resizeObserver = undefined
chart?.dispose()
chart = undefined
}
watch(range, loadReport)
onMounted(loadReport)
onUnmounted(disposeChart)
</script>
<template>
<section class="performance-panel" aria-labelledby="performance-title">
<header class="performance-heading">
<div>
<span>PERFORMANCE RAIL / {{ report?.dataSource?.toUpperCase() || 'PROMETHEUS' }}</span>
<h3 id="performance-title">系统性能</h3>
<p>从接口进入数据库定位响应时间消耗在哪里</p>
</div>
<div class="performance-actions">
<div class="range-switch" aria-label="性能报表时间范围">
<button
v-for="item in rangeOptions"
:key="item.value"
type="button"
:class="{ active: range === item.value }"
:aria-pressed="range === item.value"
@click="range = item.value"
>
{{ item.label }}
</button>
</div>
<el-button
circle
:icon="RefreshRight"
:loading="loading"
aria-label="刷新性能报表"
@click="loadReport"
/>
</div>
</header>
<div v-if="loading && !report" class="performance-loading">
<el-skeleton :rows="5" animated />
</div>
<div
v-else-if="report?.status !== 'ready'"
:class="`is-${report?.status || 'unavailable'}`"
class="source-state"
>
<el-icon><Connection /></el-icon>
<div>
<strong>
{{ report?.status === 'not_configured' ? '等待连接性能数据源' : '性能数据暂不可用' }}
</strong>
<p>{{ report?.detail }}</p>
<small>
业务接口继续正常运行报表不会回退读取教务业务数据库
</small>
</div>
<a
v-if="report?.dashboardUrl"
:href="report.dashboardUrl"
target="_blank"
rel="noreferrer"
>
打开监控平台
<el-icon><TopRight /></el-icon>
</a>
</div>
<template v-else>
<div class="performance-strip">
<div class="strip-lead">
<span>采样结论</span>
<strong>{{ operatingNote }}</strong>
<small>
{{ formatTime(report.from) }} {{ formatTime(report.to) }}
</small>
</div>
<dl>
<div>
<dt>请求总量</dt>
<dd>{{ formatNumber(report.headline?.requestCount) }}</dd>
</div>
<div>
<dt>接口 P95</dt>
<dd>{{ formatNumber(report.headline?.requestP95Milliseconds, 1) }}<small>ms</small></dd>
</div>
<div>
<dt>5xx 比例</dt>
<dd>{{ formatNumber(report.headline?.serverErrorRatePercent, 2) }}<small>%</small></dd>
</div>
<div>
<dt>数据库 P95</dt>
<dd>{{ formatNumber(report.headline?.databaseP95Milliseconds, 1) }}<small>ms</small></dd>
</div>
<div>
<dt>慢查询</dt>
<dd>{{ formatNumber(report.headline?.slowDatabaseCommandCount) }}</dd>
</div>
<div>
<dt>查询失败</dt>
<dd>{{ formatNumber(report.headline?.failedDatabaseCommandCount) }}</dd>
</div>
</dl>
</div>
<div v-if="hasSamples" class="performance-rail">
<div ref="chartElement" class="rail-chart" aria-label="请求速率与接口 P95 趋势图" />
</div>
<div v-else class="samples-empty">
数据源已连接但该时间范围内尚未收到请求指标
</div>
<div class="rankings">
<article class="ranking-board">
<div class="ranking-heading">
<div>
<span>HTTP ROUTES</span>
<h4>接口耗时排行</h4>
</div>
<small>P95 / 请求量 / 5xx</small>
</div>
<div v-if="report.endpoints.length" class="ranking-list">
<div
v-for="(item, index) in report.endpoints"
:key="item.name"
class="ranking-row"
>
<b>{{ String(index + 1).padStart(2, '0') }}</b>
<div>
<strong :title="item.name">{{ item.name }}</strong>
<span>
<i
:style="{ width: metricWidth(item.p95Milliseconds, report.endpoints) }"
/>
</span>
</div>
<dl>
<dd>{{ formatNumber(item.p95Milliseconds, 1) }} ms</dd>
<dt>{{ formatNumber(item.requestCount) }} · {{ formatNumber(item.exceptionalCount) }} 错误</dt>
</dl>
</div>
</div>
<p v-else class="ranking-empty">该范围内没有接口指标</p>
</article>
<article class="ranking-board database-board">
<div class="ranking-heading">
<div>
<span>DATABASE QUERIES</span>
<h4>数据库查询排行</h4>
</div>
<small>P95 / 调用量 / 慢查询</small>
</div>
<div v-if="report.databaseQueries.length" class="ranking-list">
<div
v-for="(item, index) in report.databaseQueries"
:key="item.name"
class="ranking-row"
>
<b>{{ String(index + 1).padStart(2, '0') }}</b>
<div>
<strong :title="item.name">{{ item.name }}</strong>
<span>
<i
:style="{ width: metricWidth(item.p95Milliseconds, report.databaseQueries) }"
/>
</span>
</div>
<dl>
<dd>{{ formatNumber(item.p95Milliseconds, 1) }} ms</dd>
<dt>{{ formatNumber(item.requestCount) }} · {{ formatNumber(item.exceptionalCount) }} </dt>
</dl>
</div>
</div>
<p v-else class="ranking-empty">该范围内没有数据库指标</p>
</article>
</div>
<footer class="performance-foot">
<span>生成于 {{ formatTime(report.generatedAt) }} · 页面数据采用短时缓存</span>
<a
v-if="report.dashboardUrl"
:href="report.dashboardUrl"
target="_blank"
rel="noreferrer"
>
查看原始调用链
<el-icon><TopRight /></el-icon>
</a>
</footer>
</template>
</section>
</template>
<style scoped>
.performance-panel {
--ink: #1e2932;
--muted: #66747e;
--line: #d8dee1;
--paper: #f6f8f8;
--panel: #fff;
--signal: #1f7468;
--warning: #b47722;
--danger: #b1463e;
background: var(--panel);
border: 1px solid var(--line);
color: var(--ink);
min-width: 0;
overflow: hidden;
}
.performance-heading {
align-items: flex-end;
background:
linear-gradient(90deg, rgba(31, 116, 104, 0.06), transparent 38%),
var(--panel);
border-bottom: 1px solid var(--line);
display: flex;
justify-content: space-between;
padding: 20px 22px 18px;
}
.performance-heading span,
.ranking-heading span,
.strip-lead > span {
color: var(--signal);
font-family: "Cascadia Mono", Consolas, monospace;
font-size: 10px;
font-weight: 700;
letter-spacing: .12em;
}
.performance-heading h3 {
font-family: "Noto Serif SC", "Source Han Serif SC", serif;
font-size: 21px;
margin: 5px 0 3px;
}
.performance-heading p {
color: var(--muted);
font-size: 12px;
margin: 0;
}
.performance-actions {
align-items: center;
display: flex;
gap: 10px;
}
.range-switch {
background: #edf1f1;
display: flex;
padding: 3px;
}
.range-switch button {
background: transparent;
border: 0;
color: #68767e;
cursor: pointer;
font-size: 11px;
padding: 7px 11px;
transition: background .16s ease, color .16s ease;
}
.range-switch button.active {
background: var(--ink);
color: #fff;
}
.range-switch button:focus-visible {
outline: 2px solid var(--signal);
outline-offset: 2px;
}
.performance-loading {
padding: 32px;
}
.source-state {
align-items: flex-start;
background: #f8faf9;
display: grid;
gap: 16px;
grid-template-columns: auto minmax(0, 1fr) auto;
margin: 22px;
padding: 24px;
}
.source-state > .el-icon {
background: #e7efed;
color: var(--signal);
font-size: 22px;
padding: 12px;
}
.source-state strong {
display: block;
font-size: 15px;
margin: 2px 0 6px;
}
.source-state p,
.source-state small {
color: var(--muted);
line-height: 1.6;
margin: 0;
}
.source-state p { font-size: 12px; }
.source-state small { font-size: 10px; }
.source-state.is-unavailable > .el-icon { background: #f6e9e8; color: var(--danger); }
.source-state a,
.performance-foot a {
align-items: center;
color: var(--signal);
display: inline-flex;
font-size: 11px;
gap: 4px;
text-decoration: none;
}
.performance-strip {
border-bottom: 1px solid var(--line);
display: grid;
grid-template-columns: 230px minmax(0, 1fr);
}
.strip-lead {
background: var(--ink);
color: #fff;
padding: 18px 20px;
}
.strip-lead > span { color: #84c7bc; }
.strip-lead strong { display: block; font-size: 13px; margin: 9px 0 13px; }
.strip-lead small { color: #aebbc2; font-family: "Cascadia Mono", Consolas, monospace; font-size: 9px; }
.performance-strip > dl {
display: grid;
grid-template-columns: repeat(6, minmax(0, 1fr));
margin: 0;
}
.performance-strip dl > div {
border-right: 1px solid #e5eaec;
padding: 16px 14px;
}
.performance-strip dl > div:last-child { border-right: 0; }
.performance-strip dt { color: var(--muted); font-size: 10px; margin-bottom: 9px; }
.performance-strip dd { font-family: "Cascadia Mono", Consolas, monospace; font-size: 18px; margin: 0; }
.performance-strip dd small { color: var(--muted); font-size: 9px; margin-left: 3px; }
.performance-rail {
border-bottom: 1px solid var(--line);
padding: 16px 20px 8px;
}
.rail-chart { height: 260px; width: 100%; }
.samples-empty,
.ranking-empty {
color: var(--muted);
font-size: 12px;
margin: 0;
padding: 44px 22px;
text-align: center;
}
.samples-empty { border-bottom: 1px solid var(--line); }
.rankings {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.ranking-board {
border-right: 1px solid var(--line);
min-width: 0;
padding: 18px 20px 20px;
}
.ranking-board:last-child { border-right: 0; }
.ranking-heading {
align-items: flex-start;
display: flex;
justify-content: space-between;
margin-bottom: 14px;
}
.ranking-heading h4 {
font-family: "Noto Serif SC", "Source Han Serif SC", serif;
font-size: 15px;
margin: 4px 0 0;
}
.ranking-heading > small {
color: #89959b;
font-family: "Cascadia Mono", Consolas, monospace;
font-size: 9px;
margin-top: 5px;
}
.ranking-list { display: grid; gap: 1px; }
.ranking-row {
align-items: center;
background: #f8fafa;
display: grid;
gap: 11px;
grid-template-columns: 26px minmax(0, 1fr) 116px;
min-height: 50px;
padding: 7px 10px;
}
.ranking-row > b {
color: #9aa6ab;
font-family: "Cascadia Mono", Consolas, monospace;
font-size: 10px;
}
.ranking-row > div { min-width: 0; }
.ranking-row strong {
display: block;
font-family: "Cascadia Mono", Consolas, monospace;
font-size: 10px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.ranking-row > div > span {
background: #dfe7e7;
display: block;
height: 3px;
margin-top: 8px;
overflow: hidden;
}
.ranking-row i {
background: var(--signal);
display: block;
height: 100%;
}
.database-board .ranking-row i { background: var(--warning); }
.ranking-row dl {
margin: 0;
text-align: right;
}
.ranking-row dd {
font-family: "Cascadia Mono", Consolas, monospace;
font-size: 10px;
margin: 0 0 3px;
}
.ranking-row dt { color: var(--muted); font-size: 9px; }
.performance-foot {
align-items: center;
background: var(--paper);
border-top: 1px solid var(--line);
color: var(--muted);
display: flex;
font-size: 10px;
justify-content: space-between;
padding: 11px 20px;
}
@media (prefers-reduced-motion: reduce) {
.range-switch button { transition: none; }
}
@media (max-width: 1120px) {
.performance-strip { grid-template-columns: 190px minmax(0, 1fr); }
.performance-strip > dl { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.performance-strip dl > div:nth-child(3) { border-right: 0; }
.performance-strip dl > div:nth-child(-n+3) { border-bottom: 1px solid #e5eaec; }
}
@media (max-width: 820px) {
.performance-heading { align-items: flex-start; gap: 16px; }
.performance-actions { align-items: flex-end; flex-direction: column-reverse; }
.performance-strip { display: block; }
.rankings { grid-template-columns: 1fr; }
.ranking-board { border-bottom: 1px solid var(--line); border-right: 0; }
.ranking-board:last-child { border-bottom: 0; }
}
@media (max-width: 560px) {
.performance-heading { display: block; padding: 17px 14px; }
.performance-actions { align-items: stretch; flex-direction: row; margin-top: 14px; }
.range-switch { flex: 1; overflow-x: auto; }
.range-switch button { flex: 1 0 auto; padding-inline: 9px; }
.source-state { grid-template-columns: auto 1fr; margin: 12px; padding: 16px; }
.source-state a { grid-column: 2; }
.performance-strip > dl { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.performance-strip dl > div,
.performance-strip dl > div:nth-child(3) { border-bottom: 1px solid #e5eaec; border-right: 1px solid #e5eaec; }
.performance-strip dl > div:nth-child(even) { border-right: 0; }
.performance-strip dl > div:nth-last-child(-n+2) { border-bottom: 0; }
.performance-rail { padding-inline: 8px; }
.rail-chart { height: 230px; }
.ranking-board { padding-inline: 12px; }
.ranking-heading > small { display: none; }
.ranking-row { grid-template-columns: 22px minmax(0, 1fr) 96px; padding-inline: 7px; }
.performance-foot { align-items: flex-start; gap: 8px; }
}
</style>
+105
View File
@@ -0,0 +1,105 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import http from '../api/http'
interface SystemVersionResponse {
version: string
}
const backendVersion = ref('获取中')
const currentYear = new Date().getFullYear()
const frontendVersion = __APP_VERSION__
onMounted(async () => {
try {
const { data } = await http.get<SystemVersionResponse>('/system/version')
backendVersion.value = data.version ? `v${data.version}` : '未知'
} catch {
backendVersion.value = '未知'
}
})
</script>
<template>
<footer class="site-footer" aria-label="网站版权与版本信息">
<div class="site-footer-inner">
<p>© {{ currentYear }} 明序教务 · 版权所有</p>
<div class="version-list" aria-label="系统版本">
<span>前端版本 <b>v{{ frontendVersion }}</b></span>
<span>后端版本 <b>{{ backendVersion }}</b></span>
</div>
</div>
</footer>
</template>
<style scoped>
.site-footer {
position: relative;
z-index: 1;
border-top: 1px solid rgba(255, 255, 255, .1);
color: #d9e0f2;
background:
linear-gradient(90deg, rgba(255, 255, 255, .025) 1px, transparent 1px),
linear-gradient(112deg, #152550 0%, #1d326c 72%, #176a70 130%);
background-size: 28px 28px, auto;
}
.site-footer-inner {
min-height: 58px;
max-width: 1540px;
margin: 0 auto;
padding: 11px 32px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
}
.site-footer p {
margin: 0;
font-size: 12px;
letter-spacing: .04em;
}
.version-list {
display: flex;
align-items: center;
gap: 8px;
}
.version-list span {
padding: 5px 9px;
border: 1px solid rgba(255, 255, 255, .14);
border-radius: 4px;
color: #aeb9d8;
background: rgba(255, 255, 255, .055);
font-size: 10px;
white-space: nowrap;
}
.version-list b {
margin-left: 5px;
color: #66d5c5;
font: 700 10px/1.2 Consolas, monospace;
}
@media (max-width: 600px) {
.site-footer-inner {
min-height: 72px;
padding: 10px 14px;
align-items: flex-start;
flex-direction: column;
justify-content: center;
gap: 7px;
}
.version-list {
width: 100%;
}
.version-list span {
flex: 1;
text-align: center;
}
}
</style>
+3
View File
@@ -0,0 +1,3 @@
/// <reference types="vite/client" />
declare const __APP_VERSION__: string
+10 -8
View File
@@ -177,6 +177,10 @@ const navigationGroups = computed<NavigationGroup[]>(() => [
hasAnyRole(['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Teacher', 'Student', 'Counselor']),
{ path: '/grades', label: isStudent.value ? '学业成绩' : isTeacher.value ? '成绩录入' : '成绩管理' },
),
...whenVisible(
hasAnyRole(['SuperAdmin', 'AcademicAdmin', 'Student']),
{ path: '/other-exams', label: '其他考试成绩' },
),
...whenVisible(
hasAnyRole(['SuperAdmin', 'AcademicAdmin', 'Teacher', 'Student']),
{
@@ -212,6 +216,10 @@ const navigationGroups = computed<NavigationGroup[]>(() => [
key: 'student-status',
label: '学籍管理',
items: [
...whenVisible(
isStudent.value,
{ path: '/my-profile', label: '个人信息' },
),
...whenVisible(
hasAnyRole(['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Counselor', 'Student']),
{ path: '/student-status-changes', label: isStudent.value ? '学籍异动' : '异动审核' },
@@ -263,6 +271,7 @@ const workspaceLabel = computed(() => {
})
const pageTitle = computed(() => {
if (route.path === '/account') return '个人账户'
const matchedItem = navigationGroups.value
.flatMap((group) => group.items)
.find((item) => item.path === route.path)
@@ -318,6 +327,7 @@ onMounted(() => {
<b>{{ auth.user?.displayName ?? '系统管理员' }}</b>
<span>{{ auth.user?.roles?.[0] ?? '教务人员' }}</span>
</div>
<el-button text @click="router.push('/account')">个人账户</el-button>
<el-button text @click="signOut">退出</el-button>
</div>
</div>
@@ -353,10 +363,6 @@ onMounted(() => {
</el-sub-menu>
</template>
</el-menu>
<div class="navigation-status">
<span>CORE SYSTEM</span>
<b>核心业务已就绪</b>
</div>
</nav>
</header>
@@ -404,10 +410,6 @@ onMounted(() => {
</template>
</el-menu>
<div class="phase-note">
<span>第一阶段 · 核心可用版</span>
<p>教学运行学籍与毕业审核已就绪</p>
</div>
</aside>
<div v-if="mobileMenu" class="mobile-mask" @click="mobileMenu = false" />
+6
View File
@@ -6,11 +6,17 @@ import router from './router'
import { initializeAppUpdates } from './services/appUpdates'
import { initializeNativeHome } from './services/nativeHome'
import { setRouter } from './utils/navigate'
import { initializeAuthSession } from './auth/session'
const app = createApp(App)
app.use(createPinia())
app.use(router)
setRouter(router)
window.addEventListener('mingxu-session-expired', () => {
const returnUrl = location.pathname + location.search + location.hash
void router.push({ name: 'login', query: { redirect: returnUrl } })
})
initializeAuthSession()
app.mount('#app')
void initializeAppUpdates()
initializeNativeHome(router)
+29
View File
@@ -13,6 +13,18 @@ const router = createRouter({
component: () => import('../views/LoginView.vue'),
meta: { public: true },
},
{
path: '/sso/callback',
name: 'sso-callback',
component: () => import('../views/SsoCallbackView.vue'),
meta: { public: true },
},
{
path: '/sso/bind',
name: 'sso-bind',
component: () => import('../views/SsoBindView.vue'),
meta: { public: true },
},
{
path: '/timetable',
name: 'public-timetable',
@@ -41,6 +53,17 @@ const router = createRouter({
name: 'dashboard',
component: () => import('../views/DashboardView.vue'),
},
{
path: 'account',
name: 'account',
component: () => import('../views/AccountView.vue'),
},
{
path: 'my-profile',
name: 'my-profile',
component: () => import('../views/StudentProfileView.vue'),
meta: { roles: ['Student'] },
},
{
path: 'base-data',
redirect: '/base-data/organization',
@@ -224,6 +247,12 @@ const router = createRouter({
roles: ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Teacher', 'Student', 'Counselor'],
},
},
{
path: 'other-exams',
name: 'other-exams',
component: () => import('../views/OtherExamsView.vue'),
meta: { roles: ['SuperAdmin', 'AcademicAdmin', 'Student'] },
},
{
path: 'exams',
name: 'exams',
+57 -11
View File
@@ -1,6 +1,12 @@
import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import http from '../api/http'
import {
authStorageKeys,
clearAuthSession,
isNativeApp,
saveAuthSession,
} from '../auth/session'
export interface CurrentUser {
id: string
@@ -12,35 +18,75 @@ export interface CurrentUser {
}
export const useAuthStore = defineStore('auth', () => {
const token = ref(localStorage.getItem('jiaowu_token') ?? '')
const saved = localStorage.getItem('jiaowu_user')
const token = ref(localStorage.getItem(authStorageKeys.token) ?? '')
const saved = localStorage.getItem(authStorageKeys.user)
const user = ref<CurrentUser | null>(saved ? JSON.parse(saved) : null)
const isLoggedIn = computed(() => Boolean(token.value))
const isSuperAdmin = computed(() => user.value?.roles.includes('SuperAdmin') ?? false)
async function login(userName: string, password: string) {
const { data } = await http.post('/auth/login', { userName, password })
const { data } = await http.post('/auth/login', {
userName,
password,
isNativeApp: isNativeApp(),
})
token.value = data.token
user.value = data.user
localStorage.setItem('jiaowu_token', data.token)
localStorage.setItem('jiaowu_user', JSON.stringify(data.user))
window.dispatchEvent(new Event('mingxu-auth-changed'))
saveAuthSession(data)
}
async function exchangeSso(code: string) {
const { data } = await http.post('/auth/sso/exchange', {
code,
isNativeApp: isNativeApp(),
})
token.value = data.token
user.value = data.user
saveAuthSession(data)
}
async function bindSso(code: string, userName: string, password: string) {
const { data } = await http.post('/auth/sso/bind', {
code,
userName,
password,
isNativeApp: isNativeApp(),
})
token.value = data.token
user.value = data.user
saveAuthSession(data)
}
async function refresh() {
if (!token.value) return
const { data } = await http.get('/auth/me')
user.value = data
localStorage.setItem('jiaowu_user', JSON.stringify(data))
localStorage.setItem(authStorageKeys.user, JSON.stringify(data))
}
function logout() {
const refreshToken = localStorage.getItem(authStorageKeys.refreshToken)
if (refreshToken) void http.post('/auth/logout', { refreshToken }).catch(() => undefined)
token.value = ''
user.value = null
localStorage.removeItem('jiaowu_token')
localStorage.removeItem('jiaowu_user')
window.dispatchEvent(new Event('mingxu-auth-changed'))
clearAuthSession()
}
return { token, user, isLoggedIn, isSuperAdmin, login, refresh, logout }
window.addEventListener('mingxu-auth-changed', () => {
token.value = localStorage.getItem(authStorageKeys.token) ?? ''
const currentUser = localStorage.getItem(authStorageKeys.user)
user.value = currentUser ? JSON.parse(currentUser) : null
})
return {
token,
user,
isLoggedIn,
isSuperAdmin,
login,
exchangeSso,
bindSso,
refresh,
logout,
}
})
+20 -12
View File
@@ -80,14 +80,7 @@ button { cursor: pointer; }
background: linear-gradient(180deg, #fff, #f5faf9);
font-weight: 650;
}
.horizontal-menu .el-sub-menu__icon-arrow { margin-left: 6px; }
.navigation-status {
flex: 0 0 auto; min-width: 152px; padding-left: 24px;
display: grid; align-content: center; gap: 2px;
border-left: 1px solid var(--line);
}
.navigation-status span { color: var(--teal); font: 700 8px/1.2 Consolas, monospace; letter-spacing: .13em; }
.navigation-status b { color: #677083; font-size: 10px; font-weight: 500; }
.horizontal-menu .el-sub-menu__icon-arrow { display: none; }
.mobile-navigation {
position: fixed; inset: 0 auto 0 0; z-index: 30; width: 286px;
display: flex; flex-direction: column; overflow-y: auto;
@@ -121,10 +114,6 @@ button { cursor: pointer; }
.mobile-nav-menu .el-menu-item.is-active { color: white; background: #2d478d; box-shadow: inset 3px 0 #46c6b5; }
.mobile-nav-menu .el-sub-menu .el-menu { background: rgba(0,0,0,.1); }
.mobile-nav-menu .el-sub-menu .el-menu-item { min-width: 0; padding-left: 40px !important; font-size: 12px; }
.phase-note { margin: auto 20px 24px; padding-top: 17px; border-top: 1px solid rgba(255,255,255,.12); }
.phase-note span { color: #45c6b5; font-size: 11px; font-weight: 700; letter-spacing: .06em; }
.phase-note p { margin: 7px 0 0; color: #9faad0; font-size: 12px; line-height: 1.6; }
.main-area { min-width: 0; }
.menu-toggle {
width: 38px; height: 38px; border: 1px solid rgba(255,255,255,.18);
@@ -502,6 +491,8 @@ button { cursor: pointer; }
.cell-add { margin: auto; color: transparent; font-size: 9px; }
.timetable-cell.editable:hover .cell-add { color: #a0a8b4; }
.schedule-card { min-width: 0; padding: 8px 9px; display: grid; gap: 4px; position: relative; border-left: 3px solid #45bcae; color: #eaf2ff; background: linear-gradient(130deg, #263f80, #1a2e64); box-shadow: 0 4px 10px rgba(24,40,83,.12); cursor: pointer; }
.schedule-card.experiment { border-left-color: #f2b84b; background: linear-gradient(130deg, #705022, #4d3518); }
.schedule-card.experiment span { color: #ffd88a; }
.schedule-card.readonly { cursor: default; }
.schedule-card span { padding-right: 16px; color: #74d5c8; font: 700 8px/1.2 Consolas, monospace; letter-spacing: .04em; }
.schedule-card b { overflow: hidden; font-size: 11px; white-space: nowrap; text-overflow: ellipsis; }
@@ -1206,6 +1197,23 @@ button { cursor: pointer; }
.public-timetable-link { display: block; margin: 14px 0 18px; color: #176b87; font-size: 13px; font-weight: 650; text-align: center; text-decoration: none; }
.account-activation-link { display: block; margin: -8px 0 18px; color: #315b73; font-size: 13px; font-weight: 650; text-align: center; text-decoration: none; }
.login-submit { width: 100%; margin-top: 6px; height: 46px; }
.sso-login-submit { width: 100%; height: 46px; border-color: #176b87; color: #176b87; font-weight: 650; }
.login-divider { display: flex; align-items: center; gap: 12px; margin: 16px 0; color: #9aa4b2; font-size: 12px; }
.login-divider::before, .login-divider::after { content: ""; flex: 1; height: 1px; background: #e5e9ef; }
.sso-callback-page { min-height: 100vh; display: grid; place-content: center; justify-items: center; padding: 24px; background: #f4f7fa; color: #263445; text-align: center; }
.sso-callback-page h1 { margin: 18px 0 8px; font-size: 22px; }
.sso-callback-page p { margin: 0; color: var(--muted); }
.sso-binding-page { min-height: 100vh; display: grid; place-items: center; padding: 28px; background: radial-gradient(circle at top left, #e3f5f2, transparent 42%), #f4f7fa; }
.sso-binding-card { width: min(470px, 100%); padding: 38px; border: 1px solid #e3e8ee; border-radius: 18px; background: #fff; box-shadow: 0 20px 55px rgba(35, 57, 78, .12); }
.sso-binding-card .brand-mark { margin-bottom: 24px; }
.sso-binding-card h1 { margin: 8px 0 12px; font-family: "STZhongsong", "Songti SC", serif; font-size: 28px; }
.binding-description { margin: 0 0 26px; color: var(--muted); line-height: 1.75; }
.binding-description strong { color: #176b87; }
.sso-binding-card label { display: block; margin-bottom: 18px; }
.sso-binding-card label > span { display: block; margin-bottom: 8px; color: #525b6d; font-size: 12px; font-weight: 650; }
.binding-submit { width: 100%; height: 46px; }
.binding-security-note { margin: 18px 0 10px; color: #7b8794; font-size: 12px; line-height: 1.65; }
.sso-binding-card > a { color: #315b73; font-size: 13px; font-weight: 650; text-decoration: none; }
@media (max-width: 1100px) {
.metric-grid { grid-template-columns: repeat(2, 1fr); }
+203
View File
@@ -0,0 +1,203 @@
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import http, { apiErrorMessage } from '../api/http'
import { useAuthStore } from '../stores/auth'
const route = useRoute()
const router = useRouter()
const auth = useAuthStore()
const loading = ref(true)
const actionLoading = ref(false)
const sso = reactive({
enabled: false,
providerDisplayName: '学校统一身份认证',
isBound: false,
callbackUrl: '',
})
const ssoErrors: Record<string, string> = {
binding_intent_expired: '绑定请求已失效,请重新发起绑定。',
identity_already_bound: '该统一身份账号已经绑定其他教务系统账号。',
account_already_bound: '当前教务系统账号已经绑定其他统一身份账号。',
account_disabled: '当前教务系统账号已停用或锁定。',
account_link_failed: '统一身份账户绑定失败,请重新尝试。',
configuration_error: '统一身份认证回调地址配置不正确,请联系管理员。',
}
async function loadAccount() {
loading.value = true
try {
const { data } = await http.get('/auth/sso/account')
sso.enabled = Boolean(data.enabled)
sso.providerDisplayName = String(data.providerDisplayName || sso.providerDisplayName)
sso.isBound = Boolean(data.isBound)
sso.callbackUrl = String(data.callbackUrl || '')
} catch (error) {
ElMessage.error(apiErrorMessage(error))
} finally {
loading.value = false
}
}
async function startBinding() {
actionLoading.value = true
try {
const { data } = await http.post('/auth/sso/prepare-binding')
window.location.assign(String(data.loginUrl))
} catch (error) {
ElMessage.error(apiErrorMessage(error))
actionLoading.value = false
}
}
async function unbind() {
try {
const result = await ElMessageBox.prompt(
'解绑后将不能再使用当前统一身份账号登录。请输入教务系统密码确认。',
'解除统一身份绑定',
{
inputType: 'password',
inputPlaceholder: '请输入教务系统密码',
inputValidator: (value) => Boolean(value) || '密码不能为空',
confirmButtonText: '确认解绑',
cancelButtonText: '取消',
type: 'warning',
},
)
actionLoading.value = true
await http.post('/auth/sso/unbind', { password: result.value })
ElMessage.success('统一身份账户已解绑。')
await loadAccount()
} catch (error) {
if (error === 'cancel' || error === 'close') return
ElMessage.error(apiErrorMessage(error))
} finally {
actionLoading.value = false
}
}
onMounted(async () => {
const ssoError = String(route.query.ssoError ?? '')
if (ssoError) {
ElMessage.error(ssoErrors[ssoError] ?? '统一身份账户绑定失败,请重新尝试。')
await router.replace('/account')
}
await loadAccount()
})
</script>
<template>
<section class="account-page">
<header class="account-heading">
<div>
<span class="eyebrow">ACCOUNT &amp; SECURITY</span>
<h1>个人账户</h1>
<p>管理您的登录身份与单点登录绑定</p>
</div>
<div class="account-avatar">{{ auth.user?.displayName?.slice(0, 1) ?? '用' }}</div>
</header>
<div class="account-grid">
<article class="account-card identity-card">
<div class="card-title">
<div>
<span>基本信息</span>
<h2>{{ auth.user?.displayName }}</h2>
</div>
<el-tag type="success" effect="light">账号已启用</el-tag>
</div>
<dl>
<div>
<dt>登录账号</dt>
<dd>{{ auth.user?.userName }}</dd>
</div>
<div>
<dt>系统角色</dt>
<dd class="role-list">
<el-tag v-for="role in auth.user?.roles" :key="role" effect="plain">{{ role }}</el-tag>
</dd>
</div>
<div>
<dt>数据范围</dt>
<dd>{{ auth.user?.effectiveDataScope }}</dd>
</div>
</dl>
</article>
<article v-loading="loading" class="account-card sso-card">
<div class="card-title">
<div>
<span>单点登录</span>
<h2>{{ sso.providerDisplayName }}</h2>
</div>
<el-tag v-if="sso.isBound" type="success">已绑定</el-tag>
<el-tag v-else-if="sso.enabled" type="info">未绑定</el-tag>
<el-tag v-else type="warning">未启用</el-tag>
</div>
<p v-if="sso.isBound" class="sso-description">
当前教务系统账号已经关联统一身份认证您可以直接通过 Keycloak 登录
</p>
<p v-else-if="sso.enabled" class="sso-description">
绑定后即使统一身份用户名与教务系统账号不同也可以直接登录当前账号
</p>
<p v-else class="sso-description">管理员尚未启用统一身份认证</p>
<el-button
v-if="sso.enabled && !sso.isBound"
type="primary"
:loading="actionLoading"
@click="startBinding"
>
绑定统一身份账户
</el-button>
<el-button
v-else-if="sso.isBound"
type="danger"
plain
:loading="actionLoading"
@click="unbind"
>
解除绑定
</el-button>
<details v-if="sso.enabled && sso.callbackUrl" class="callback-details">
<summary>管理员配置参考</summary>
<p>Keycloak Valid redirect URI 必须与下列地址完全一致</p>
<code>{{ sso.callbackUrl }}</code>
</details>
</article>
</div>
</section>
</template>
<style scoped>
.account-page { display: grid; gap: 22px; }
.account-heading { display: flex; align-items: center; justify-content: space-between; padding: 26px 30px; border-radius: 18px; background: linear-gradient(125deg, #173a50, #176b87 65%, #2e9b91); color: white; box-shadow: 0 18px 45px rgba(23, 58, 80, .18); }
.account-heading h1 { margin: 7px 0 5px; font-family: "STZhongsong", "Songti SC", serif; font-size: 30px; }
.account-heading p { margin: 0; color: rgba(255,255,255,.72); }
.account-heading .eyebrow { color: #8ee4d8; }
.account-avatar { display: grid; place-items: center; width: 68px; height: 68px; border: 1px solid rgba(255,255,255,.34); border-radius: 22px; background: rgba(255,255,255,.12); font-size: 28px; font-weight: 700; }
.account-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px; }
.account-card { min-width: 0; min-height: 310px; padding: 28px; border: 1px solid #e2e8ee; border-radius: 16px; background: white; box-shadow: 0 12px 34px rgba(35, 57, 78, .07); }
.card-title { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; padding-bottom: 20px; border-bottom: 1px solid #edf0f3; }
.card-title span { color: #73808d; font-size: 12px; }
.card-title h2 { margin: 6px 0 0; color: #263445; font-size: 21px; }
dl { margin: 6px 0 0; }
dl > div { display: grid; grid-template-columns: 100px 1fr; gap: 18px; padding: 16px 0; border-bottom: 1px solid #f0f2f4; }
dt { color: #7b8794; font-size: 13px; }
dd { margin: 0; color: #263445; font-weight: 650; }
.role-list { display: flex; flex-wrap: wrap; gap: 7px; }
.sso-description { min-height: 54px; margin: 22px 0; color: #65717e; line-height: 1.7; }
.callback-details { margin-top: 24px; color: #65717e; font-size: 12px; }
.callback-details summary { cursor: pointer; color: #315b73; font-weight: 650; }
.callback-details p { margin: 10px 0 7px; }
.callback-details code { display: block; overflow-wrap: anywhere; padding: 10px 12px; border-radius: 8px; background: #f4f7f9; color: #176b87; }
@media (max-width: 1100px) {
.account-grid { grid-template-columns: 1fr; }
.account-heading { padding: 22px; }
.account-avatar { width: 56px; height: 56px; border-radius: 18px; }
.account-card { min-height: 0; padding: 22px; }
}
</style>
+216 -14
View File
@@ -27,7 +27,7 @@ const statusFilter = ref('')
const projectDialog = ref(false)
const editingProjectId = ref('')
const projectForm = reactive({
teachingTaskId: '',
teachingTaskIds: [] as string[],
code: '',
name: '',
arrangementMode: 'Centralized',
@@ -47,13 +47,20 @@ const sessionForm = reactive({
notes: '',
})
const batchSessionDialog = ref(false)
const batchSessionProjectIds = ref<string[]>([])
const batchSessionRows = ref<any[]>([])
const participantsDialog = ref(false)
const participantSession = ref<any>(null)
const participants = ref<any[]>([])
const participantsLoading = ref(false)
const selectedTask = computed(() =>
options.tasks.find((task) => task.id === projectForm.teachingTaskId),
options.tasks.find((task) => task.id === projectForm.teachingTaskIds[0]),
)
const batchProjectOptions = computed(() =>
projects.value.filter((project) => project.status !== 'Closed'),
)
const activePeriods = computed(() =>
options.periods.filter((period) =>
@@ -82,7 +89,7 @@ const statusLabels: Record<string, string> = {
function resetProjectForm() {
editingProjectId.value = ''
Object.assign(projectForm, {
teachingTaskId: '',
teachingTaskIds: [],
code: '',
name: '',
arrangementMode: 'Centralized',
@@ -106,7 +113,7 @@ function openCreateProject() {
function openEditProject(project: any) {
editingProjectId.value = project.id
Object.assign(projectForm, {
teachingTaskId: project.teachingTaskId,
teachingTaskIds: [project.teachingTaskId],
code: project.code,
name: project.name,
arrangementMode: project.arrangementMode,
@@ -118,13 +125,13 @@ function openEditProject(project: any) {
}
async function saveProject() {
if (!projectForm.teachingTaskId || !projectForm.code.trim()
if (!projectForm.teachingTaskIds.length || !projectForm.code.trim()
|| !projectForm.name.trim() || projectForm.dates.length !== 2) {
ElMessage.warning('请填写教学任务、项目编码、名称和开放日期')
return
}
const payload = {
teachingTaskId: projectForm.teachingTaskId,
teachingTaskId: projectForm.teachingTaskIds[0],
code: projectForm.code,
name: projectForm.name,
arrangementMode: projectForm.arrangementMode,
@@ -138,8 +145,12 @@ async function saveProject() {
await http.put(`/experiments/${editingProjectId.value}`, payload)
ElMessage.success('实验项目已更新')
} else {
await http.post('/experiments', payload)
ElMessage.success('实验项目已创建')
await http.post('/experiments/batch', {
...payload,
teachingTaskId: undefined,
teachingTaskIds: projectForm.teachingTaskIds,
})
ElMessage.success(`已为 ${projectForm.teachingTaskIds.length} 个教学任务创建实验项目`)
}
projectDialog.value = false
await load()
@@ -148,6 +159,78 @@ async function saveProject() {
}
}
function openBatchSession() {
batchSessionProjectIds.value = []
batchSessionRows.value = []
batchSessionDialog.value = true
}
function syncBatchSessionRows() {
const existing = new Map(batchSessionRows.value.map((row) => [row.projectId, row]))
batchSessionRows.value = batchSessionProjectIds.value.map((projectId) => {
const current = existing.get(projectId)
if (current) return current
const project = projects.value.find((item) => item.id === projectId)
const firstPeriod = options.periods.find((item) =>
item.academicTermId === project?.academicTermId,
)
return {
projectId,
classroomId: '',
sessionDate: project?.startDate ?? '',
startPeriod: firstPeriod?.periodNumber,
periodCount: 2,
capacity: 30,
notes: '',
}
})
}
function applyFirstBatchTime() {
const first = batchSessionRows.value[0]
if (!first) return
batchSessionRows.value.slice(1).forEach((row) => {
row.sessionDate = first.sessionDate
row.startPeriod = first.startPeriod
row.periodCount = first.periodCount
})
ElMessage.success('已套用首行的日期和节次,请分别选择不冲突的实验室')
}
function batchProject(projectId: string) {
return projects.value.find((project) => project.id === projectId)
}
function periodsForProject(projectId: string) {
const project = batchProject(projectId)
return options.periods.filter((period) =>
period.academicTermId === project?.academicTermId,
)
}
async function saveBatchSessions() {
if (!batchSessionRows.value.length) {
ElMessage.warning('请至少选择一个实验项目')
return
}
if (batchSessionRows.value.some((row) =>
!row.classroomId || !row.sessionDate || !row.startPeriod || !row.periodCount,
)) {
ElMessage.warning('请完整填写每个项目的日期、节次、实验室和容量')
return
}
try {
await http.post('/experiments/sessions/batch', {
items: batchSessionRows.value,
})
batchSessionDialog.value = false
ElMessage.success(`已批量安排 ${batchSessionRows.value.length} 个实验场次`)
await load()
} catch (error) {
ElMessage.error(apiErrorMessage(error))
}
}
function openSession(project: any) {
selectedProject.value = project
const firstPeriod = options.periods.find((item) =>
@@ -382,8 +465,11 @@ onMounted(async () => {
<p v-else>把实验项目分成两条运行轨道集中排入固定课次或开放场次供学生自主预约</p>
</div>
<div class="intro-actions">
<el-button v-if="!isStudent" :icon="Calendar" @click="openBatchSession">
批量排课
</el-button>
<el-button v-if="!isStudent" type="primary" :icon="Plus" @click="openCreateProject">
新建实验项目
批量设置实验任务
</el-button>
<el-button :icon="Refresh" @click="load">刷新</el-button>
</div>
@@ -627,19 +713,22 @@ onMounted(async () => {
<el-dialog
v-model="projectDialog"
:title="editingProjectId ? '编辑实验项目' : '新建实验项目'"
:title="editingProjectId ? '编辑实验项目' : '批量设置实验任务'"
width="720px"
top="5vh"
>
<el-form label-position="top" class="experiment-form">
<div class="form-section">
<header><span>PROJECT</span><b>规定实验项目</b></header>
<el-form-item label="所属教学任务" required>
<el-form-item :label="editingProjectId ? '所属教学任务' : '适用教学任务(可多选)'" required>
<el-select
v-model="projectForm.teachingTaskId"
v-model="projectForm.teachingTaskIds"
filterable
multiple
collapse-tags
collapse-tags-tooltip
:disabled="!!editingProjectId"
placeholder="选择已发布教学任务"
placeholder="选择同一学期、同一课程的已发布教学任务"
@change="onTaskChange"
>
<el-option
@@ -647,8 +736,14 @@ onMounted(async () => {
:key="task.id"
:label="`${task.courseCode} · ${task.courseName} · ${task.taskNumber}`"
:value="task.id"
:disabled="!!selectedTask
&& (task.academicTermId !== selectedTask.academicTermId
|| task.courseId !== selectedTask.courseId)"
/>
</el-select>
<small v-if="!editingProjectId" class="form-help">
已选 {{ projectForm.teachingTaskIds.length }} 实验编码名称内容和开放日期将一次应用到这些教学任务
</small>
</el-form-item>
<div class="form-grid two">
<el-form-item label="项目编码" required>
@@ -708,7 +803,13 @@ onMounted(async () => {
</el-form>
<template #footer>
<el-button @click="projectDialog = false">取消</el-button>
<el-button type="primary" @click="saveProject">保存项目</el-button>
<el-button type="primary" @click="saveProject">
{{ editingProjectId
? '保存项目'
: projectForm.teachingTaskIds.length
? `创建 ${projectForm.teachingTaskIds.length} 个项目`
: '创建项目' }}
</el-button>
</template>
</el-dialog>
@@ -778,6 +879,86 @@ onMounted(async () => {
</template>
</el-dialog>
<el-dialog
v-model="batchSessionDialog"
title="批量安排实验场次"
width="min(1180px, 94vw)"
top="4vh"
>
<el-alert
title="一次提交整批排课;系统会逐条检查管理范围、开放日期、实验室、课表、教师和班级冲突,任何一条失败都不会写入本批次。"
type="info"
:closable="false"
show-icon
/>
<el-form label-position="top" class="batch-session-form">
<el-form-item label="选择实验项目" required>
<el-select
v-model="batchSessionProjectIds"
multiple
filterable
collapse-tags
collapse-tags-tooltip
placeholder="选择需要一起排课的实验项目"
@change="syncBatchSessionRows"
>
<el-option
v-for="project in batchProjectOptions"
:key="project.id"
:label="`${project.courseCode} · ${project.name} · ${project.taskNumber}`"
:value="project.id"
/>
</el-select>
</el-form-item>
<div v-if="batchSessionRows.length" class="batch-session-tools">
<span> {{ batchSessionRows.length }} 条排课</span>
<el-button size="small" @click="applyFirstBatchTime">套用首行日期与节次</el-button>
</div>
<div class="batch-session-table">
<article v-for="(row, index) in batchSessionRows" :key="row.projectId" class="batch-session-row">
<div class="batch-project-cell">
<span>{{ index + 1 }}</span>
<div>
<b>{{ batchProject(row.projectId)?.name }}</b>
<small>{{ batchProject(row.projectId)?.taskNumber }} · {{ batchProject(row.projectId)?.classNames.join('、') || '选课学生' }}</small>
</div>
</div>
<el-date-picker
v-model="row.sessionDate"
type="date"
value-format="YYYY-MM-DD"
placeholder="实验日期"
/>
<el-select v-model="row.startPeriod" placeholder="起始节次">
<el-option
v-for="period in periodsForProject(row.projectId)"
:key="period.periodNumber"
:label="period.name"
:value="period.periodNumber"
/>
</el-select>
<el-input-number v-model="row.periodCount" :min="1" :max="12" controls-position="right" />
<el-select v-model="row.classroomId" filterable placeholder="实验室">
<el-option
v-for="room in options.classrooms"
:key="room.id"
:label="`${room.campusName} · ${room.buildingName} ${room.name} · ${room.capacity} 人`"
:value="room.id"
/>
</el-select>
<el-input-number v-model="row.capacity" :min="1" :max="10000" controls-position="right" />
</article>
</div>
<el-empty v-if="!batchSessionRows.length" :image-size="60" description="选择实验项目后,在同一张表中完成排课" />
</el-form>
<template #footer>
<el-button @click="batchSessionDialog = false">取消</el-button>
<el-button type="primary" :disabled="!batchSessionRows.length" @click="saveBatchSessions">
提交整批排课
</el-button>
</template>
</el-dialog>
<el-dialog
v-model="participantsDialog"
:title="`${participantSession?.project?.arrangementMode === 'Centralized' ? '应到名单' : '预约名单'} · ${participantSession ? formatSessionTime(participantSession) : ''}`"
@@ -912,6 +1093,7 @@ onMounted(async () => {
.student-booking-summary span { display: grid; gap: 2px; color: #365f5b; font-size: 12px; }
.student-booking-summary b { font-size: 10px; text-transform: uppercase; letter-spacing: .06em; }
.experiment-form { display: grid; gap: 13px; }
.form-help { display: block; margin-top: 7px; color: var(--muted); line-height: 1.5; }
.form-section { padding: 14px 15px 1px; border: 1px solid var(--line); background: #fbfcfd; }
.form-section > header { display: flex; align-items: baseline; gap: 9px; margin-bottom: 13px; }
.form-section > header span { color: var(--lab-teal); font: 700 10px/1 Consolas, monospace; letter-spacing: .08em; }
@@ -920,6 +1102,25 @@ onMounted(async () => {
.mode-choice :deep(.el-radio-button__inner) { display: grid; gap: 5px; width: 100%; padding: 13px; }
.mode-choice b { font-size: 13px; }
.mode-choice small { font-size: 10px; font-weight: 400; }
.batch-session-form { display: grid; gap: 12px; margin-top: 16px; }
.batch-session-tools { display: flex; align-items: center; justify-content: space-between; color: var(--muted); font-size: 12px; }
.batch-session-table { display: grid; gap: 8px; overflow-x: auto; padding-bottom: 4px; }
.batch-session-row {
display: grid;
grid-template-columns: minmax(230px, 1.4fr) 150px 120px 110px minmax(230px, 1.3fr) 110px;
gap: 8px;
align-items: center;
min-width: 1000px;
padding: 10px;
border: 1px solid #dce5e9;
background: #f9fbfc;
}
.batch-project-cell { display: flex; align-items: center; gap: 10px; min-width: 0; }
.batch-project-cell > span { display: grid; width: 25px; height: 25px; place-items: center; border-radius: 50%; background: #e5f0f5; color: var(--lab-blue); font: 700 11px/1 Consolas, monospace; }
.batch-project-cell > div { display: grid; gap: 3px; min-width: 0; }
.batch-project-cell b, .batch-project-cell small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.batch-project-cell b { color: var(--lab-ink); font-size: 12px; }
.batch-project-cell small { color: var(--muted); font-size: 10px; }
@media (prefers-reduced-motion: reduce) {
.session-ticket { transition: none; }
}
@@ -936,5 +1137,6 @@ onMounted(async () => {
.ticket-action { grid-column: 1 / -1; justify-content: flex-start; padding: 0 10px 10px; }
.project-actions, .student-booking-summary { padding-inline: 14px; }
.mode-choice { grid-template-columns: 1fr; }
.intro-actions { flex-wrap: wrap; justify-content: flex-end; }
}
</style>
+45 -2
View File
@@ -1,13 +1,16 @@
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { apiErrorMessage } from '../api/http'
import { useAuthStore } from '../stores/auth'
import http from '../api/http'
const route = useRoute()
const router = useRouter()
const auth = useAuthStore()
const loading = ref(false)
const ssoLoading = ref(false)
const sso = reactive({ enabled: false, displayName: '学校统一身份认证' })
const form = reactive({
userName: String(route.query.userName ?? ''),
password: '',
@@ -24,6 +27,37 @@ async function submit() {
loading.value = false
}
}
function startSso() {
ssoLoading.value = true
const apiBaseUrl = String(import.meta.env.VITE_API_BASE_URL ?? '/api').replace(/\/$/, '')
const redirect = String(route.query.redirect ?? '/dashboard')
window.location.assign(
`${apiBaseUrl}/auth/sso/login?returnUrl=${encodeURIComponent(redirect)}`,
)
}
const ssoErrors: Record<string, string> = {
authentication_failed: '统一身份认证未完成,请重新尝试。',
missing_subject: 'Keycloak 未返回用户唯一标识,请联系管理员检查客户端映射。',
account_disabled: '教务系统账号已停用或锁定,请联系管理员。',
account_link_failed: '统一身份账号绑定失败,请联系管理员。',
account_update_failed: '登录状态更新失败,请稍后重试。',
binding_expired: '账户绑定请求已失效,请重新使用统一身份认证登录。',
configuration_error: '统一身份认证回调地址配置不正确,请联系管理员。',
}
onMounted(async () => {
const ssoError = String(route.query.ssoError ?? '')
if (ssoError) ElMessage.error(ssoErrors[ssoError] ?? '统一身份认证失败,请重新尝试。')
try {
const { data } = await http.get('/auth/sso/settings')
sso.enabled = Boolean(data.enabled)
sso.displayName = String(data.displayName || sso.displayName)
} catch {
sso.enabled = false
}
})
</script>
<template>
@@ -48,7 +82,6 @@ async function submit() {
<span v-if="[3, 8, 9, 14, 18].includes(item)">教学</span>
</div>
</div>
<p class="story-foot">第一阶段 · 基础管理工作台</p>
</section>
<section class="login-panel">
@@ -82,6 +115,16 @@ async function submit() {
>
进入工作台
</el-button>
<div v-if="sso.enabled" class="login-divider"><span></span></div>
<el-button
v-if="sso.enabled"
class="sso-login-submit"
size="large"
:loading="ssoLoading"
@click="startSso"
>
使用{{ sso.displayName }}登录
</el-button>
<router-link class="public-timetable-link" to="/timetable">无需登录查询班级课表 </router-link>
<router-link class="account-activation-link" to="/activate">学生首次登录自助激活账号 </router-link>
</form>
+3
View File
@@ -8,6 +8,7 @@ import {
import { ElMessage, ElMessageBox } from 'element-plus'
import http, { apiErrorMessage } from '../api/http'
import AppUpdateManagementPanel from '../components/AppUpdateManagementPanel.vue'
import PerformanceReportPanel from '../components/PerformanceReportPanel.vue'
type HealthStatus = 'healthy' | 'warning' | 'unhealthy'
@@ -406,6 +407,8 @@ onMounted(refreshAll)
</div>
</section>
<PerformanceReportPanel />
<section class="console-split">
<article class="alerts-panel">
<div class="panel-heading">
+108
View File
@@ -0,0 +1,108 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download, Plus, Promotion, Upload } from '@element-plus/icons-vue'
import http, { apiErrorMessage } from '../api/http'
import { useAuthStore } from '../stores/auth'
type ResultRow = { studentNumber: string; studentName?: string; collegeName?: string; className?: string; attemptNumber?: number; score: number | null; level: string; isPassed: boolean | null; notes: string }
const auth = useAuthStore()
const isStudent = computed(() => auth.user?.roles.includes('Student'))
const loading = ref(false)
const batches = ref<any[]>([])
const selected = ref<any>(null)
const results = ref<ResultRow[]>([])
const mine = reactive({ best: [] as any[], history: [] as any[] })
const dialog = ref(false)
const saving = ref(false)
const form = reactive({ examCode: '', name: '', organizer: '', examDate: new Date().toISOString().slice(0, 10), metricKind: 3, maxScore: 100, levelOptions: '' })
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)
async function load() {
loading.value = true
try {
if (isStudent.value) Object.assign(mine, (await http.get('/other-exams/mine')).data)
else batches.value = (await http.get('/other-exams/batches')).data
} catch (error) { ElMessage.error(apiErrorMessage(error)) } finally { loading.value = false }
}
async function openBatch(row: any) {
try {
const data = (await http.get(`/other-exams/batches/${row.id}`)).data
const metricKind = Number(data.batch.metricKind ?? 3)
data.batch.metricKind = [1, 2, 3].includes(metricKind) ? metricKind : 3
selected.value = data.batch
results.value = data.results.map((item: any) => ({ ...item, score: item.score ?? null, level: item.level ?? '', notes: item.notes ?? '' }))
} catch (error) { ElMessage.error(apiErrorMessage(error)) }
}
function addResult() { results.value.push({ studentNumber: '', studentName: '', collegeName: '', className: '', score: null, level: '', isPassed: null, notes: '' }) }
async function lookupStudent(row: ResultRow | any) {
row.studentName = ''; row.collegeName = ''; row.className = ''
if (!row.studentNumber.trim()) return
try {
const { data } = await http.get('/other-exams/students/lookup', { params: { studentNumber: row.studentNumber.trim() } })
row.studentNumber = data.studentNumber; row.studentName = data.name; row.collegeName = data.collegeName; row.className = data.className
} catch { ElMessage.warning(`未找到学号 ${row.studentNumber}`) }
}
async function saveResults() {
saving.value = true
try {
await http.put(`/other-exams/batches/${selected.value.id}/results`, { results: results.value.map(row => ({ studentNumber: row.studentNumber, score: isScoreMetric.value ? row.score : null, level: isLevelMetric.value ? row.level : null, isPassed: isPassMetric.value ? row.isPassed : null, notes: row.notes })) })
ElMessage.success('成绩已保存,参加次数由系统自动计算'); await openBatch(selected.value); await load()
} catch (error) { ElMessage.error(apiErrorMessage(error)) } finally { saving.value = false }
}
async function publish() {
try {
await ElMessageBox.confirm('确认发布本批次成绩?发布后学生可查看;修改后可再次发布。', '发布其他考试成绩')
await http.post(`/other-exams/batches/${selected.value.id}/publish`)
ElMessage.success('成绩已发布'); await openBatch(selected.value); await load()
} catch (error: any) { if (error !== 'cancel' && error !== 'close') ElMessage.error(apiErrorMessage(error)) }
}
async function createBatch() {
try { await http.post('/other-exams/batches', form); dialog.value = false; ElMessage.success('考试批次已建立'); await load() }
catch (error) { ElMessage.error(apiErrorMessage(error)) }
}
async function downloadTemplate() {
try {
const response = await http.get(`/other-exams/batches/${selected.value.id}/template`, { responseType: 'blob' })
const url = URL.createObjectURL(response.data); const link = document.createElement('a'); link.href = url; link.download = `其他考试成绩导入模板-${selected.value.examCode || selected.value.name}.xlsx`; link.click(); URL.revokeObjectURL(url)
} catch (error) { ElMessage.error(apiErrorMessage(error)) }
}
async function importExcel(event: Event) {
const input = event.target as HTMLInputElement; const file = input.files?.[0]; input.value = ''
if (!file) return
const data = new FormData(); data.append('file', file)
try { await http.post(`/other-exams/batches/${selected.value.id}/import`, data, { headers: { 'Content-Type': 'multipart/form-data' } }); ElMessage.success('其他考试成绩导入成功'); await openBatch(selected.value); await load() }
catch (error) { ElMessage.error(apiErrorMessage(error)) }
}
function metricName(kind: number | string) { const value = Number(kind); return value === 1 ? '合格制' : value === 2 ? '等级制' : '分数制' }
function displayResult(row: any) { return row.metricKind === 3 ? `${row.score} / ${row.maxScore}` : row.metricKind === 2 ? row.level : row.isPassed ? '合格' : '不合格' }
onMounted(load)
</script>
<template>
<div class="other-exams-page">
<section class="exam-hero"><div><span class="kicker">ASSESSMENT ARCHIVE</span><h1>其他考试成绩</h1><p>{{ isStudent ? '你的证书、等级考试与校外考试,按考试归档,最优结果一目了然。' : '用考试编码归并同一考试,按场次维护成绩,系统自动记录每位学生的参加次数。' }}</p></div><el-button v-if="!isStudent" type="primary" :icon="Plus" @click="dialog = true">新建考试场次</el-button></section>
<template v-if="isStudent">
<section class="result-board"><div class="board-title"><div><span class="kicker">BEST OUTCOME</span><h2>我的最优结果</h2></div><span class="board-note">同一考试编码下自动比较</span></div><el-table :data="mine.best" v-loading="loading"><el-table-column prop="examName" label="考试" min-width="180"/><el-table-column prop="examCode" label="考试编码" width="130"/><el-table-column prop="examDate" label="考试日期" width="120"/><el-table-column label="最优结果" min-width="150"><template #default="{ row }"><strong class="best-value">{{ displayResult(row) }}</strong></template></el-table-column><el-table-column prop="attemptNumber" label="参加次数" width="100"/></el-table><el-empty v-if="!loading && !mine.best.length" description="暂无已发布的其他考试成绩"/></section>
<section class="result-board history-board"><div class="board-title"><div><span class="kicker">FULL HISTORY</span><h2>历史成绩</h2></div><span class="board-note">每次发布的结果都会保留</span></div><el-table :data="mine.history" v-loading="loading"><el-table-column prop="examName" label="考试" min-width="180"/><el-table-column prop="examCode" label="考试编码" width="130"/><el-table-column prop="examDate" label="考试日期" width="120"/><el-table-column prop="attemptNumber" label="第几次参加" width="110"/><el-table-column label="结果" min-width="140"><template #default="{ row }">{{ displayResult(row) }}</template></el-table-column><el-table-column prop="publishedAt" label="发布时间" width="170"/></el-table></section>
</template>
<template v-else>
<section class="batch-panel"><div class="panel-heading"><div><span class="kicker">EXAM SESSIONS</span><h2>考试场次</h2></div><span>点击场次进入成绩录入</span></div><el-table :data="batches" v-loading="loading" @row-click="openBatch"><el-table-column prop="examCode" label="考试编码" width="140"/><el-table-column prop="name" label="考试名称" min-width="190"/><el-table-column prop="examDate" label="考试日期" width="120"/><el-table-column label="评价方式" width="100"><template #default="{ row }">{{ metricName(row.metricKind) }}</template></el-table-column><el-table-column prop="resultCount" label="已录入" width="90"/><el-table-column label="状态" width="120"><template #default="{ row }"><el-tag :type="row.status === 2 ? 'success' : 'info'">{{ row.status === 2 ? `已发布 ${row.publicationCount} ` : '草稿' }}</el-tag></template></el-table-column></el-table></section>
<section v-if="selected" class="editor-panel"><div class="editor-heading"><div><span class="kicker">{{ selected.examCode }}</span><h2>{{ selected.name }}</h2><p>{{ selected.organizer || '未填写组织方' }} · {{ selected.examDate }} · {{ metricName(selected.metricKind) }}{{ selected.metricKind === 3 ? ` · 满分 ${selected.maxScore}` : '' }}</p></div><div class="editor-actions"><el-button :icon="Download" @click="downloadTemplate">下载导入模板</el-button><label class="upload-button"><Upload />批量导入<input type="file" accept=".xlsx,.xls" @change="importExcel" /></label><el-button :icon="Plus" @click="addResult">新增一行</el-button><el-button type="primary" :loading="saving" @click="saveResults">保存记录</el-button><el-button type="success" :icon="Promotion" @click="publish">发布</el-button></div></div><div class="editor-hint">学号输入完成后离开输入框,系统自动检索姓名、学院和班级;参加次数不需要填写,由系统按考试编码和考试日期自动计算。</div><el-table :data="results" class="score-table"><el-table-column label="学号" min-width="150" fixed><template #default="{ row }"><el-input v-model="row.studentNumber" placeholder="输入学号" @blur="lookupStudent(row)" /></template></el-table-column><el-table-column label="姓名" width="110"><template #default="{ row }"><span :class="{ 'unresolved': row.studentNumber && !row.studentName }">{{ row.studentName || '待检索' }}</span></template></el-table-column><el-table-column label="学院" min-width="150"><template #default="{ row }">{{ row.collegeName || '—' }}</template></el-table-column><el-table-column label="班级" min-width="150"><template #default="{ row }">{{ row.className || '—' }}</template></el-table-column><el-table-column v-if="selected.metricKind === 3" label="成绩" width="150"><template #default="{ row }"><el-input-number v-model="row.score" :min="0" :max="selected.maxScore" :precision="2" controls-position="right" placeholder="请输入分数" /></template></el-table-column><el-table-column v-if="selected.metricKind === 2" label="等级" width="150"><template #default="{ row }"><el-select v-model="row.level" placeholder="选择等级"><el-option v-for="level in (selected.levelOptions || '').split(',').filter(Boolean)" :key="level" :label="level" :value="level" /></el-select></template></el-table-column><el-table-column v-if="selected.metricKind === 1" label="考试结果" width="150"><template #default="{ row }"><el-select v-model="row.isPassed" placeholder="选择结果"><el-option label="合格" :value="true"/><el-option label="不合格" :value="false"/></el-select></template></el-table-column><el-table-column label="参加次数" width="100"><template #default="{ row }"><span class="auto-attempt">{{ row.attemptNumber || '自动' }}</span></template></el-table-column><el-table-column label="备注" min-width="180"><template #default="{ row }"><el-input v-model="row.notes" placeholder="可选" /></template></el-table-column></el-table><el-empty v-if="!results.length" description="还没有成绩记录,点击“新增一行”或使用批量导入" /></section>
</template>
<el-dialog v-model="dialog" title="新建其他考试场次" width="600px"><el-form label-width="100px"><el-form-item label="考试编码" required><el-input v-model="form.examCode" placeholder="如 CET4、IELTS、计算机二级;同一考试始终使用相同编码" /></el-form-item><el-form-item label="考试名称" required><el-input v-model="form.name" placeholder="如 大学英语四级" /></el-form-item><el-form-item label="组织方"><el-input v-model="form.organizer" /></el-form-item><el-form-item label="考试日期"><el-date-picker v-model="form.examDate" type="date" value-format="YYYY-MM-DD" /></el-form-item><el-form-item label="评价方式"><el-select v-model="form.metricKind"><el-option label="分数制" :value="3"/><el-option label="等级制" :value="2"/><el-option label="合格/不合格" :value="1"/></el-select></el-form-item><el-form-item v-if="form.metricKind === 3" label="满分"><el-input-number v-model="form.maxScore" :min="1" /></el-form-item><el-form-item v-if="form.metricKind === 2" label="等级顺序"><el-input v-model="form.levelOptions" placeholder="按最优到最差填写,如 A+,A,B,C,D" /></el-form-item></el-form><template #footer><el-button @click="dialog = false">取消</el-button><el-button type="primary" @click="createBatch">建立场次</el-button></template></el-dialog>
</div>
</template>
<style scoped>
.other-exams-page { --ink:#172b3a; --muted:#718391; --line:#dce6e9; --teal:#087f78; --navy:#193b68; padding-bottom:40px; }
.exam-hero { display:flex; justify-content:space-between; align-items:end; gap:24px; padding:26px 0 24px; border-bottom:1px solid var(--line); margin-bottom:20px; }
.kicker { color:var(--teal); font-size:11px; letter-spacing:.17em; font-weight:800; }.exam-hero h1,.board-title h2,.panel-heading h2,.editor-heading h2 { color:var(--ink); margin:7px 0; letter-spacing:-.025em; }.exam-hero h1 { font-size:32px; }.exam-hero p,.editor-heading p { color:var(--muted); margin:0; line-height:1.7; }.result-board,.batch-panel,.editor-panel { background:#fff; border:1px solid var(--line); border-radius:14px; box-shadow:0 12px 30px rgba(32,61,73,.06); margin-bottom:18px; overflow:hidden; }.board-title,.panel-heading { display:flex; justify-content:space-between; align-items:center; padding:20px 22px 14px; }.board-title h2,.panel-heading h2,.editor-heading h2 { font-size:20px; }.board-note,.panel-heading>span { color:var(--muted); font-size:13px; }.history-board { opacity:.96; }.best-value { color:var(--navy); font-variant-numeric:tabular-nums; }.editor-heading { display:flex; justify-content:space-between; gap:20px; align-items:center; padding:20px 22px 14px; }.editor-actions { display:flex; flex-wrap:wrap; gap:8px; justify-content:flex-end; }.upload-button { display:inline-flex; align-items:center; gap:5px; border:1px solid #dcdfe6; border-radius:4px; padding:8px 14px; color:#606266; cursor:pointer; font-size:14px; }.upload-button:hover { color:var(--navy); border-color:var(--navy); }.upload-button input { display:none; }.editor-hint { margin:0 22px 14px; padding:11px 14px; border-left:3px solid #d4a72c; background:#fff9e8; color:#786223; font-size:13px; }.auto-attempt { display:inline-flex; align-items:center; padding:4px 8px; border-radius:20px; background:#edf6f5; color:var(--teal); font-size:12px; }.unresolved { color:#c27b18; }.score-table :deep(.el-input-number) { width:125px; }.score-table :deep(.el-table__cell) { padding:12px 0; }
@media (max-width:760px) { .exam-hero,.editor-heading,.board-title,.panel-heading { display:block; }.exam-hero .el-button { margin-top:16px; }.editor-actions { justify-content:flex-start; margin-top:16px; }.board-note,.panel-heading>span { display:block; margin-top:5px; }.editor-hint { margin-left:14px; margin-right:14px; } }
.editor-heading > div:first-child { min-width: 0; }
.editor-actions { flex: 0 0 auto; }
.upload-button { flex: 0 0 auto; min-width: 112px; white-space: nowrap; justify-content: center; line-height: 1.4; }
</style>
+50 -1
View File
@@ -133,8 +133,25 @@ function resetForm(row?: any) {
enrollmentDate: `${currentYear}-09-01`,
status: 'Active',
dateOfBirth: '',
englishName: '',
idCardNumber: '',
nationality: '',
ethnicity: '',
politicalStatus: '',
nativePlace: '',
householdAddress: '',
currentAddress: '',
postalCode: '',
phone: '',
email: '',
qq: '',
weChat: '',
emergencyContactName: '',
emergencyContactRelationship: '',
emergencyContactPhone: '',
specialTags: '',
specialNeeds: '',
biography: '',
notes: '',
}, row ?? {})
}
@@ -516,7 +533,7 @@ watch(active, async () => {
</div>
</section>
<el-dialog v-model="dialogVisible" :title="`${editingId ? '编辑' : '新增'}${pageTitle}`" width="620px">
<el-dialog v-model="dialogVisible" :title="`${editingId ? '编辑' : '新增'}${pageTitle}`" width="min(860px, 94vw)">
<el-form label-position="top" class="entity-form">
<template v-if="active === 'teachers'">
<div class="form-grid">
@@ -580,6 +597,38 @@ watch(active, async () => {
</el-form-item>
</div>
<el-form-item label="出生日期"><el-date-picker v-model="form.dateOfBirth" value-format="YYYY-MM-DD" /></el-form-item>
<el-divider content-position="left">个人资料</el-divider>
<div class="form-grid">
<el-form-item label="英文姓名"><el-input v-model="form.englishName" /></el-form-item>
<el-form-item label="证件号码"><el-input v-model="form.idCardNumber" /></el-form-item>
</div>
<div class="form-grid">
<el-form-item label="国籍"><el-input v-model="form.nationality" /></el-form-item>
<el-form-item label="民族"><el-input v-model="form.ethnicity" /></el-form-item>
</div>
<div class="form-grid">
<el-form-item label="政治面貌"><el-input v-model="form.politicalStatus" /></el-form-item>
<el-form-item label="籍贯"><el-input v-model="form.nativePlace" /></el-form-item>
</div>
<div class="form-grid">
<el-form-item label="户籍地址"><el-input v-model="form.householdAddress" /></el-form-item>
<el-form-item label="现居住地址"><el-input v-model="form.currentAddress" /></el-form-item>
</div>
<div class="form-grid">
<el-form-item label="邮政编码"><el-input v-model="form.postalCode" /></el-form-item>
<el-form-item label="微信"><el-input v-model="form.weChat" /></el-form-item>
</div>
<div class="form-grid">
<el-form-item label="QQ"><el-input v-model="form.qq" /></el-form-item>
<el-form-item label="紧急联系人"><el-input v-model="form.emergencyContactName" /></el-form-item>
</div>
<div class="form-grid">
<el-form-item label="与本人关系"><el-input v-model="form.emergencyContactRelationship" /></el-form-item>
<el-form-item label="紧急联系电话"><el-input v-model="form.emergencyContactPhone" /></el-form-item>
</div>
<el-form-item label="特殊标记"><el-input v-model="form.specialTags" placeholder="多个标记可用逗号分隔" /></el-form-item>
<el-form-item label="特殊情况说明"><el-input v-model="form.specialNeeds" type="textarea" :rows="3" /></el-form-item>
<el-form-item label="个人简介"><el-input v-model="form.biography" type="textarea" :rows="3" /></el-form-item>
</template>
<div class="form-grid">
<el-form-item label="联系电话"><el-input v-model="form.phone" /></el-form-item>
+48 -16
View File
@@ -125,6 +125,19 @@ const publishStatusText = computed(() => {
const selectedTaskConstraint = computed(() =>
constraints.value.find((item) => item.id === entryForm.teachingTaskId),
)
const isExperimentRoom = (room: any) =>
['实验', '实训', '机房', '语音'].some((keyword) => room.roomType?.includes(keyword))
const entryClassrooms = computed(() =>
classrooms.value.filter((room) =>
(!selectedTaskConstraint.value?.requiredCampusId
|| room.campusId === selectedTaskConstraint.value.requiredCampusId) &&
(!selectedTaskConstraint.value?.requiredBuildingId
|| room.buildingId === selectedTaskConstraint.value.requiredBuildingId) &&
(!selectedTaskConstraint.value?.allowedClassroomIds?.length
|| selectedTaskConstraint.value.allowedClassroomIds.includes(room.id)) &&
(entryForm.kind !== 'Experiment' || isExperimentRoom(room)),
),
)
const entryWeekdays = computed(() => {
const allowedDays = selectedTaskConstraint.value?.allowedDayOfWeeks ?? []
return allowedDays.length
@@ -416,7 +429,7 @@ function openManualHandling() {
async function autoSchedule() {
try {
await ElMessageBox.confirm(
'系统会保留当前手工安排,并为尚未排满的教学任务分配教师可用时间和符合约束的教室。生成后仍可手工调整。',
'系统会保留当前手工安排,同时补齐理论课和实验课。实验课仅使用实验室、实训室、机房等场地;生成后仍可手工调整。',
'开始自动排课',
{ type: 'warning', confirmButtonText: '生成排课', cancelButtonText: '取消' },
)
@@ -657,6 +670,7 @@ function openEntry(entry?: any, day?: number, period?: number) {
editingEntryId.value = entry?.id ?? ''
Object.assign(entryForm, {
teachingTaskId: entry?.teachingTaskId,
kind: entry?.kind ?? 'Lecture',
classroomId: entry?.classroomId,
dayOfWeek: entry?.dayOfWeek ?? day ?? 1,
startPeriod: entry?.startPeriod ?? period ?? 1,
@@ -679,7 +693,7 @@ function changeEntryTask() {
!task.allowedDayOfWeeks.includes(entryForm.dayOfWeek)) {
entryForm.dayOfWeek = task.allowedDayOfWeeks[0]
}
if (task.requiresClassroom === false) {
if (task.requiresClassroom === false && entryForm.kind !== 'Experiment') {
entryForm.classroomId = null
return
}
@@ -687,15 +701,25 @@ function changeEntryTask() {
if (room && (
(task.requiredCampusId && room.campusId !== task.requiredCampusId) ||
(task.requiredBuildingId && room.buildingId !== task.requiredBuildingId) ||
(task.allowedClassroomIds?.length && !task.allowedClassroomIds.includes(room.id))
(task.allowedClassroomIds?.length && !task.allowedClassroomIds.includes(room.id)) ||
(entryForm.kind === 'Experiment' && !isExperimentRoom(room))
)) {
entryForm.classroomId = null
}
}
function changeEntryKind() {
const room = classrooms.value.find((item) => item.id === entryForm.classroomId)
if (entryForm.kind === 'Experiment' && room && !isExperimentRoom(room)) {
entryForm.classroomId = null
}
}
async function saveEntry() {
if (!entryForm.teachingTaskId ||
(selectedTaskConstraint.value?.requiresClassroom !== false && !entryForm.classroomId)) {
((entryForm.kind === 'Experiment' ||
selectedTaskConstraint.value?.requiresClassroom !== false) &&
!entryForm.classroomId)) {
ElMessage.warning('请选择教学任务,并按课程要求选择教室。')
return
}
@@ -714,7 +738,8 @@ async function saveEntry() {
ElMessage.warning('所选星期不在该教学任务允许的上课日内。')
return
}
if (selectedTaskConstraint.value?.requiresClassroom === false) entryForm.classroomId = null
if (entryForm.kind !== 'Experiment' &&
selectedTaskConstraint.value?.requiresClassroom === false) entryForm.classroomId = null
try {
const base = `/schedules/plans/${selected.value.id}/entries`
if (editingEntryId.value) await http.put(`${base}/${editingEntryId.value}`, entryForm)
@@ -928,10 +953,13 @@ onBeforeUnmount(() => {
v-for="entry in entriesAt(day.value, period)"
:key="entry.id"
class="schedule-card"
:class="{ readonly: !isDraft }"
:class="{ readonly: !isDraft, experiment: entry.kind === 'Experiment' }"
@click="isDraft && openEntry(entry)"
>
<span>{{ entry.courseCode }} · {{ patternLabels[entry.weekPattern] }}</span>
<span>
{{ entry.kind === 'Experiment' ? '实验课' : '理论课' }} ·
{{ entry.courseCode }} · {{ patternLabels[entry.weekPattern] }}
</span>
<b>{{ entry.courseName }}</b>
<small>{{ entry.teacherNames.join('、') }} · {{ entry.classroomName || '不占用教室' }}</small>
<i>{{ entry.startWeek }}{{ entry.endWeek }} / 连上 {{ entry.periodCount }} </i>
@@ -986,15 +1014,23 @@ onBeforeUnmount(() => {
<el-option v-for="item in tasks" :key="item.id" :label="`${item.taskNumber} · ${item.name}`" :value="item.id" />
</el-select>
</el-form-item>
<el-form-item label="课次类型" required>
<el-radio-group v-model="entryForm.kind" @change="changeEntryKind">
<el-radio-button value="Lecture">理论课</el-radio-button>
<el-radio-button value="Experiment" :disabled="!selectedTaskConstraint?.coursePracticeHours">
实验课
</el-radio-button>
</el-radio-group>
</el-form-item>
<el-alert
v-if="selectedTaskConstraint"
:title="`普通课表每周 ${selectedTaskConstraint.weeklyHours} 学时(实践 ${selectedTaskConstraint.coursePracticeHours} 学时另由实验管理安排);可排第 ${selectedTaskConstraint.startWeek}—${selectedTaskConstraint.endWeek} 周;允许上课日:${entryWeekdays.map((day) => day.label).join('、')}`"
:title="`课程共 ${selectedTaskConstraint.courseTotalHours} 学时:理论 ${selectedTaskConstraint.courseTotalHours - selectedTaskConstraint.coursePracticeHours} 学时、实验 ${selectedTaskConstraint.coursePracticeHours} 学时,均须在本课表排足;可排第 ${selectedTaskConstraint.startWeek}—${selectedTaskConstraint.endWeek} 周;允许上课日:${entryWeekdays.map((day) => day.label).join('、')}`"
type="info"
:closable="false"
show-icon
/>
<el-alert
v-if="selectedTaskConstraint?.requiresClassroom === false"
v-if="selectedTaskConstraint?.requiresClassroom === false && entryForm.kind !== 'Experiment'"
title="该课程不占用教室,仍会校验教师和行政班时间冲突。"
type="info"
:closable="false"
@@ -1002,19 +1038,15 @@ onBeforeUnmount(() => {
/>
<el-form-item
v-else
label="教室"
:label="entryForm.kind === 'Experiment' ? '实验室 / 实训室 / 机房' : '教室'"
required
:hint="selectedTaskConstraint?.requiredBuildingId ? '仅显示约束范围内教室' : ''"
>
<el-select v-model="entryForm.classroomId" filterable>
<el-option
v-for="item in classrooms.filter((room) =>
(!selectedTaskConstraint?.requiredCampusId || room.campusId === selectedTaskConstraint.requiredCampusId) &&
(!selectedTaskConstraint?.requiredBuildingId || room.buildingId === selectedTaskConstraint.requiredBuildingId) &&
(!selectedTaskConstraint?.allowedClassroomIds?.length || selectedTaskConstraint.allowedClassroomIds.includes(room.id))
)"
v-for="item in entryClassrooms"
:key="item.id"
:label="`${item.campusName} / ${item.buildingName} / ${item.name}${item.capacity}人)`"
:label="`${item.campusName} / ${item.buildingName} / ${item.name}${item.roomType}${item.capacity}人)`"
:value="item.id"
/>
</el-select>
+109
View File
@@ -0,0 +1,109 @@
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import http, { apiErrorMessage } from '../api/http'
import { useAuthStore } from '../stores/auth'
const route = useRoute()
const router = useRouter()
const auth = useAuthStore()
const loading = ref(false)
const checking = ref(true)
const binding = reactive({
providerDisplayName: '学校统一身份认证',
externalUserName: '',
})
const form = reactive({ userName: '', password: '' })
function safeRedirect(value: unknown) {
const path = String(value ?? '')
return path.startsWith('/') && !path.startsWith('//') ? path : '/dashboard'
}
async function submit() {
if (!form.userName.trim() || !form.password) {
ElMessage.warning('请填写现有教务系统账号和密码。')
return
}
loading.value = true
try {
await auth.bindSso(String(route.query.code ?? ''), form.userName, form.password)
ElMessage.success('账户绑定成功。')
await router.replace(safeRedirect(route.query.redirect))
} catch (error) {
ElMessage.error(apiErrorMessage(error))
} finally {
loading.value = false
}
}
onMounted(async () => {
const code = String(route.query.code ?? '')
if (!code) {
await router.replace({ name: 'login', query: { ssoError: 'authentication_failed' } })
return
}
try {
const { data } = await http.get('/auth/sso/binding', { params: { code } })
binding.providerDisplayName = String(data.providerDisplayName || binding.providerDisplayName)
binding.externalUserName = String(data.externalUserName || '')
} catch (error) {
ElMessage.error(apiErrorMessage(error))
await router.replace({ name: 'login', query: { ssoError: 'binding_expired' } })
} finally {
checking.value = false
}
})
</script>
<template>
<main class="sso-binding-page">
<section v-loading="checking" class="sso-binding-card">
<div class="brand-mark" aria-hidden="true">
<span v-for="index in 9" :key="index" />
</div>
<span class="eyebrow">首次使用统一身份认证</span>
<h1>绑定现有教务系统账号</h1>
<p class="binding-description">
已通过{{ binding.providerDisplayName }}验证
<strong v-if="binding.externalUserName">{{ binding.externalUserName }}</strong>
请输入一次现有教务系统账号和密码今后即可直接使用单点登录
</p>
<form @submit.prevent="submit">
<label>
<span>教务系统账号</span>
<el-input v-model="form.userName" size="large" autocomplete="username" />
</label>
<label>
<span>教务系统密码</span>
<el-input
v-model="form.password"
size="large"
type="password"
show-password
autocomplete="current-password"
@keyup.enter="submit"
/>
</label>
<el-button
class="binding-submit"
type="primary"
size="large"
native-type="submit"
:loading="loading"
:disabled="checking"
>
确认绑定并登录
</el-button>
</form>
<p class="binding-security-note">
绑定只建立登录关联不会修改您的角色学院或人员档案
</p>
<router-link to="/login">取消并返回登录页</router-link>
</section>
</main>
</template>
+39
View File
@@ -0,0 +1,39 @@
<script setup lang="ts">
import { onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { apiErrorMessage } from '../api/http'
import { useAuthStore } from '../stores/auth'
const route = useRoute()
const router = useRouter()
const auth = useAuthStore()
function safeRedirect(value: unknown) {
const path = String(value ?? '')
return path.startsWith('/') && !path.startsWith('//') ? path : '/dashboard'
}
onMounted(async () => {
const code = String(route.query.code ?? '')
if (!code) {
await router.replace({ name: 'login', query: { ssoError: 'authentication_failed' } })
return
}
try {
await auth.exchangeSso(code)
await router.replace(safeRedirect(route.query.redirect))
} catch (error) {
ElMessage.error(apiErrorMessage(error))
await router.replace({ name: 'login', query: { ssoError: 'authentication_failed' } })
}
})
</script>
<template>
<main class="sso-callback-page">
<el-icon class="is-loading" :size="34"><Loading /></el-icon>
<h1>正在完成统一身份认证</h1>
<p>请稍候不要关闭此页面</p>
</main>
</template>
+169
View File
@@ -0,0 +1,169 @@
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { Check, EditPen, Refresh } from '@element-plus/icons-vue'
import http, { apiErrorMessage } from '../api/http'
const loading = ref(true)
const saving = ref(false)
const editing = ref(false)
const profile = reactive<Record<string, any>>({})
const form = reactive<Record<string, any>>({})
const genderLabels: Record<string, string> = {
Unknown: '未设置', Male: '男', Female: '女',
}
const statusLabels: Record<string, string> = {
Active: '在籍', Suspended: '休学', Graduated: '毕业', Withdrawn: '退学',
}
const editableFields = [
'gender', 'dateOfBirth', 'englishName', 'idCardNumber', 'nationality',
'ethnicity', 'politicalStatus', 'nativePlace', 'householdAddress',
'currentAddress', 'postalCode', 'phone', 'email', 'qq', 'weChat',
'emergencyContactName', 'emergencyContactRelationship',
'emergencyContactPhone', 'specialTags', 'specialNeeds', 'biography',
]
function copyToForm() {
for (const key of editableFields) form[key] = profile[key] ?? ''
}
async function load() {
loading.value = true
try {
Object.assign(profile, (await http.get('/student/profile')).data)
copyToForm()
} catch (error) {
ElMessage.error(apiErrorMessage(error))
} finally {
loading.value = false
}
}
function startEdit() {
copyToForm()
editing.value = true
}
function cancelEdit() {
copyToForm()
editing.value = false
}
async function save() {
saving.value = true
try {
await http.put('/student/profile', form)
ElMessage.success('个人信息已保存,无需审核。')
editing.value = false
await load()
} catch (error) {
ElMessage.error(apiErrorMessage(error))
} finally {
saving.value = false
}
}
onMounted(load)
</script>
<template>
<div class="profile-page" v-loading="loading">
<section class="profile-hero">
<div>
<span>STUDENT PROFILE</span>
<h2>我的个人信息</h2>
<p>完善个人资料联系方式与需要任课教师关注的特殊情况</p>
</div>
<div class="profile-actions">
<el-button :icon="Refresh" @click="load">刷新</el-button>
<el-button v-if="!editing" type="primary" :icon="EditPen" @click="startEdit">修改信息</el-button>
<template v-else>
<el-button @click="cancelEdit">取消</el-button>
<el-button type="primary" :icon="Check" :loading="saving" @click="save">直接保存</el-button>
</template>
</div>
</section>
<el-alert
title="联系电话、电子邮箱、微信、紧急联系人以及特殊标记/说明会向你的任课教师展示,并写入教学班名单导出文件。"
type="info"
:closable="false"
show-icon
/>
<section class="identity-strip">
<div><span>学号</span><b>{{ profile.studentNumber }}</b><small>不可自行修改</small></div>
<div><span>姓名</span><b>{{ profile.name }}</b><small>不可自行修改</small></div>
<div><span>学院 / 专业</span><b>{{ profile.collegeName }}</b><small>{{ profile.majorName }}</small></div>
<div><span>行政班 / 学籍</span><b>{{ profile.className }}</b><small>{{ statusLabels[profile.status] }} · {{ profile.enrollmentYear }} </small></div>
</section>
<el-form :model="form" label-position="top" class="profile-form" :disabled="!editing">
<article class="profile-card">
<header><span>01</span><div><h3>身份与背景</h3><p>除学号和姓名外可直接维护常用身份信息</p></div></header>
<div class="form-grid">
<el-form-item label="英文姓名"><el-input v-model="form.englishName" maxlength="100" /></el-form-item>
<el-form-item label="性别"><el-select v-model="form.gender"><el-option v-for="(label, value) in genderLabels" :key="value" :label="label" :value="value" /></el-select></el-form-item>
<el-form-item label="出生日期"><el-date-picker v-model="form.dateOfBirth" value-format="YYYY-MM-DD" /></el-form-item>
<el-form-item label="证件号码"><el-input v-model="form.idCardNumber" maxlength="30" /></el-form-item>
<el-form-item label="国籍"><el-input v-model="form.nationality" maxlength="50" /></el-form-item>
<el-form-item label="民族"><el-input v-model="form.ethnicity" maxlength="50" /></el-form-item>
<el-form-item label="政治面貌"><el-input v-model="form.politicalStatus" maxlength="50" /></el-form-item>
<el-form-item label="籍贯"><el-input v-model="form.nativePlace" maxlength="100" /></el-form-item>
</div>
</article>
<article class="profile-card">
<header><span>02</span><div><h3>联系方式与地址</h3><p>任课教师仅能看到本区的电话邮箱和微信</p></div></header>
<div class="form-grid">
<el-form-item label="联系电话"><el-input v-model="form.phone" maxlength="30" /></el-form-item>
<el-form-item label="电子邮箱"><el-input v-model="form.email" maxlength="100" /></el-form-item>
<el-form-item label="微信"><el-input v-model="form.weChat" maxlength="60" /></el-form-item>
<el-form-item label="QQ"><el-input v-model="form.qq" maxlength="30" /></el-form-item>
<el-form-item label="邮政编码"><el-input v-model="form.postalCode" maxlength="20" /></el-form-item>
<el-form-item label="户籍地址" class="span-2"><el-input v-model="form.householdAddress" maxlength="300" /></el-form-item>
<el-form-item label="现居住地址" class="span-2"><el-input v-model="form.currentAddress" maxlength="300" /></el-form-item>
</div>
</article>
<article class="profile-card attention-card">
<header><span>03</span><div><h3>紧急联系与特殊标记</h3><p>本区内容会向任课教师展示请填写真实且必要的信息</p></div></header>
<div class="form-grid">
<el-form-item label="紧急联系人"><el-input v-model="form.emergencyContactName" maxlength="50" /></el-form-item>
<el-form-item label="与本人关系"><el-input v-model="form.emergencyContactRelationship" maxlength="30" /></el-form-item>
<el-form-item label="紧急联系电话"><el-input v-model="form.emergencyContactPhone" maxlength="30" /></el-form-item>
<el-form-item label="特殊标记"><el-input v-model="form.specialTags" maxlength="300" placeholder="多个标记可用逗号分隔" /></el-form-item>
<el-form-item label="特殊情况说明" class="span-2"><el-input v-model="form.specialNeeds" type="textarea" :rows="4" maxlength="1000" show-word-limit placeholder="例如学习支持、健康与安全方面需教师留意的事项" /></el-form-item>
<el-form-item label="个人简介" class="span-2"><el-input v-model="form.biography" type="textarea" :rows="4" maxlength="1000" show-word-limit /></el-form-item>
</div>
</article>
</el-form>
</div>
</template>
<style scoped>
.profile-page { display: grid; gap: 18px; }
.profile-hero { display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 26px 30px; border-radius: 18px; color: white; background: linear-gradient(125deg, #173a50, #176b87 62%, #2e9b91); box-shadow: 0 18px 45px rgba(23, 58, 80, .16); }
.profile-hero span { color: #8ee4d8; font-size: 11px; font-weight: 800; letter-spacing: .12em; }
.profile-hero h2 { margin: 7px 0 5px; font-size: 30px; font-family: "STZhongsong", "Songti SC", serif; }
.profile-hero p { margin: 0; color: rgba(255,255,255,.75); }
.profile-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; }
.identity-strip { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); border: 1px solid var(--line); background: white; }
.identity-strip > div { display: grid; gap: 5px; padding: 18px 20px; border-right: 1px solid var(--line); }
.identity-strip > div:last-child { border-right: 0; }
.identity-strip span, .identity-strip small { color: var(--muted); font-size: 12px; }
.identity-strip b { color: #263445; }
.profile-form { display: grid; gap: 18px; }
.profile-card { padding: 24px; border: 1px solid var(--line); border-radius: 14px; background: white; box-shadow: 0 10px 28px rgba(35,57,78,.05); }
.profile-card > header { display: flex; gap: 14px; margin-bottom: 22px; padding-bottom: 16px; border-bottom: 1px solid #edf0f3; }
.profile-card > header > span { color: var(--teal); font: 800 12px/1 Consolas, monospace; }
.profile-card h3 { margin: 0 0 5px; color: #263445; }
.profile-card p { margin: 0; color: var(--muted); font-size: 12px; }
.attention-card { border-top: 3px solid #d89b36; }
.form-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0 18px; }
.span-2 { grid-column: span 2; }
:deep(.el-form.is-disabled .el-input__wrapper), :deep(.el-form.is-disabled .el-textarea__inner) { background: #f8fafb; color: #364655; }
@media (max-width: 900px) { .identity-strip { grid-template-columns: repeat(2, 1fr); } .form-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (max-width: 620px) { .profile-hero { align-items: flex-start; flex-direction: column; padding: 22px; } .profile-actions { justify-content: flex-start; } .identity-strip, .form-grid { grid-template-columns: 1fr; } .identity-strip > div { border-right: 0; border-bottom: 1px solid var(--line); } .span-2 { grid-column: auto; } .profile-card { padding: 18px; } }
</style>
+28
View File
@@ -118,6 +118,31 @@ onMounted(async () => {
<el-table-column prop="name" label="姓名" min-width="100" />
<el-table-column prop="className" label="班级" min-width="130" />
<el-table-column prop="majorName" label="专业" min-width="150" />
<el-table-column label="联系方式" min-width="210">
<template #default="{ row }">
<div class="contact-cell">
<span>{{ row.phone || '未填写电话' }}</span>
<small>{{ row.email || row.weChat ? [row.email, row.weChat && `微信 ${row.weChat}`].filter(Boolean).join(' · ') : '未填写邮箱或微信' }}</small>
</div>
</template>
</el-table-column>
<el-table-column label="紧急联系人" min-width="180">
<template #default="{ row }">
<div class="contact-cell">
<span>{{ row.emergencyContactName || '—' }}<template v-if="row.emergencyContactRelationship">{{ row.emergencyContactRelationship }}</template></span>
<small>{{ row.emergencyContactPhone || '未填写联系电话' }}</small>
</div>
</template>
</el-table-column>
<el-table-column label="特殊标记" min-width="210">
<template #default="{ row }">
<div class="special-cell">
<el-tag v-if="row.specialTags" type="warning" effect="light">{{ row.specialTags }}</el-tag>
<span v-else></span>
<small v-if="row.specialNeeds">{{ row.specialNeeds }}</small>
</div>
</template>
</el-table-column>
<el-table-column label="名单来源" width="210">
<template #default="{ row }">{{ row.enrolledAt ? `选课 · ${new Date(row.enrolledAt).toLocaleString('zh-CN')}` : '行政班关联' }}</template>
</el-table-column>
@@ -156,6 +181,9 @@ onMounted(async () => {
.roster-head h3 { margin: 5px 0 4px; font-size: 18px; }
.roster-head p { color: var(--muted); font-size: 12px; margin: 0; }
.roster-head span { color: var(--teal); font-size: 10px; font-weight: 700; }
.contact-cell, .special-cell { display: grid; gap: 4px; line-height: 1.35; }
.contact-cell small, .special-cell small { color: var(--muted); white-space: normal; }
.special-cell .el-tag { width: fit-content; max-width: 100%; white-space: normal; height: auto; padding-block: 3px; }
@media (max-width: 760px) {
.roster-workspace { grid-template-columns: 1fr; }
.roster-task-list { max-height: 220px; border-right: none; border-bottom: 1px solid var(--line); }
+7 -9
View File
@@ -79,12 +79,10 @@ const selectedCourse = computed(() =>
)
const regularScheduleHours = (course: any) =>
Math.max(0, Number(course?.totalHours ?? 0) - Number(course?.practiceHours ?? 0))
const targetCourseHours = (course: any, schedulingMode: string) =>
schedulingMode === 'Flexible'
? Number(course?.totalHours ?? 0)
: regularScheduleHours(course)
const targetCourseHours = (course: any) =>
Number(course?.totalHours ?? 0)
const selectedCourseTargetHours = computed(() =>
targetCourseHours(selectedCourse.value, form.schedulingMode),
targetCourseHours(selectedCourse.value),
)
const plannedHours = computed(() =>
form.startWeek && form.endWeek && form.weeklyHours && form.endWeek >= form.startWeek
@@ -124,7 +122,7 @@ const generationPlannedHours = computed(() =>
)
const generationHoursMatch = computed(() =>
!selectedGenerationCourse.value ||
generationPlannedHours.value === regularScheduleHours(selectedGenerationCourse.value),
generationPlannedHours.value === Number(selectedGenerationCourse.value?.totalHours ?? 0),
)
const manageableCourses = computed(() => {
if (isSuperAdmin.value) return courses.value
@@ -364,7 +362,7 @@ async function save() {
}
if (!hoursMatch.value) {
ElMessage.warning(
`该课程普通课表应安排 ${selectedCourseTargetHours.value} 学时,当前安排合计 ${plannedHours.value} 学时;实践学时请在实验管理中安排`,
`该课程理论课和实验课共应安排 ${selectedCourseTargetHours.value} 学时,当前安排合计 ${plannedHours.value} 学时。`,
)
return
}
@@ -551,7 +549,7 @@ async function generatePublicTasks() {
}
if (!generationHoursMatch.value) {
ElMessage.warning(
`该课程普通课表应安排 ${regularScheduleHours(selectedGenerationCourse.value)} 学时,当前安排合计 ${generationPlannedHours.value} 学时;实践学时不进入普通课表`,
`该课程理论课和实验课共应安排 ${selectedGenerationCourse.value?.totalHours ?? 0} 学时,当前安排合计 ${generationPlannedHours.value} 学时。`,
)
return
}
@@ -773,7 +771,7 @@ onMounted(async () => {
<el-radio-button value="Flexible">非排时课程</el-radio-button>
</el-radio-group>
<small class="field-hint">
正常排课只安排非实践学时全部由实验模块安排的课程选择非排时课程
正常排课会同时安排理论课和实验课只有无需固定星期节次和场地的课程选择非排时课程
</small>
</el-form-item>
<el-form-item label="授课教师">
+12 -1
View File
@@ -1014,12 +1014,14 @@ onMounted(async () => {
:class="{
'exam-block': entry.isExam,
'experiment-block': entry.isExperiment,
'scheduled-experiment-block': !entry.isExperiment && entry.kind === 'Experiment',
}"
:style="gridEntryStyle(entry)"
>
<strong>
<span v-if="entry.isExam" class="entry-kind">考试</span>
<span v-if="entry.isExperiment" class="entry-kind experiment-kind">实验</span>
<span v-if="!entry.isExperiment && entry.kind === 'Experiment'" class="entry-kind scheduled-experiment-kind">实验课</span>
{{ entry.isExperiment ? entry.experimentProjectName : entry.courseName }}
</strong>
<span v-if="entry.isExam && entry.examPlanName">{{ entry.examPlanName }}</span>
@@ -1064,12 +1066,14 @@ onMounted(async () => {
:class="{
'exam-block': entry.isExam,
'experiment-block': entry.isExperiment,
'scheduled-experiment-block': !entry.isExperiment && entry.kind === 'Experiment',
}"
:style="dayEntryStyle(entry)"
>
<strong>
<span v-if="entry.isExam" class="entry-kind">考试</span>
<span v-if="entry.isExperiment" class="entry-kind experiment-kind">实验</span>
<span v-if="!entry.isExperiment && entry.kind === 'Experiment'" class="entry-kind scheduled-experiment-kind">实验课</span>
{{ entry.isExperiment ? entry.experimentProjectName : entry.courseName }}
</strong>
<span v-if="entry.isExam && entry.examPlanName">{{ entry.examPlanName }}</span>
@@ -1113,7 +1117,11 @@ onMounted(async () => {
{{ entry.startWeek }} ·
{{ entry.startPeriod }}{{ entry.startPeriod + entry.periodCount - 1 }}
</small>
<small>{{ entry.teacherNames.join('、') || '监考教师待定' }}</small>
<small v-if="entry.examRoomCount > 1">
任课教师{{ entry.teacherNames.join('、') || '待定' }} ·
学生登录后可查看本人考场及监考教师
</small>
<small v-else>{{ entry.teacherNames.join('') || '监考教师待定' }}</small>
</div>
</article>
</div>
@@ -1329,6 +1337,9 @@ onMounted(async () => {
.course-block.experiment-block small, .day-course-block.experiment-block small { color: #527a74; }
.entry-kind { display: inline-block; margin-right: 5px; padding: 1px 5px; border-radius: 2px; background: #b65b32; color: #fff; font-size: 10px !important; line-height: 1.5; vertical-align: 1px; }
.entry-kind.experiment-kind { background: #168276; }
.course-block.scheduled-experiment-block, .day-course-block.scheduled-experiment-block { border-left-color: #b77819; background: #fff6df; color: #73521f; }
.course-block.scheduled-experiment-block strong, .day-course-block.scheduled-experiment-block strong { color: #66430e; }
.entry-kind.scheduled-experiment-kind { background: #b77819; }
.exam-overview { margin-top: 20px; border: 1px solid #e2d6cf; background: #fffaf7; }
.exam-overview > header { padding: 14px 16px; display: flex; align-items: center; justify-content: space-between; gap: 16px; border-bottom: 1px solid #eaded7; background: #fff5ef; }
.exam-overview > header > div { display: flex; align-items: baseline; gap: 10px; }
+8
View File
@@ -1,15 +1,23 @@
import { defineConfig, loadEnv } from 'vite'
import { readFileSync } from 'node:fs'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
const packageJson = JSON.parse(
readFileSync(new URL('./package.json', import.meta.url), 'utf8'),
) as { version: string }
// https://vite.dev/config/
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '')
const isCapacitor = env.VITE_ROUTER_MODE === 'hash'
return {
define: {
__APP_VERSION__: JSON.stringify(packageJson.version),
},
plugins: [
vue(),
AutoImport({