Add lesson retrieval functionality in VocabController and VocabService

- Introduced a new method in VocabService to fetch lesson details, including access control based on user ownership and lesson visibility.
- Updated VocabController to wrap the new method for user access.
- Added a new route in VocabRouter to handle requests for specific lessons.
- Enhanced VocabCourseListView to support navigation to individual lesson views, improving user experience in accessing lesson content.
This commit is contained in:
Torsten Schulz (local)
2026-01-19 15:07:52 +01:00
parent 33787ba796
commit c13cb40c7b
6 changed files with 238 additions and 2 deletions

View File

@@ -32,6 +32,7 @@ class VocabController {
this.deleteCourse = this._wrapWithUser((userId, req) => this.service.deleteCourse(userId, req.params.courseId)); this.deleteCourse = this._wrapWithUser((userId, req) => this.service.deleteCourse(userId, req.params.courseId));
// Lessons // Lessons
this.getLesson = this._wrapWithUser((userId, req) => this.service.getLesson(userId, req.params.lessonId));
this.addLessonToCourse = this._wrapWithUser((userId, req) => this.service.addLessonToCourse(userId, req.params.courseId, req.body), { successStatus: 201 }); this.addLessonToCourse = this._wrapWithUser((userId, req) => this.service.addLessonToCourse(userId, req.params.courseId, req.body), { successStatus: 201 });
this.updateLesson = this._wrapWithUser((userId, req) => this.service.updateLesson(userId, req.params.lessonId, req.body)); this.updateLesson = this._wrapWithUser((userId, req) => this.service.updateLesson(userId, req.params.lessonId, req.body));
this.deleteLesson = this._wrapWithUser((userId, req) => this.service.deleteLesson(userId, req.params.lessonId)); this.deleteLesson = this._wrapWithUser((userId, req) => this.service.deleteLesson(userId, req.params.lessonId));

View File

@@ -43,6 +43,7 @@ router.delete('/courses/:courseId/enroll', vocabController.unenrollFromCourse);
// Progress // Progress
router.get('/courses/:courseId/progress', vocabController.getCourseProgress); router.get('/courses/:courseId/progress', vocabController.getCourseProgress);
router.get('/lessons/:lessonId', vocabController.getLesson);
router.put('/lessons/:lessonId/progress', vocabController.updateLessonProgress); router.put('/lessons/:lessonId/progress', vocabController.updateLessonProgress);
// Grammar Exercises // Grammar Exercises

View File

@@ -846,6 +846,33 @@ export default class VocabService {
return { success: true }; return { success: true };
} }
async getLesson(hashedUserId, lessonId) {
const user = await this._getUserByHashedId(hashedUserId);
const lesson = await VocabCourseLesson.findByPk(lessonId, {
include: [
{
model: VocabCourse,
as: 'course'
}
]
});
if (!lesson) {
const err = new Error('Lesson not found');
err.status = 404;
throw err;
}
// Prüfe Zugriff
if (lesson.course.ownerUserId !== user.id && !lesson.course.isPublic) {
const err = new Error('Access denied');
err.status = 403;
throw err;
}
return lesson.get({ plain: true });
}
async addLessonToCourse(hashedUserId, courseId, { chapterId, lessonNumber, title, description, weekNumber, dayNumber, lessonType, audioUrl, culturalNotes, targetMinutes, targetScorePercent, requiresReview }) { async addLessonToCourse(hashedUserId, courseId, { chapterId, lessonNumber, title, description, weekNumber, dayNumber, lessonType, audioUrl, culturalNotes, targetMinutes, targetScorePercent, requiresReview }) {
const user = await this._getUserByHashedId(hashedUserId); const user = await this._getUserByHashedId(hashedUserId);
const course = await VocabCourse.findByPk(courseId); const course = await VocabCourse.findByPk(courseId);

View File

@@ -99,6 +99,13 @@ const socialRoutes = [
props: true, props: true,
meta: { requiresAuth: true } meta: { requiresAuth: true }
}, },
{
path: '/socialnetwork/vocab/courses/:courseId/lessons/:lessonId',
name: 'VocabLesson',
component: () => import('../views/social/VocabLessonView.vue'),
props: true,
meta: { requiresAuth: true }
},
]; ];
export default socialRoutes; export default socialRoutes;

