diff --git a/README.md b/README.md index e7393c3..b95640d 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 课程、同步授课教师及导入学生。教师复制历史课程时,来源限于本人曾任教且已在教务系统关联的 Moodle 数字 ID 链接;编号链接需要先由管理员改为对应数字 ID 链接才能作为教师复制来源。教师同步不会自动完成全部步骤,课程创建、教师同步和学生导入分别发起。 + 配置 `Moodle__StudentRoleId` 后,有管理权限的管理员或该教学班的任课教师可将当前教学班名单导入 Moodle,学号须与 Moodle 用户名一致。名单包括行政班关联和正式选课学生,排除学籍异动限制;导入是增量操作,不会自动移除退课学生或创建账号。导入前应确认选课名单,名单变化后可重复导入;需要撤销访问时须在 Moodle 中处理。 管理员也可输入 Moodle 历史课程的数字 ID 来复制课程;需要启用 `core_course_duplicate_course`、`core_course_update_courses` 并授予来源课程备份和目标分类恢复、课程更新权限。复制成功后写入教学任务编号作为课程 ID 号码,不包含旧用户及其数据。复制或更新编号超时、失败时,Moodle 可能留下未完成课程;须先在 Moodle 检查结果并处理,再手动关联,不应直接认定复制成功。 diff --git a/src/Jiaowu.Api/Controllers/CourseSelectionsController.cs b/src/Jiaowu.Api/Controllers/CourseSelectionsController.cs index 9b3f957..4856ba8 100644 --- a/src/Jiaowu.Api/Controllers/CourseSelectionsController.cs +++ b/src/Jiaowu.Api/Controllers/CourseSelectionsController.cs @@ -1840,6 +1840,7 @@ public sealed class CourseSelectionsController( x.TaskNumber, TaskName = x.Name, x.MoodleCourseUrl, + x.Status, x.AcademicTermId, TermName = x.AcademicTerm!.Name, CourseCode = x.Course!.Code, diff --git a/src/Jiaowu.Api/Controllers/MoodleCoursesController.cs b/src/Jiaowu.Api/Controllers/MoodleCoursesController.cs index c94c2b6..2d80e97 100644 --- a/src/Jiaowu.Api/Controllers/MoodleCoursesController.cs +++ b/src/Jiaowu.Api/Controllers/MoodleCoursesController.cs @@ -46,10 +46,9 @@ public sealed class MoodleCoursesController(AppDbContext db, ICurrentUserDataSco public async Task SyncTeachers(Guid id, CancellationToken ct) { var query = db.TeachingTasks.AsNoTracking().Include(x => x.Course).Include(x => x.Teachers).ThenInclude(x => x.Teacher).AsQueryable(); - if (scope.Current.RestrictedCollegeId is Guid collegeId) query = query.Where(x => x.Course!.CollegeId == collegeId); var task = await query.SingleOrDefaultAsync(x => x.Id == id, ct); if (task is null) return NotFound(); - if (!TeachingTaskMaintenancePolicy.CanManage(scope.Current, task.Course!.CollegeId, task.Course.Nature)) return Forbid(); + if (!CanManageOrTeach(task)) return Forbid(); if (task.Status != TeachingTaskStatus.Published || task.MoodleCourseUrl is null) return Conflict(new ProblemDetails { Detail = "请先发布教学任务并关联 Moodle 课程。", Status = 409 }); try @@ -66,12 +65,10 @@ public sealed class MoodleCoursesController(AppDbContext db, ICurrentUserDataSco [HttpPost("teaching-tasks/{id:guid}")] public async Task Create(Guid id, CancellationToken ct) { - var query = db.TeachingTasks.AsNoTracking().Include(x => x.Course).AsQueryable(); - if (scope.Current.RestrictedCollegeId is Guid collegeId) - query = query.Where(x => x.Course!.CollegeId == collegeId); + var query = db.TeachingTasks.AsNoTracking().Include(x => x.Course).Include(x => x.Teachers).ThenInclude(x => x.Teacher).AsQueryable(); var task = await query.SingleOrDefaultAsync(x => x.Id == id, ct); if (task is null) return NotFound(); - if (!TeachingTaskMaintenancePolicy.CanManage(scope.Current, task.Course!.CollegeId, task.Course.Nature)) return Forbid(); + if (!CanManageOrTeach(task)) return Forbid(); if (task.Status != TeachingTaskStatus.Published) return Conflict(new ProblemDetails { Detail = "仅已发布的教学任务可以创建 Moodle 课程。", Status = 409 }); if (task.MoodleCourseUrl is not null) return Conflict(new ProblemDetails { Detail = "该教学任务已有 Moodle 课程关联。", Status = 409 }); try @@ -91,11 +88,16 @@ public sealed class MoodleCoursesController(AppDbContext db, ICurrentUserDataSco [HttpPost("teaching-tasks/{id:guid}/copy")] public async Task Copy(Guid id, MoodleCopyRequest request, CancellationToken ct) { - var query = db.TeachingTasks.AsNoTracking().Include(x => x.Course).AsQueryable(); - if (scope.Current.RestrictedCollegeId is Guid collegeId) query = query.Where(x => x.Course!.CollegeId == collegeId); + var query = db.TeachingTasks.AsNoTracking().Include(x => x.Course).Include(x => x.Teachers).ThenInclude(x => x.Teacher).AsQueryable(); var task = await query.SingleOrDefaultAsync(x => x.Id == id, ct); if (task is null) return NotFound(); - if (!TeachingTaskMaintenancePolicy.CanManage(scope.Current, task.Course!.CollegeId, task.Course.Nature)) return Forbid(); + if (!CanManageOrTeach(task)) return Forbid(); + if (!TeachingTaskMaintenancePolicy.CanManage(scope.Current, task.Course!.CollegeId, task.Course.Nature)) + { + var links = await db.TeachingTasks.AsNoTracking().Where(x => x.MoodleCourseUrl != null && x.Teachers.Any(t => t.Teacher!.UserId == scope.Current.UserId)) + .Select(x => x.MoodleCourseUrl!).ToListAsync(ct); + if (!links.Any(url => moodle.IsCourseIdLink(url, request.TemplateId))) return Forbid(); + } if (task.Status != TeachingTaskStatus.Published || task.MoodleCourseUrl is not null) return Conflict(new ProblemDetails { Detail = "仅已发布且未关联的教学任务可以复制课程。", Status = 409 }); try @@ -111,6 +113,9 @@ public sealed class MoodleCoursesController(AppDbContext db, ICurrentUserDataSco return StatusCode(502, new ProblemDetails { Title = "Moodle 课程复制失败", Detail = ex.Message + " 如已开始复制,请在 Moodle 检查是否产生未完成的课程。", Status = 502 }); } } + private bool CanManageOrTeach(TeachingTask task) => + TeachingTaskMaintenancePolicy.CanManage(scope.Current, task.Course!.CollegeId, task.Course.Nature) || + scope.Current.IsInRole(SystemRoles.Teacher) && task.Teachers.Any(t => t.Teacher!.UserId == scope.Current.UserId); } public sealed record MoodleCopyRequest(long TemplateId); diff --git a/src/Jiaowu.Api/Infrastructure/Teaching/MoodleCourseClient.cs b/src/Jiaowu.Api/Infrastructure/Teaching/MoodleCourseClient.cs index a1fcbf6..e7a7126 100644 --- a/src/Jiaowu.Api/Infrastructure/Teaching/MoodleCourseClient.cs +++ b/src/Jiaowu.Api/Infrastructure/Teaching/MoodleCourseClient.cs @@ -8,6 +8,15 @@ public sealed class MoodleCourseClient(IHttpClientFactory clients, IConfiguratio 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 bool IsCourseIdLink(string url, long courseId) + { + if (courseId <= 0 || !TryGetSettings(out var baseUri, out _, out _) || !Uri.TryCreate(url, UriKind.Absolute, out var uri) || + !string.Equals(uri.GetLeftPart(UriPartial.Path), new Uri(baseUri, "course/view.php").GetLeftPart(UriPartial.Path), StringComparison.OrdinalIgnoreCase) || + !string.IsNullOrEmpty(uri.UserInfo)) return false; + var query = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(uri.Query); + return !query.ContainsKey("name") && !query.ContainsKey("idnumber") && query.TryGetValue("id", out var id) && long.TryParse(id.ToString(), out var parsed) && parsed == courseId; + } + public Task SyncTeachersAsync(string courseUrl, IReadOnlyList teacherNumbers, CancellationToken ct) => EnrolUsersAsync(courseUrl, teacherNumbers, "TeacherRoleId", ct); diff --git a/tests/Jiaowu.Api.Tests/TeachingTaskRosterProfileTests.cs b/tests/Jiaowu.Api.Tests/TeachingTaskRosterProfileTests.cs index 07abc04..3aa41bc 100644 --- a/tests/Jiaowu.Api.Tests/TeachingTaskRosterProfileTests.cs +++ b/tests/Jiaowu.Api.Tests/TeachingTaskRosterProfileTests.cs @@ -4,9 +4,11 @@ using Jiaowu.Api.Domain.Academic; using Jiaowu.Api.Domain.Identity; using Jiaowu.Api.Infrastructure.Auth; using Jiaowu.Api.Infrastructure.Persistence; +using Jiaowu.Api.Infrastructure.Teaching; using Microsoft.AspNetCore.Mvc; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; namespace Jiaowu.Api.Tests; @@ -83,6 +85,8 @@ public sealed class TeachingTaskRosterProfileTests db.Add(task); db.Add(new TeachingTask { TaskNumber = "OTHER", Name = "其他教学班", AcademicTermId = term.Id, CourseId = course.Id, Capacity = 40, Status = TeachingTaskStatus.Published, MoodleCourseUrl = "https://moodle.example.edu/course/view.php?id=99" }); db.Add(new TeachingTask { TaskNumber = "DRAFT", Name = "草稿教学班", AcademicTermId = term.Id, CourseId = course.Id, Capacity = 40, Status = TeachingTaskStatus.Draft, MoodleCourseUrl = "https://moodle.example.edu/course/view.php?id=100", Classes = [new TeachingTaskClass { AdministrativeClassId = administrativeClass.Id }] }); + var teacherTask = new TeachingTask { TaskNumber = "OWN", Name = "本人教学班", AcademicTermId = term.Id, CourseId = course.Id, Capacity = 40, Status = TeachingTaskStatus.Published, Teachers = [new TeachingTaskTeacher { TeacherId = teacher.Id }] }; + db.Add(teacherTask); await db.SaveChangesAsync(); var studentController = new CourseSelectionsController(db, new StudentDataScope(studentUser.Id)); @@ -91,6 +95,15 @@ public sealed class TeachingTaskRosterProfileTests var ownCourse = Assert.Single(courses.Cast()); Assert.Equal("https://moodle.example.edu/course/view.php?id=42", Property(ownCourse, "MoodleCourseUrl")); + var moodle = new MoodleCourseClient(new UnusedHttpClientFactory(), new ConfigurationBuilder().Build()); + var moodleController = new MoodleCoursesController(db, new TeacherDataScope(teacherUser.Id), moodle); + var otherTask = await db.TeachingTasks.SingleAsync(x => x.TaskNumber == "OTHER"); + Assert.IsType(await moodleController.Create(otherTask.Id, CancellationToken.None)); + Assert.IsType(await moodleController.SyncTeachers(otherTask.Id, CancellationToken.None)); + Assert.Equal(502, Assert.IsType(await moodleController.Create(teacherTask.Id, CancellationToken.None)).StatusCode); + Assert.IsType(await moodleController.Copy(teacherTask.Id, new MoodleCopyRequest(99), CancellationToken.None)); + Assert.Equal(502, Assert.IsType(await moodleController.SyncTeachers(task.Id, CancellationToken.None)).StatusCode); + var controller = new CourseSelectionsController( db, new TeacherDataScope(teacherUser.Id)); @@ -134,4 +147,9 @@ public sealed class TeachingTaskRosterProfileTests { public CurrentUserScope Current { get; } = new(userId, "学生", null, DataScope.Self, new HashSet { SystemRoles.Student }); } + + private sealed class UnusedHttpClientFactory : IHttpClientFactory + { + public HttpClient CreateClient(string name) => throw new InvalidOperationException("HTTP should not be called"); + } } diff --git a/web/src/i18n/messages/en-US/core.ts b/web/src/i18n/messages/en-US/core.ts index a0870ea..f8629f4 100644 --- a/web/src/i18n/messages/en-US/core.ts +++ b/web/src/i18n/messages/en-US/core.ts @@ -9,6 +9,7 @@ export default { 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", + teacherCopyHint: "Enter the numeric Moodle course ID of a previously assigned class linked in this system. Users and their records are excluded; check Moodle if copying times out.", }, selectionTemplate: { courseSelection: "Course selection", diff --git a/web/src/i18n/messages/zh-CN/core.ts b/web/src/i18n/messages/zh-CN/core.ts index 81416ab..e2d9317 100644 --- a/web/src/i18n/messages/zh-CN/core.ts +++ b/web/src/i18n/messages/zh-CN/core.ts @@ -9,6 +9,7 @@ export default { students: "导入 Moodle 学生", studentsConfirm: "按当前教学班名单和学号匹配 Moodle 用户名并加入课程;已有学生不会被移除。确认继续?", studentsDone: "已处理 {count} 名学生", studentsBatch: "批量导入 Moodle 学生", studentsBatchConfirm: "为选中的 {count} 个已关联教学班导入当前学生名单;不会移除已有学生。确认继续?", studentsBatchDone: "已处理 {count} 个教学班。", copy: "复制历史课程", copyHint: "请输入 Moodle 历史课程的数字 ID。复制不包含旧用户及其记录;如复制超时,请先在 Moodle 检查结果。", invalidTemplate: "请输入正整数课程 ID", copied: "Moodle 历史课程已复制并关联", + teacherCopyHint: "请输入本人曾任教且已在教务系统关联的 Moodle 课程数字 ID。复制不包含旧用户及其记录;如复制超时,请先在 Moodle 检查结果。", }, selectionTemplate: { courseSelection: "学生选课", diff --git a/web/src/views/TeacherRosterView.vue b/web/src/views/TeacherRosterView.vue index d4ffe6e..ce9fe84 100644 --- a/web/src/views/TeacherRosterView.vue +++ b/web/src/views/TeacherRosterView.vue @@ -15,14 +15,58 @@ const roster = ref(null) const termId = ref() const { locale, t } = useI18n() const moodleStudentSync = ref(false) +const moodleAvailable = ref(false) +const moodleTeacherSync = ref(false) const syncingMoodle = ref(false) +async function createMoodleCourse() { + if (!selectedTask.value) return + const taskId = selectedTask.value.id + try { + await ElMessageBox.confirm(t('moodle.createConfirm'), t('moodle.create'), { type: 'warning' }) + syncingMoodle.value = true + await http.post(`/moodle-courses/teaching-tasks/${taskId}`) + ElMessage.success(t('moodle.created')) + await loadTasks() + } catch (error) { + if (error !== 'cancel' && error !== 'close') ElMessage.error(apiErrorMessage(error)) + } finally { syncingMoodle.value = false } +} + +async function syncMoodleTeachers() { + if (!selectedTask.value) return + const taskId = selectedTask.value.id + try { + await ElMessageBox.confirm(t('moodle.syncConfirm'), t('moodle.syncTeachers'), { type: 'warning' }) + syncingMoodle.value = true + await http.post(`/moodle-courses/teaching-tasks/${taskId}/teachers`) + ElMessage.success(t('moodle.syncSuccess')) + } catch (error) { + if (error !== 'cancel' && error !== 'close') ElMessage.error(apiErrorMessage(error)) + } finally { syncingMoodle.value = false } +} + +async function copyMoodleCourse() { + if (!selectedTask.value) return + const taskId = selectedTask.value.id + try { + const answer = await ElMessageBox.prompt(t('moodle.teacherCopyHint'), t('moodle.copy'), { inputPattern: /^[1-9]\d*$/, inputErrorMessage: t('moodle.invalidTemplate') }) + syncingMoodle.value = true + await http.post(`/moodle-courses/teaching-tasks/${taskId}/copy`, { templateId: Number(answer.value) }) + ElMessage.success(t('moodle.copied')) + await loadTasks() + } catch (error) { + if (error !== 'cancel' && error !== 'close') ElMessage.error(apiErrorMessage(error)) + } finally { syncingMoodle.value = false } +} + async function syncMoodleStudents() { if (!selectedTask.value) return + const taskId = selectedTask.value.id 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`) + const result = await http.post(`/moodle-courses/teaching-tasks/${taskId}/students`) ElMessage.success(t('moodle.studentsDone', { count: result.data.count })) } catch (error) { if (error !== 'cancel' && error !== 'close') ElMessage.error(apiErrorMessage(error)) @@ -80,7 +124,12 @@ async function exportRoster() { } onMounted(async () => { - try { moodleStudentSync.value = (await http.get('/moodle-courses/availability')).data.studentSync } catch { moodleStudentSync.value = false } + try { + const settings = (await http.get('/moodle-courses/availability')).data + moodleAvailable.value = settings.available + moodleTeacherSync.value = settings.teacherSync + moodleStudentSync.value = settings.studentSync + } catch { moodleStudentSync.value = false } terms.value = (await http.get('/base-data/terms')).data termId.value = defaultAcademicTermId(terms.value) await loadTasks() @@ -124,8 +173,13 @@ onMounted(async () => {
+