diff --git a/README.md b/README.md index 8615ef9..7ab8bd6 100644 --- a/README.md +++ b/README.md @@ -291,6 +291,8 @@ Kubernetes 或密钥管理系统仍可覆盖文件中的值。 配置 `Moodle__TeacherRoleId` 并为服务账户提供 `core_user_get_users_by_field`、`enrol_manual_enrol_users` 和相应用户查询、手动选课及角色分配权限后,管理员可在已关联的教学任务中同步授课教师。教务工号须与 Moodle 用户名一致;系统先检查所有教师账号,再加入课程,不会自动创建账号或移除 Moodle 中已有的教师。课程需启用 Moodle 手动选课方式。 +配置 `Moodle__StudentRoleId` 后,有管理权限的管理员或该教学班的任课教师可将当前教学班名单导入 Moodle,学号须与 Moodle 用户名一致。名单包括行政班关联和正式选课学生,排除学籍异动限制;导入是增量操作,不会自动移除退课学生或创建账号。导入前应确认选课名单,名单变化后可重复导入;需要撤销访问时须在 Moodle 中处理。 + 管理员也可输入 Moodle 历史课程的数字 ID 来复制课程;需要启用 `core_course_duplicate_course` 并授予来源课程备份和目标分类恢复权限。复制不包含旧用户及其数据。复制超时或失败时,Moodle 可能留下未完成课程;须先在 Moodle 检查结果并处理,再手动关联,不应直接认定复制成功。 ### Keycloak 单点登录(可选) diff --git a/src/Jiaowu.Api/Controllers/MoodleCoursesController.cs b/src/Jiaowu.Api/Controllers/MoodleCoursesController.cs index 19cd338..5b5a834 100644 --- a/src/Jiaowu.Api/Controllers/MoodleCoursesController.cs +++ b/src/Jiaowu.Api/Controllers/MoodleCoursesController.cs @@ -10,12 +10,37 @@ using Microsoft.EntityFrameworkCore; namespace Jiaowu.Api.Controllers; [ApiController] -[Authorize(Roles = SystemRoles.SuperAdmin + "," + SystemRoles.AcademicAdmin + "," + SystemRoles.CollegeAdmin)] +[Authorize(Roles = SystemRoles.SuperAdmin + "," + SystemRoles.AcademicAdmin + "," + SystemRoles.CollegeAdmin + "," + SystemRoles.Teacher)] [Route("api/moodle-courses")] public sealed class MoodleCoursesController(AppDbContext db, ICurrentUserDataScope scope, MoodleCourseClient moodle) : ControllerBase { [HttpGet("availability")] - public ActionResult Availability() => Ok(new { available = moodle.IsConfigured, teacherSync = moodle.CanSyncTeachers }); + public ActionResult Availability() => Ok(new { available = moodle.IsConfigured, teacherSync = moodle.CanSyncTeachers, studentSync = moodle.CanSyncStudents }); + + [HttpPost("teaching-tasks/{id:guid}/students")] + public async Task SyncStudents(Guid id, CancellationToken ct) + { + var task = await db.TeachingTasks.AsNoTracking().Where(x => x.Id == id) + .Select(x => new { x.Id, x.Status, x.MoodleCourseUrl, x.Course!.CollegeId, x.Course.Nature, + IsTeacher = x.Teachers.Any(t => t.Teacher!.UserId == scope.Current.UserId) }).SingleOrDefaultAsync(ct); + if (task is null) return NotFound(); + var authorized = TeachingTaskMaintenancePolicy.CanManage(scope.Current, task.CollegeId, task.Nature) || + scope.Current.IsInRole(SystemRoles.Teacher) && task.IsTeacher; + if (!authorized) return Forbid(); + if (task.Status != TeachingTaskStatus.Published || task.MoodleCourseUrl is null) + return Conflict(new ProblemDetails { Detail = "请先发布教学任务并关联 Moodle 课程。", Status = 409 }); + var numbers = await TeachingTaskRosterQuery.ForTask(db, id).AsNoTracking() + .OrderBy(x => x.StudentNumber).Select(x => x.StudentNumber).ToListAsync(ct); + try + { + await moodle.SyncStudentsAsync(task.MoodleCourseUrl, numbers, ct); + return Ok(new { count = numbers.Count }); + } + catch (MoodleIntegrationException ex) + { + return StatusCode(502, new ProblemDetails { Title = "Moodle 学生导入失败", Detail = ex.Message, Status = 502 }); + } + } [HttpPost("teaching-tasks/{id:guid}/teachers")] public async Task SyncTeachers(Guid id, CancellationToken ct) diff --git a/src/Jiaowu.Api/Infrastructure/Teaching/MoodleCourseClient.cs b/src/Jiaowu.Api/Infrastructure/Teaching/MoodleCourseClient.cs index 0ae22d7..1ae3d2b 100644 --- a/src/Jiaowu.Api/Infrastructure/Teaching/MoodleCourseClient.cs +++ b/src/Jiaowu.Api/Infrastructure/Teaching/MoodleCourseClient.cs @@ -6,18 +6,25 @@ public sealed class MoodleCourseClient(IHttpClientFactory clients, IConfiguratio { public bool IsConfigured => TryGetSettings(out _, out _, out _); public bool CanSyncTeachers => IsConfigured && int.TryParse(configuration["Moodle:TeacherRoleId"], out var role) && role > 0; + public bool CanSyncStudents => IsConfigured && int.TryParse(configuration["Moodle:StudentRoleId"], out var role) && role > 0; - public async Task SyncTeachersAsync(string courseUrl, IReadOnlyList teacherNumbers, CancellationToken ct) + public Task SyncTeachersAsync(string courseUrl, IReadOnlyList teacherNumbers, CancellationToken ct) => + EnrolUsersAsync(courseUrl, teacherNumbers, "TeacherRoleId", ct); + + public Task SyncStudentsAsync(string courseUrl, IReadOnlyList studentNumbers, CancellationToken ct) => + EnrolUsersAsync(courseUrl, studentNumbers, "StudentRoleId", ct); + + private async Task EnrolUsersAsync(string courseUrl, IReadOnlyList teacherNumbers, string roleSetting, CancellationToken ct) { if (!TryGetSettings(out var baseUri, out var token, out _) || - !int.TryParse(configuration["Moodle:TeacherRoleId"], out var roleId) || roleId <= 0) - throw new MoodleIntegrationException("请配置 Moodle 教师角色 ID 和服务连接。"); + !int.TryParse(configuration[$"Moodle:{roleSetting}"], out var roleId) || roleId <= 0) + throw new MoodleIntegrationException("请配置 Moodle 对应角色 ID 和服务连接。"); if (!Uri.TryCreate(courseUrl, UriKind.Absolute, out var courseUri) || !string.Equals(courseUri.GetLeftPart(UriPartial.Path), new Uri(baseUri, "course/view.php").GetLeftPart(UriPartial.Path), StringComparison.OrdinalIgnoreCase) || !Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(courseUri.Query).TryGetValue("id", out var idText) || !long.TryParse(idText.ToString(), out var courseId) || courseId <= 0) throw new MoodleIntegrationException("课程链接与配置的 Moodle 站点不匹配,无法同步教师。"); - if (teacherNumbers.Count == 0) throw new MoodleIntegrationException("教学任务没有授课教师。"); + if (teacherNumbers.Count == 0) throw new MoodleIntegrationException("教学任务名单为空。"); var usersQuery = new Dictionary { ["field"] = "username" }; for (var i = 0; i < teacherNumbers.Count; i++) usersQuery[$"values[{i}]"] = teacherNumbers[i]; using var response = await CallAsync(baseUri, token, "core_user_get_users_by_field", usersQuery, ct); @@ -32,7 +39,7 @@ public sealed class MoodleCourseClient(IHttpClientFactory clients, IConfiguratio throw new MoodleIntegrationException("Moodle 用户信息无效或存在重复、停用账号。"); } if (teacherNumbers.Any(number => !users.ContainsKey(number))) - throw new MoodleIntegrationException("部分教师工号未匹配到 Moodle 用户名,请检查账号后重试。"); + throw new MoodleIntegrationException("部分人员编号未匹配到 Moodle 用户名,请检查账号后重试。"); var enrollments = new Dictionary(); for (var i = 0; i < teacherNumbers.Count; i++) { diff --git a/tests/Jiaowu.Api.Tests/MoodleCourseClientTests.cs b/tests/Jiaowu.Api.Tests/MoodleCourseClientTests.cs index 5d4510e..01d81ab 100644 --- a/tests/Jiaowu.Api.Tests/MoodleCourseClientTests.cs +++ b/tests/Jiaowu.Api.Tests/MoodleCourseClientTests.cs @@ -6,6 +6,21 @@ namespace Jiaowu.Api.Tests; public sealed class MoodleCourseClientTests { + [Fact] + public async Task StudentImport_ValidatesAllAccountsBeforeEnrollingWithStudentRole() + { + var handler = new TeacherHandler(); + var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + { + ["Moodle:BaseUrl"] = "https://moodle.example.edu/sub", ["Moodle:Token"] = "token", ["Moodle:CategoryId"] = "4", ["Moodle:StudentRoleId"] = "5" + }).Build(); + var client = new MoodleCourseClient(new Factory(new HttpClient(handler)), config); + await Assert.ThrowsAsync(() => client.SyncStudentsAsync("https://moodle.example.edu/sub/course/view.php?id=42", ["T01", "missing"], CancellationToken.None)); + Assert.Single(handler.Requests); + await client.SyncStudentsAsync("https://moodle.example.edu/sub/course/view.php?id=42", ["T01"], CancellationToken.None); + Assert.Contains("enrolments%5B0%5D%5Broleid%5D=5", handler.Requests.Last()); + } + [Fact] public async Task CopyCourse_ExcludesUsersAndDoesNotReuseUnknownExistingCourse() { diff --git a/web/src/i18n/messages/en-US/core.ts b/web/src/i18n/messages/en-US/core.ts index 17bbb42..4b04b1a 100644 --- a/web/src/i18n/messages/en-US/core.ts +++ b/web/src/i18n/messages/en-US/core.ts @@ -5,6 +5,8 @@ export default { create: "Create empty course", createConfirm: "Create a hidden, empty Moodle course for this teaching task? Teachers and students will not be enrolled automatically.", created: "Moodle course created and linked", batchCreate: "Create Moodle courses", batchConfirm: "Create hidden, empty courses for {count} selected tasks? Teachers and students will not be enrolled automatically.", batchResult: "Course creation results", batchSuccess: "Created or recovered {count} courses.", unavailable: "Configure the Moodle service first.", syncTeachers: "Sync teachers", syncConfirm: "Match teacher numbers to Moodle usernames and enrol teachers. Existing teachers will not be removed. Continue?", syncSuccess: "Teachers synced to Moodle", + students: "Import Moodle students", studentsConfirm: "Enrol the current class roster by matching student numbers to Moodle usernames. Existing students will not be removed. Continue?", studentsDone: "Processed {count} students", + studentsBatch: "Import Moodle students in bulk", studentsBatchConfirm: "Import current student rosters for {count} linked classes? Existing students will not be removed.", studentsBatchDone: "Processed {count} classes.", copy: "Copy existing course", copyHint: "Enter the numeric ID of the Moodle course to copy. Users and their records are excluded. If the copy times out, check Moodle before retrying.", invalidTemplate: "Enter a positive numeric course ID", copied: "Moodle course copied and linked", }, selectionTemplate: { diff --git a/web/src/i18n/messages/zh-CN/core.ts b/web/src/i18n/messages/zh-CN/core.ts index 0795109..9bd9a32 100644 --- a/web/src/i18n/messages/zh-CN/core.ts +++ b/web/src/i18n/messages/zh-CN/core.ts @@ -5,6 +5,8 @@ export default { create: "创建空课程", createConfirm: "将在 Moodle 创建隐藏的空课程并关联当前教学任务。教师和学生尚不会自动加入,确认继续?", created: "Moodle 课程已创建并关联", batchCreate: "批量创建 Moodle 课程", batchConfirm: "将为选中的 {count} 个未关联教学任务创建隐藏的空课程,不会自动加入教师或学生。确认继续?", batchResult: "批量创建结果", batchSuccess: "已创建或恢复关联 {count} 门课程。", unavailable: "请先配置 Moodle 服务。", syncTeachers: "同步授课教师", syncConfirm: "按工号匹配 Moodle 用户名并加入授课教师;不会移除 Moodle 中已有的教师。确认继续?", syncSuccess: "授课教师已同步至 Moodle", + students: "导入 Moodle 学生", studentsConfirm: "按当前教学班名单和学号匹配 Moodle 用户名并加入课程;已有学生不会被移除。确认继续?", studentsDone: "已处理 {count} 名学生", + studentsBatch: "批量导入 Moodle 学生", studentsBatchConfirm: "为选中的 {count} 个已关联教学班导入当前学生名单;不会移除已有学生。确认继续?", studentsBatchDone: "已处理 {count} 个教学班。", copy: "复制历史课程", copyHint: "请输入 Moodle 历史课程的数字 ID。复制不包含旧用户及其记录;如复制超时,请先在 Moodle 检查结果。", invalidTemplate: "请输入正整数课程 ID", copied: "Moodle 历史课程已复制并关联", }, selectionTemplate: { diff --git a/web/src/views/TeacherRosterView.vue b/web/src/views/TeacherRosterView.vue index a00fb2a..d4ffe6e 100644 --- a/web/src/views/TeacherRosterView.vue +++ b/web/src/views/TeacherRosterView.vue @@ -14,6 +14,20 @@ const selectedTask = ref(null) const roster = ref(null) const termId = ref() const { locale, t } = useI18n() +const moodleStudentSync = ref(false) +const syncingMoodle = ref(false) + +async function syncMoodleStudents() { + if (!selectedTask.value) return + try { + await ElMessageBox.confirm(t('moodle.studentsConfirm'), t('moodle.students'), { type: 'warning' }) + syncingMoodle.value = true + const result = await http.post(`/moodle-courses/teaching-tasks/${selectedTask.value.id}/students`) + ElMessage.success(t('moodle.studentsDone', { count: result.data.count })) + } catch (error) { + if (error !== 'cancel' && error !== 'close') ElMessage.error(apiErrorMessage(error)) + } finally { syncingMoodle.value = false } +} let rosterRequest = 0 async function loadTasks() { @@ -66,6 +80,7 @@ async function exportRoster() { } onMounted(async () => { + try { moodleStudentSync.value = (await http.get('/moodle-courses/availability')).data.studentSync } catch { moodleStudentSync.value = false } terms.value = (await http.get('/base-data/terms')).data termId.value = defaultAcademicTermId(terms.value) await loadTasks() @@ -111,6 +126,7 @@ onMounted(async () => {