View File

@@ -197,6 +197,10 @@ export default {
const nativeLang = this.languages.find(lang => lang.name === nativeLanguageName); const nativeLang = this.languages.find(lang => lang.name === nativeLanguageName);
if (nativeLang) { if (nativeLang) {
this.myNativeLanguageId = nativeLang.id; this.myNativeLanguageId = nativeLang.id;
// Setze die eigene Muttersprache als Standardauswahl
if (!this.selectedNativeLanguageId) {
this.selectedNativeLanguageId = 'my';
}
console.log(`[loadMyNativeLanguageId] Gefunden: ${nativeLanguageName} (ID: ${nativeLang.id})`); console.log(`[loadMyNativeLanguageId] Gefunden: ${nativeLanguageName} (ID: ${nativeLang.id})`);
} else { } else {
console.warn(`[loadMyNativeLanguageId] Sprache "${nativeLanguageName}" nicht in languages-Liste gefunden. Verfügbare Sprachen:`, this.languages.map(l => l.name).join(', ')); console.warn(`[loadMyNativeLanguageId] Sprache "${nativeLanguageName}" nicht in languages-Liste gefunden. Verfügbare Sprachen:`, this.languages.map(l => l.name).join(', '));
@@ -297,6 +301,16 @@ export default {
this.loading = false; this.loading = false;
} }
}, },
async checkIfHasCourses() {
// Prüfe, ob der Benutzer bereits Kurse hat
try {
const res = await apiClient.get('/api/vocab/courses/my');
const courses = res.data || [];
return courses.length > 0;
} catch (e) {
return false;
}
},
async createCourse() { async createCourse() {
try { try {
await apiClient.post('/api/vocab/courses', this.newCourse); await apiClient.post('/api/vocab/courses', this.newCourse);
@@ -318,7 +332,8 @@ export default {
async enroll(courseId) { async enroll(courseId) {
try { try {
await apiClient.post(`/api/vocab/courses/${courseId}/enroll`); await apiClient.post(`/api/vocab/courses/${courseId}/enroll`);
await this.loadAllCourses(); // Nach dem Einschreiben sofort zum Kurs navigieren
this.openCourse(courseId);
} catch (e) { } catch (e) {
console.error('Fehler beim Einschreiben:', e); console.error('Fehler beim Einschreiben:', e);
alert(e.response?.data?.error || 'Fehler beim Einschreiben'); alert(e.response?.data?.error || 'Fehler beim Einschreiben');
@@ -333,7 +348,13 @@ export default {
}, },
async mounted() { async mounted() {
await this.loadLanguages(); await this.loadLanguages();
// Wenn der Benutzer bereits Kurse hat, zeige "Meine Kurse" als Standard
const hasCourses = await this.checkIfHasCourses();
if (hasCourses) {
await this.loadMyCourses();
} else {
await this.loadAllCourses(); await this.loadAllCourses();
}
}, },
}; };
</script> </script>

View File

@@ -0,0 +1,179 @@
<template>
<div class="vocab-lesson-view">
<div v-if="loading">{{ $t('general.loading') }}</div>
<div v-else-if="lesson">
<div class="lesson-header">
<button @click="back" class="btn-back">{{ $t('general.back') }}</button>
<h2>{{ lesson.title }}</h2>
</div>
<p v-if="lesson.description" class="lesson-description">{{ lesson.description }}</p>
<div v-if="lesson.grammarExercises && lesson.grammarExercises.length > 0" class="grammar-exercises">
<h3>{{ $t('socialnetwork.vocab.courses.grammarExercises') }}</h3>
<div v-for="exercise in lesson.grammarExercises" :key="exercise.id" class="exercise-item">
<h4>{{ exercise.title }}</h4>
<p v-if="exercise.description">{{ exercise.description }}</p>
<div v-if="exercise.type === 'gap_fill'" class="gap-fill-exercise">
<p v-html="formatGapFill(exercise.content)"></p>
<input v-model="exerciseAnswers[exercise.id]" :placeholder="$t('socialnetwork.vocab.courses.enterAnswer')" />
<button @click="checkAnswer(exercise.id)">{{ $t('socialnetwork.vocab.courses.checkAnswer') }}</button>
<div v-if="exerciseResults[exercise.id]" class="exercise-result" :class="exerciseResults[exercise.id].correct ? 'correct' : 'wrong'">
{{ exerciseResults[exercise.id].correct ? $t('socialnetwork.vocab.courses.correct') : $t('socialnetwork.vocab.courses.wrong') }}
<p v-if="exercise.explanation">{{ exercise.explanation }}</p>
</div>
</div>
</div>
</div>
<div v-else>
<p>{{ $t('socialnetwork.vocab.courses.noExercises') }}</p>
</div>
</div>
</div>
</template>
<script>
import { mapGetters } from 'vuex';
import apiClient from '@/utils/axios.js';
export default {
name: 'VocabLessonView',
props: {
courseId: {
type: String,
required: true
},
lessonId: {
type: String,
required: true
}
},
data() {
return {
loading: false,
lesson: null,
exerciseAnswers: {},
exerciseResults: {}
};
},
computed: {
...mapGetters(['user'])
},
watch: {
courseId() {
this.loadLesson();
},
lessonId() {
this.loadLesson();
}
},
methods: {
async loadLesson() {
this.loading = true;
try {
const res = await apiClient.get(`/api/vocab/lessons/${this.lessonId}`);
this.lesson = res.data;
// Lade Grammatik-Übungen
if (this.lesson && this.lesson.id) {
await this.loadGrammarExercises();
}
} catch (e) {
console.error('Konnte Lektion nicht laden:', e);
} finally {
this.loading = false;
}
},
async loadGrammarExercises() {
try {
const res = await apiClient.get(`/api/vocab/lessons/${this.lessonId}/grammar-exercises`);
this.lesson.grammarExercises = res.data || [];
} catch (e) {
console.error('Konnte Grammatik-Übungen nicht laden:', e);
this.lesson.grammarExercises = [];
}
},
formatGapFill(content) {
// Ersetze Platzhalter mit Input-Feldern
return content.replace(/\{gap\}/g, '<span class="gap">_____</span>');
},
async checkAnswer(exerciseId) {
try {
const answer = this.exerciseAnswers[exerciseId];
const res = await apiClient.post(`/api/vocab/exercises/${exerciseId}/check`, { answer });
this.exerciseResults[exerciseId] = res.data;
} catch (e) {
console.error('Fehler beim Prüfen der Antwort:', e);
}
},
back() {
this.$router.push(`/socialnetwork/vocab/courses/${this.courseId}`);
}
},
async mounted() {
await this.loadLesson();
}
};
</script>
<style scoped>
.vocab-lesson-view {
padding: 20px;
}
.lesson-header {
display: flex;
align-items: center;
gap: 15px;
margin-bottom: 20px;
}
.btn-back {
padding: 8px 16px;
border: 1px solid #ddd;
border-radius: 4px;
background: white;
cursor: pointer;
}
.lesson-description {
color: #666;
margin-bottom: 20px;
}
.grammar-exercises {
margin-top: 30px;
}
.exercise-item {
background: white;
padding: 15px;
border: 1px solid #ddd;
border-radius: 4px;
margin-bottom: 15px;
}
.gap-fill-exercise input {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
margin: 10px 0;
}
.exercise-result {
margin-top: 10px;
padding: 10px;
border-radius: 4px;
}
.exercise-result.correct {
background: #d4edda;
color: #155724;
}
.exercise-result.wrong {
background: #f8d7da;
color: #721c24;
}
</style>