feat: implement core e-learning pages, course composable, and i18n localization.

This commit is contained in:
supalerk-ar66 2026-02-09 11:40:41 +07:00
parent f736eb7f38
commit e94410d0e7
9 changed files with 235 additions and 138 deletions

View file

@ -7,6 +7,7 @@ export interface Course {
thumbnail_url: string
price: string
is_free: boolean
original_price?: string
have_certificate: boolean
status: string // DRAFT, PUBLISHED
category_id: number
@ -41,6 +42,15 @@ interface CourseResponse {
message: string
data: Course[]
total: number
page?: number
limit?: number
totalPages?: number
}
interface SingleCourseResponse {
code: number
message: string
data: Course
}
// Interface สำหรับคอร์สที่ผู้ใช้ลงทะเบียนเรียนแล้ว (My Course)
@ -97,12 +107,6 @@ export interface QuizResult {
attempt_id: number
}
// ==========================================
// Composable: useCourse
// หน้าที่: จัดการ Logic ทุกอย่างเกี่ยวกับคอร์สเรียน
// - ดึงข้อมูลคอร์ส (Public & Protected)
// - ลงทะเบียนเรียน (Enroll)
// - ติดตามความคืบหน้าการเรียน (Progress tracking)
// Interface สำหรับ Certificate
export interface Certificate {
certificate_id: number
@ -116,21 +120,37 @@ export interface Certificate {
}
// ==========================================
// Composable: useCourse
// หน้าที่: จัดการ Logic ทุกอย่างเกี่ยวกับคอร์สเรียน
// - ดึงข้อมูลคอร์ส (Public & Protected)
// - ลงทะเบียนเรียน (Enroll)
// - ติดตามความคืบหน้าการเรียน (Progress tracking)
export const useCourse = () => {
const config = useRuntimeConfig()
const API_BASE_URL = config.public.apiBase as string
const { token } = useAuth()
// ใช้ useState เพื่อเก็บรายชื่อคอร์สทั้งหมดใน Memory
// ใช้ useState เพื่อเก็บรายชื่อคอร์สทั้งหมดใน Memory (สำหรับกรณีดึงทั้งหมด)
const coursesState = useState<Course[]>('courses_cache', () => [])
const isCoursesLoaded = useState<boolean>('courses_loaded', () => false)
// ฟังก์ชันดึงรายชื่อคอร์สทั้งหมด (Catalog)
// ใช้สำหรับหน้า Discover/Browse
// Endpoint: GET /courses
const fetchCourses = async (forceRefresh = false) => {
// ถ้าโหลดไปแล้ว และไม่ได้บังคับ Refresh ให้ใช้ข้อมูลจาก State
if (isCoursesLoaded.value && !forceRefresh && coursesState.value.length > 0) {
/**
* (Catalog)
* Pagination
* Endpoint: GET /courses
*/
const fetchCourses = async (params: {
category_id?: number;
page?: number;
limit?: number;
random?: boolean;
forceRefresh?: boolean
} = {}) => {
const { forceRefresh = false, ...apiParams } = params
// ใช้ Cache เฉพาะกรณีดึง "ทั้งหมด" แบบปกติ (ไม่มี params)
const isRequestingAll = Object.keys(apiParams).length === 0
if (isRequestingAll && isCoursesLoaded.value && !forceRefresh && coursesState.value.length > 0) {
return {
success: true,
data: coursesState.value,
@ -139,9 +159,18 @@ export const useCourse = () => {
}
try {
const data = await $fetch<CourseResponse>(`${API_BASE_URL}/courses`, {
// สร้าง Query String
const queryParams = new URLSearchParams()
if (apiParams.category_id) queryParams.append('category_id', apiParams.category_id.toString())
if (apiParams.page) queryParams.append('page', apiParams.page.toString())
if (apiParams.limit) queryParams.append('limit', apiParams.limit.toString())
if (apiParams.random !== undefined) queryParams.append('random', apiParams.random.toString())
const queryString = queryParams.toString()
const url = `${API_BASE_URL}/courses${queryString ? `?${queryString}` : ''}`
const data = await $fetch<CourseResponse>(url, {
method: 'GET',
// ส่ง Token ไปด้วยถ้ามี
headers: token.value ? {
Authorization: `Bearer ${token.value}`
} : {}
@ -149,33 +178,27 @@ export const useCourse = () => {
const courses = data.data || []
// เก็บลง State
coursesState.value = courses
isCoursesLoaded.value = true
// เก็บลง State เฉพาะกรณีดึง "ทั้งหมด"
if (isRequestingAll) {
coursesState.value = courses
isCoursesLoaded.value = true
}
return {
success: true,
data: courses,
total: data.total || 0
total: data.total || 0,
page: data.page,
limit: data.limit,
totalPages: data.totalPages
}
} catch (err: any) {
console.error('Fetch courses failed:', err)
// Retry logic for 429 Too Many Requests
// Retry logic logic for 429
if (err.statusCode === 429 || err.status === 429) {
await new Promise(resolve => setTimeout(resolve, 1500)); // Wait 1.5s
try {
const retryData = await $fetch<CourseResponse>(`${API_BASE_URL}/courses`, {
method: 'GET',
headers: token.value ? { Authorization: `Bearer ${token.value}` } : {}
})
const courses = retryData.data || []
coursesState.value = courses
isCoursesLoaded.value = true
return { success: true, data: courses, total: retryData.total || 0 }
} catch (retryErr) {
console.error('Retry fetch courses failed:', retryErr)
}
await new Promise(resolve => setTimeout(resolve, 1500))
return fetchCourses(params) // Recursive retry
}
return {
@ -185,37 +208,24 @@ export const useCourse = () => {
}
}
// ฟังก์ชันดึงรายละเอียดคอร์สตาม ID
// Endpoint: GET /courses/:id
/**
* ID
* Endpoint: GET /courses/:id
*/
const fetchCourseById = async (id: number) => {
try {
const data = await $fetch<CourseResponse>(`${API_BASE_URL}/courses/${id}`, {
const data = await $fetch<SingleCourseResponse>(`${API_BASE_URL}/courses/${id}`, {
method: 'GET',
headers: token.value ? {
Authorization: `Bearer ${token.value}`
} : {}
})
// Logic จัดการข้อมูลที่ได้รับ (API อาจส่งกลับมาเป็น Array หรือ Object)
let courseData: any = null
if (Array.isArray(data.data)) {
// ถ้าเป็น Array ให้หาอันที่ ID ตรงกัน
courseData = data.data.find((c: any) => c.id == id)
// Fallback: ถ้าหาไม่เจอ แต่มีข้อมูลตัวเดียว อาจจะเป็นตัวนั้น
if (!courseData && data.data.length === 1) {
courseData = data.data[0]
}
} else {
courseData = data.data
}
if (!courseData) throw new Error('Course not found')
if (!data.data) throw new Error('Course not found')
return {
success: true,
data: courseData
data: data.data // ข้อมูลคอร์สตัวเดียว
}
} catch (err: any) {
console.error('Fetch course details failed:', err)
@ -634,7 +644,18 @@ export const useCourse = () => {
}
}
/**
* Helper: แปลงข้อมูล 2 locale
*/
const getLocalizedText = (text: string | { th: string; en: string } | undefined | null) => {
if (!text) return ''
if (typeof text === 'string') return text
// @ts-ignore
return text.th || text.en || ''
}
return {
getLocalizedText,
fetchCourses,
fetchCourseById,
enrollCourse,

View file

@ -159,7 +159,8 @@
"next": "Next",
"back": "Back",
"backToHome": "Back to Home",
"error": "Error"
"error": "Error",
"loading": "Loading"
},
"classroom": {
"backToDashboard": "Back to My Courses",

View file

@ -160,7 +160,8 @@
"next": "ถัดไป",
"back": "ย้อนกลับ",
"backToHome": "กลับสู่หน้าหลัก",
"error": "เกิดข้อผิดพลาด"
"error": "เกิดข้อผิดพลาด",
"loading": "กำลังโหลด"
},
"classroom": {
"backToDashboard": "กลับไปคอร์สของฉัน",

View file

@ -28,11 +28,16 @@ const isLoading = ref(false);
const isLoadingDetail = ref(false);
const isEnrolling = ref(false);
// Pagination State
const currentPage = ref(1);
const totalPages = ref(1);
const itemsPerPage = 12;
const { t } = useI18n();
const { currentUser } = useAuth();
const { fetchCategories } = useCategory();
const { fetchCourses, fetchCourseById, enrollCourse } = useCourse();
const { fetchCourses, fetchCourseById, enrollCourse, getLocalizedText } = useCourse();
// 2. Computed Properties
@ -41,9 +46,13 @@ const sortOptions = computed(() => [t('discovery.sortRecent')]);
const filteredCourses = computed(() => {
let result = courses.value;
if (selectedCategoryIds.value.length > 0) {
// If more than 1 category is selected, we still do client-side filtering
// because the API currently only supports one category_id at a time.
if (selectedCategoryIds.value.length > 1) {
result = result.filter(c => selectedCategoryIds.value.includes(c.category_id));
}
if (searchQuery.value) {
const query = searchQuery.value.toLowerCase();
result = result.filter(c => {
@ -56,11 +65,7 @@ const filteredCourses = computed(() => {
});
// 3. Helper Functions
const getLocalizedText = (text: string | { th: string; en: string } | undefined) => {
if (!text) return '';
if (typeof text === 'string') return text;
return text.th || text.en || '';
};
// 4. API Actions
const loadCategories = async () => {
@ -68,11 +73,23 @@ const loadCategories = async () => {
if (res.success) categories.value = res.data || [];
};
const loadCourses = async () => {
const loadCourses = async (page = 1) => {
isLoading.value = true;
const res = await fetchCourses();
// Use server-side filtering if exactly one category is selected
const categoryId = selectedCategoryIds.value.length === 1 ? selectedCategoryIds.value[0] : undefined;
const res = await fetchCourses({
category_id: categoryId,
page: page,
limit: itemsPerPage,
forceRefresh: true
});
if (res.success) {
courses.value = res.data || [];
totalPages.value = res.totalPages || 1;
currentPage.value = res.page || 1;
}
isLoading.value = false;
};
@ -98,6 +115,12 @@ const handleEnroll = async (id: number) => {
isEnrolling.value = false;
};
// Watch for category selection changes to reload courses
watch(selectedCategoryIds, () => {
currentPage.value = 1;
loadCourses(1);
}, { deep: true });
onMounted(() => {
loadCategories();
loadCourses();
@ -166,6 +189,22 @@ onMounted(() => {
/>
</div>
<!-- Pagination Controls -->
<div v-if="totalPages > 1" class="flex justify-center mt-12 pb-10">
<q-pagination
v-model="currentPage"
:max="totalPages"
:max-pages="6"
boundary-numbers
direction-links
color="primary"
flat
active-design="unelevated"
active-color="primary"
@update:model-value="loadCourses"
/>
</div>
<!-- Empty State -->
<div
v-else

View file

@ -20,7 +20,7 @@ const route = useRoute()
const router = useRouter()
const { t } = useI18n()
const { user } = useAuth()
const { fetchCourseLearningInfo, fetchLessonContent, saveVideoProgress, checkLessonAccess, fetchVideoProgress, fetchCourseAnnouncements, markLessonComplete } = useCourse()
const { fetchCourseLearningInfo, fetchLessonContent, saveVideoProgress, checkLessonAccess, fetchVideoProgress, fetchCourseAnnouncements, markLessonComplete, getLocalizedText } = useCourse()
// Media Prefs (Global Volume)
const { volume, muted: isMuted, setVolume, setMuted, applyTo } = useMediaPrefs()
@ -94,12 +94,6 @@ const currentTime = ref(0)
const duration = ref(0)
// Helper for localization
const getLocalizedText = (text: any) => {
if (!text) return ''
if (typeof text === 'string') return text
return text.th || text.en || ''
}
const toggleSidebar = () => {
sidebarOpen.value = !sidebarOpen.value

View file

@ -238,37 +238,32 @@ const retryQuiz = () => {
}
const submitQuiz = async (auto = false) => {
// if (!auto && !confirm(t('quiz.submitConfirm'))) return
// 1. Manual Validation: Check if all questions are answered
if (!auto) {
const answeredCount = Object.keys(userAnswers.value).length
if (answeredCount < totalQuestions.value) {
$q.notify({
type: 'warning',
message: t('quiz.alertIncomplete', 'กรุณาเลือกคำตอบให้ครบทุกข้อ'),
position: 'top',
timeout: 2000
})
return
}
// Confirmation before submission
if (!confirm(t('quiz.submitConfirm', 'ยืนยันการส่งคำตอบ?'))) {
return
}
}
// 2. Start Submission Process
if (timerInterval) clearInterval(timerInterval)
isSubmitting.value = true
currentScreen.value = 'result' // Switch to result screen immediately to show loader
currentScreen.value = 'result' // Switch to result screen to show progress
try {
// Validate completion (User Request: Must answer ALL questions)
if (!auto) {
const answeredCount = Object.keys(userAnswers.value).length
if (answeredCount < totalQuestions.value) {
$q.notify({
type: 'warning',
message: t('quiz.alertIncomplete', 'กรุณาเลือกคำตอบให้ครบทุกข้อ'),
position: 'top',
timeout: 2000
})
isSubmitting.value = false
currentScreen.value = 'taking'
return
}
// Confirm submission only if manual
if (!confirm(t('quiz.submitConfirm', 'ยืนยันการส่งคำตอบ?'))) {
isSubmitting.value = false
currentScreen.value = 'taking'
return
}
}
// Prepare Payload
const answersPayload = Object.entries(userAnswers.value).map(([qId, cId]) => ({
question_id: Number(qId),
@ -574,6 +569,7 @@ const getCorrectChoiceId = (questionId: number) => {
</button>
<button
v-if="quizResult?.is_passed"
@click="reviewQuiz"
class="w-full py-2 text-blue-500 hover:text-blue-700 dark:hover:text-blue-400 font-bold text-sm transition-colors mt-2"
>

View file

@ -13,7 +13,7 @@ definePageMeta({
const route = useRoute()
// courseId URL params ( integer)
const courseId = computed(() => parseInt(route.params.id as string))
const { fetchCourseById, enrollCourse } = useCourse()
const { fetchCourseById, enrollCourse, getLocalizedText } = useCourse()
// useAsyncData Server-side rendering (SSR)
// Key: 'course-{id}' cache ID
@ -54,12 +54,6 @@ const handleEnroll = async () => {
}
const getLocalizedText = (text: string | { th: string; en: string } | undefined | null) => {
if (!text) return ''
if (typeof text === 'string') return text
// @ts-ignore
return text.th || text.en || ''
}
useHead({

View file

@ -15,17 +15,12 @@ useHead({
})
const { currentUser } = useAuth()
const { fetchCourses } = useCourse() // Import useCourse
const { fetchCourses, getLocalizedText } = useCourse() // Import useCourse
const { fetchCategories } = useCategory() // Import useCategory
const { t } = useI18n()
// Helper to get localized text
const getLocalizedText = (text: string | { th: string; en: string } | undefined) => {
if (!text) return ''
if (typeof text === 'string') return text
return text.th || text.en || ''
}
// Recommended Courses State
// ( 3 )
@ -33,28 +28,24 @@ const recommendedCourses = ref<any[]>([])
onMounted(async () => {
// 1. Fetch Categories for mapping
//
const catRes = await fetchCategories()
const catMap = new Map()
if (catRes.success) {
catRes.data?.forEach((c: any) => catMap.set(c.id, c.name))
}
// 2. Fetch All Courses and Randomize
// 3
const res = await fetchCourses()
// 2. Fetch 3 Random Courses from Server
// Server ( API parameter random limit)
const res = await fetchCourses({ random: true, limit: 3, forceRefresh: true })
if (res.success && res.data?.length) {
// Shuffle array ()
const shuffled = [...res.data].sort(() => 0.5 - Math.random())
// Pick first 3 ( 3 )
recommendedCourses.value = shuffled.slice(0, 3).map((c: any) => ({
recommendedCourses.value = res.data.map((c: any) => ({
id: c.id,
title: getLocalizedText(c.title),
category: getLocalizedText(catMap.get(c.category_id)) || 'General', // Map Category ID to Name
duration: c.lessons ? `${c.lessons} ${t('course.lessonsUnit')}` : '', // Use lesson count or empty
category: getLocalizedText(catMap.get(c.category_id)) || 'General',
duration: c.lessons ? `${c.lessons} ${t('course.lessonsUnit')}` : '',
image: c.thumbnail_url || '',
badge: '', // No mock badge
badge: '',
badgeType: ''
}))
}

View file

@ -9,6 +9,7 @@ useHead({
})
const { currentUser, updateUserProfile, changePassword, uploadAvatar, sendVerifyEmail, fetchUserProfile } = useAuth()
const { fetchAllCertificates, getLocalizedText } = useCourse()
const { t } = useI18n()
@ -19,6 +20,10 @@ const isPasswordSaving = ref(false)
const isSendingVerify = ref(false)
const isHydrated = ref(false)
// Certificates State
const certificates = ref<any[]>([])
const isLoadingCerts = ref(false)
const formatDate = (dateString?: string) => {
if (!dateString) return '-'
try {
@ -46,18 +51,6 @@ const userData = ref({
// ...
// Watch for changes in global user state (e.g. after avatar upload)
watch(() => currentUser.value, (newUser) => {
if (newUser) {
userData.value.photoURL = newUser.photoURL || ''
userData.value.firstName = newUser.firstName
userData.value.lastName = newUser.lastName
userData.value.prefix = newUser.prefix?.th || ''
userData.value.email = newUser.email
userData.value.phone = newUser.phone || ''
userData.value.emailVerifiedAt = newUser.emailVerifiedAt
}
}, { deep: true })
const passwordForm = reactive({
currentPassword: '',
@ -188,7 +181,7 @@ const handleUpdatePassword = async () => {
isPasswordSaving.value = false
}
// Watch for changes in global user state (e.g. after avatar upload)
// Watch for changes in global user state (e.g. after avatar upload or profile update)
watch(() => currentUser.value, (newUser) => {
if (newUser) {
userData.value.photoURL = newUser.photoURL || ''
@ -197,11 +190,28 @@ watch(() => currentUser.value, (newUser) => {
userData.value.prefix = newUser.prefix?.th || ''
userData.value.email = newUser.email
userData.value.phone = newUser.phone || ''
userData.value.emailVerifiedAt = newUser.emailVerifiedAt
}
}, { deep: true })
const loadCertificates = async () => {
isLoadingCerts.value = true
const res = await fetchAllCertificates()
if (res.success) {
certificates.value = res.data || []
}
isLoadingCerts.value = false
}
const viewCertificate = (url: string) => {
if (url) {
window.open(url, '_blank')
}
}
onMounted(async () => {
await fetchUserProfile(true)
loadCertificates()
isHydrated.value = true
})
</script>
@ -281,6 +291,35 @@ onMounted(async () => {
</div>
</div>
<!-- Section: My Certificates -->
<div v-if="!isEditing && certificates.length > 0" class="mt-12 fade-in" style="animation-delay: 0.1s;">
<h2 class="text-2xl font-black mb-6 text-slate-900 dark:text-white flex items-center gap-3">
<q-icon name="workspace_premium" color="warning" size="32px" />
ประกาศนยบตรของฉ
</h2>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<div v-for="cert in certificates" :key="cert.certificate_id" class="card-premium p-6 hover:border-warning/50 transition-all group">
<div class="flex items-start justify-between mb-4">
<div class="p-3 rounded-xl bg-orange-50 dark:bg-orange-900/10 text-orange-600 dark:text-orange-400">
<q-icon name="card_membership" size="32px" />
</div>
<q-btn flat round color="primary" icon="download" @click="viewCertificate(cert.download_url)" class="opacity-0 group-hover:opacity-100 transition-opacity" />
</div>
<h3 class="font-bold text-slate-900 dark:text-white mb-1 line-clamp-1">{{ getLocalizedText(cert.course_title) }}</h3>
<p class="text-xs text-slate-500 dark:text-slate-400 mb-4 italic">ออกเม: {{ formatDate(cert.issued_at) }}</p>
<q-btn
unelevated
rounded
color="warning"
text-color="dark"
class="w-full font-bold"
label="ดูประกาศนียบัตร"
@click="viewCertificate(cert.download_url)"
/>
</div>
</div>
</div>
<div v-else class="grid grid-cols-1 lg:grid-cols-2 gap-8 fade-in">
<ProfileEditForm
@ -311,21 +350,42 @@ onMounted(async () => {
}
.card-premium {
@apply bg-white dark:bg-[#1e293b] border-slate-200 dark:border-white/5;
background-color: white;
border-color: #e2e8f0;
border-radius: 1.5rem;
border-width: 1px;
box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.05);
transition: all 0.3s ease;
}
.dark .card-premium {
background-color: #1e293b;
border-color: rgba(255, 255, 255, 0.05);
box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.3);
}
.info-group .label {
@apply text-xs font-black uppercase tracking-widest text-slate-500 dark:text-slate-400 block mb-2;
font-size: 0.75rem;
font-weight: 900;
text-transform: uppercase;
letter-spacing: 0.1em;
color: #64748b;
display: block;
margin-bottom: 0.5rem;
}
.dark .info-group .label {
color: #94a3b8;
}
.info-group .value {
@apply text-lg font-bold text-slate-900 dark:text-white;
font-size: 1.125rem;
font-weight: 700;
color: #0f172a;
}
.dark .info-group .value {
color: white;
}
.premium-q-input :deep(.q-field__control) {