feat: implement core e-learning pages, course composable, and i18n localization.
This commit is contained in:
parent
f736eb7f38
commit
e94410d0e7
9 changed files with 235 additions and 138 deletions
|
|
@ -7,6 +7,7 @@ export interface Course {
|
||||||
thumbnail_url: string
|
thumbnail_url: string
|
||||||
price: string
|
price: string
|
||||||
is_free: boolean
|
is_free: boolean
|
||||||
|
original_price?: string
|
||||||
have_certificate: boolean
|
have_certificate: boolean
|
||||||
status: string // DRAFT, PUBLISHED
|
status: string // DRAFT, PUBLISHED
|
||||||
category_id: number
|
category_id: number
|
||||||
|
|
@ -41,6 +42,15 @@ interface CourseResponse {
|
||||||
message: string
|
message: string
|
||||||
data: Course[]
|
data: Course[]
|
||||||
total: number
|
total: number
|
||||||
|
page?: number
|
||||||
|
limit?: number
|
||||||
|
totalPages?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SingleCourseResponse {
|
||||||
|
code: number
|
||||||
|
message: string
|
||||||
|
data: Course
|
||||||
}
|
}
|
||||||
|
|
||||||
// Interface สำหรับคอร์สที่ผู้ใช้ลงทะเบียนเรียนแล้ว (My Course)
|
// Interface สำหรับคอร์สที่ผู้ใช้ลงทะเบียนเรียนแล้ว (My Course)
|
||||||
|
|
@ -97,12 +107,6 @@ export interface QuizResult {
|
||||||
attempt_id: number
|
attempt_id: number
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==========================================
|
|
||||||
// Composable: useCourse
|
|
||||||
// หน้าที่: จัดการ Logic ทุกอย่างเกี่ยวกับคอร์สเรียน
|
|
||||||
// - ดึงข้อมูลคอร์ส (Public & Protected)
|
|
||||||
// - ลงทะเบียนเรียน (Enroll)
|
|
||||||
// - ติดตามความคืบหน้าการเรียน (Progress tracking)
|
|
||||||
// Interface สำหรับ Certificate
|
// Interface สำหรับ Certificate
|
||||||
export interface Certificate {
|
export interface Certificate {
|
||||||
certificate_id: number
|
certificate_id: number
|
||||||
|
|
@ -116,21 +120,37 @@ export interface Certificate {
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
|
// Composable: useCourse
|
||||||
|
// หน้าที่: จัดการ Logic ทุกอย่างเกี่ยวกับคอร์สเรียน
|
||||||
|
// - ดึงข้อมูลคอร์ส (Public & Protected)
|
||||||
|
// - ลงทะเบียนเรียน (Enroll)
|
||||||
|
// - ติดตามความคืบหน้าการเรียน (Progress tracking)
|
||||||
export const useCourse = () => {
|
export const useCourse = () => {
|
||||||
const config = useRuntimeConfig()
|
const config = useRuntimeConfig()
|
||||||
const API_BASE_URL = config.public.apiBase as string
|
const API_BASE_URL = config.public.apiBase as string
|
||||||
const { token } = useAuth()
|
const { token } = useAuth()
|
||||||
|
|
||||||
// ใช้ useState เพื่อเก็บรายชื่อคอร์สทั้งหมดใน Memory
|
// ใช้ useState เพื่อเก็บรายชื่อคอร์สทั้งหมดใน Memory (สำหรับกรณีดึงทั้งหมด)
|
||||||
const coursesState = useState<Course[]>('courses_cache', () => [])
|
const coursesState = useState<Course[]>('courses_cache', () => [])
|
||||||
const isCoursesLoaded = useState<boolean>('courses_loaded', () => false)
|
const isCoursesLoaded = useState<boolean>('courses_loaded', () => false)
|
||||||
|
|
||||||
// ฟังก์ชันดึงรายชื่อคอร์สทั้งหมด (Catalog)
|
/**
|
||||||
// ใช้สำหรับหน้า Discover/Browse
|
* ดึงรายชื่อคอร์สทั้งหมด (Catalog)
|
||||||
// Endpoint: GET /courses
|
* รองรับการกรองด้วยหมวดหมู่ และ Pagination
|
||||||
const fetchCourses = async (forceRefresh = false) => {
|
* Endpoint: GET /courses
|
||||||
// ถ้าโหลดไปแล้ว และไม่ได้บังคับ Refresh ให้ใช้ข้อมูลจาก State
|
*/
|
||||||
if (isCoursesLoaded.value && !forceRefresh && coursesState.value.length > 0) {
|
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 {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: coursesState.value,
|
data: coursesState.value,
|
||||||
|
|
@ -139,9 +159,18 @@ export const useCourse = () => {
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
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',
|
method: 'GET',
|
||||||
// ส่ง Token ไปด้วยถ้ามี
|
|
||||||
headers: token.value ? {
|
headers: token.value ? {
|
||||||
Authorization: `Bearer ${token.value}`
|
Authorization: `Bearer ${token.value}`
|
||||||
} : {}
|
} : {}
|
||||||
|
|
@ -149,33 +178,27 @@ export const useCourse = () => {
|
||||||
|
|
||||||
const courses = data.data || []
|
const courses = data.data || []
|
||||||
|
|
||||||
// เก็บลง State
|
// เก็บลง State เฉพาะกรณีดึง "ทั้งหมด"
|
||||||
coursesState.value = courses
|
if (isRequestingAll) {
|
||||||
isCoursesLoaded.value = true
|
coursesState.value = courses
|
||||||
|
isCoursesLoaded.value = true
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: courses,
|
data: courses,
|
||||||
total: data.total || 0
|
total: data.total || 0,
|
||||||
|
page: data.page,
|
||||||
|
limit: data.limit,
|
||||||
|
totalPages: data.totalPages
|
||||||
}
|
}
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
console.error('Fetch courses failed:', err)
|
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) {
|
if (err.statusCode === 429 || err.status === 429) {
|
||||||
await new Promise(resolve => setTimeout(resolve, 1500)); // Wait 1.5s
|
await new Promise(resolve => setTimeout(resolve, 1500))
|
||||||
try {
|
return fetchCourses(params) // Recursive retry
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|
@ -185,37 +208,24 @@ export const useCourse = () => {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ฟังก์ชันดึงรายละเอียดคอร์สตาม ID
|
/**
|
||||||
// Endpoint: GET /courses/:id
|
* ดึงรายละเอียดคอร์สตาม ID
|
||||||
|
* Endpoint: GET /courses/:id
|
||||||
|
*/
|
||||||
const fetchCourseById = async (id: number) => {
|
const fetchCourseById = async (id: number) => {
|
||||||
try {
|
try {
|
||||||
const data = await $fetch<CourseResponse>(`${API_BASE_URL}/courses/${id}`, {
|
const data = await $fetch<SingleCourseResponse>(`${API_BASE_URL}/courses/${id}`, {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
headers: token.value ? {
|
headers: token.value ? {
|
||||||
Authorization: `Bearer ${token.value}`
|
Authorization: `Bearer ${token.value}`
|
||||||
} : {}
|
} : {}
|
||||||
})
|
})
|
||||||
|
|
||||||
// Logic จัดการข้อมูลที่ได้รับ (API อาจส่งกลับมาเป็น Array หรือ Object)
|
if (!data.data) throw new Error('Course not found')
|
||||||
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')
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: courseData
|
data: data.data // ข้อมูลคอร์สตัวเดียว
|
||||||
}
|
}
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
console.error('Fetch course details failed:', err)
|
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 {
|
return {
|
||||||
|
getLocalizedText,
|
||||||
fetchCourses,
|
fetchCourses,
|
||||||
fetchCourseById,
|
fetchCourseById,
|
||||||
enrollCourse,
|
enrollCourse,
|
||||||
|
|
|
||||||
|
|
@ -159,7 +159,8 @@
|
||||||
"next": "Next",
|
"next": "Next",
|
||||||
"back": "Back",
|
"back": "Back",
|
||||||
"backToHome": "Back to Home",
|
"backToHome": "Back to Home",
|
||||||
"error": "Error"
|
"error": "Error",
|
||||||
|
"loading": "Loading"
|
||||||
},
|
},
|
||||||
"classroom": {
|
"classroom": {
|
||||||
"backToDashboard": "Back to My Courses",
|
"backToDashboard": "Back to My Courses",
|
||||||
|
|
|
||||||
|
|
@ -160,7 +160,8 @@
|
||||||
"next": "ถัดไป",
|
"next": "ถัดไป",
|
||||||
"back": "ย้อนกลับ",
|
"back": "ย้อนกลับ",
|
||||||
"backToHome": "กลับสู่หน้าหลัก",
|
"backToHome": "กลับสู่หน้าหลัก",
|
||||||
"error": "เกิดข้อผิดพลาด"
|
"error": "เกิดข้อผิดพลาด",
|
||||||
|
"loading": "กำลังโหลด"
|
||||||
},
|
},
|
||||||
"classroom": {
|
"classroom": {
|
||||||
"backToDashboard": "กลับไปคอร์สของฉัน",
|
"backToDashboard": "กลับไปคอร์สของฉัน",
|
||||||
|
|
|
||||||
|
|
@ -28,11 +28,16 @@ const isLoading = ref(false);
|
||||||
const isLoadingDetail = ref(false);
|
const isLoadingDetail = ref(false);
|
||||||
const isEnrolling = ref(false);
|
const isEnrolling = ref(false);
|
||||||
|
|
||||||
|
// Pagination State
|
||||||
|
const currentPage = ref(1);
|
||||||
|
const totalPages = ref(1);
|
||||||
|
const itemsPerPage = 12;
|
||||||
|
|
||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const { currentUser } = useAuth();
|
const { currentUser } = useAuth();
|
||||||
const { fetchCategories } = useCategory();
|
const { fetchCategories } = useCategory();
|
||||||
const { fetchCourses, fetchCourseById, enrollCourse } = useCourse();
|
const { fetchCourses, fetchCourseById, enrollCourse, getLocalizedText } = useCourse();
|
||||||
|
|
||||||
|
|
||||||
// 2. Computed Properties
|
// 2. Computed Properties
|
||||||
|
|
@ -41,9 +46,13 @@ const sortOptions = computed(() => [t('discovery.sortRecent')]);
|
||||||
|
|
||||||
const filteredCourses = computed(() => {
|
const filteredCourses = computed(() => {
|
||||||
let result = courses.value;
|
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));
|
result = result.filter(c => selectedCategoryIds.value.includes(c.category_id));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (searchQuery.value) {
|
if (searchQuery.value) {
|
||||||
const query = searchQuery.value.toLowerCase();
|
const query = searchQuery.value.toLowerCase();
|
||||||
result = result.filter(c => {
|
result = result.filter(c => {
|
||||||
|
|
@ -56,11 +65,7 @@ const filteredCourses = computed(() => {
|
||||||
});
|
});
|
||||||
|
|
||||||
// 3. Helper Functions
|
// 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
|
// 4. API Actions
|
||||||
const loadCategories = async () => {
|
const loadCategories = async () => {
|
||||||
|
|
@ -68,11 +73,23 @@ const loadCategories = async () => {
|
||||||
if (res.success) categories.value = res.data || [];
|
if (res.success) categories.value = res.data || [];
|
||||||
};
|
};
|
||||||
|
|
||||||
const loadCourses = async () => {
|
const loadCourses = async (page = 1) => {
|
||||||
isLoading.value = true;
|
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) {
|
if (res.success) {
|
||||||
courses.value = res.data || [];
|
courses.value = res.data || [];
|
||||||
|
totalPages.value = res.totalPages || 1;
|
||||||
|
currentPage.value = res.page || 1;
|
||||||
}
|
}
|
||||||
isLoading.value = false;
|
isLoading.value = false;
|
||||||
};
|
};
|
||||||
|
|
@ -98,6 +115,12 @@ const handleEnroll = async (id: number) => {
|
||||||
isEnrolling.value = false;
|
isEnrolling.value = false;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Watch for category selection changes to reload courses
|
||||||
|
watch(selectedCategoryIds, () => {
|
||||||
|
currentPage.value = 1;
|
||||||
|
loadCourses(1);
|
||||||
|
}, { deep: true });
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
loadCategories();
|
loadCategories();
|
||||||
loadCourses();
|
loadCourses();
|
||||||
|
|
@ -166,6 +189,22 @@ onMounted(() => {
|
||||||
/>
|
/>
|
||||||
</div>
|
</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 -->
|
<!-- Empty State -->
|
||||||
<div
|
<div
|
||||||
v-else
|
v-else
|
||||||
|
|
|
||||||
|
|
@ -20,7 +20,7 @@ const route = useRoute()
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const { t } = useI18n()
|
const { t } = useI18n()
|
||||||
const { user } = useAuth()
|
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)
|
// Media Prefs (Global Volume)
|
||||||
const { volume, muted: isMuted, setVolume, setMuted, applyTo } = useMediaPrefs()
|
const { volume, muted: isMuted, setVolume, setMuted, applyTo } = useMediaPrefs()
|
||||||
|
|
||||||
|
|
@ -94,12 +94,6 @@ const currentTime = ref(0)
|
||||||
const duration = 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 = () => {
|
const toggleSidebar = () => {
|
||||||
sidebarOpen.value = !sidebarOpen.value
|
sidebarOpen.value = !sidebarOpen.value
|
||||||
|
|
|
||||||
|
|
@ -238,37 +238,32 @@ const retryQuiz = () => {
|
||||||
}
|
}
|
||||||
|
|
||||||
const submitQuiz = async (auto = false) => {
|
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)
|
if (timerInterval) clearInterval(timerInterval)
|
||||||
|
|
||||||
isSubmitting.value = true
|
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 {
|
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
|
// Prepare Payload
|
||||||
const answersPayload = Object.entries(userAnswers.value).map(([qId, cId]) => ({
|
const answersPayload = Object.entries(userAnswers.value).map(([qId, cId]) => ({
|
||||||
question_id: Number(qId),
|
question_id: Number(qId),
|
||||||
|
|
@ -574,6 +569,7 @@ const getCorrectChoiceId = (questionId: number) => {
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
|
v-if="quizResult?.is_passed"
|
||||||
@click="reviewQuiz"
|
@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"
|
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"
|
||||||
>
|
>
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,7 @@ definePageMeta({
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
// ดึง courseId จาก URL params (แปลงเป็น integer)
|
// ดึง courseId จาก URL params (แปลงเป็น integer)
|
||||||
const courseId = computed(() => parseInt(route.params.id as string))
|
const courseId = computed(() => parseInt(route.params.id as string))
|
||||||
const { fetchCourseById, enrollCourse } = useCourse()
|
const { fetchCourseById, enrollCourse, getLocalizedText } = useCourse()
|
||||||
|
|
||||||
// ใช้ useAsyncData ดึงข้อมูลคอร์ส Server-side rendering (SSR)
|
// ใช้ useAsyncData ดึงข้อมูลคอร์ส Server-side rendering (SSR)
|
||||||
// Key: 'course-{id}' เพื่อให้ cache แยกกันตาม ID
|
// 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({
|
useHead({
|
||||||
|
|
|
||||||
|
|
@ -15,17 +15,12 @@ useHead({
|
||||||
})
|
})
|
||||||
|
|
||||||
const { currentUser } = useAuth()
|
const { currentUser } = useAuth()
|
||||||
const { fetchCourses } = useCourse() // Import useCourse
|
const { fetchCourses, getLocalizedText } = useCourse() // Import useCourse
|
||||||
const { fetchCategories } = useCategory() // Import useCategory
|
const { fetchCategories } = useCategory() // Import useCategory
|
||||||
|
|
||||||
const { t } = useI18n()
|
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
|
// Recommended Courses State
|
||||||
// เก็บข้อมูลคอร์สแนะนำ (สุ่มมา 3 คอร์ส)
|
// เก็บข้อมูลคอร์สแนะนำ (สุ่มมา 3 คอร์ส)
|
||||||
|
|
@ -33,28 +28,24 @@ const recommendedCourses = ref<any[]>([])
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
// 1. Fetch Categories for mapping
|
// 1. Fetch Categories for mapping
|
||||||
// ดึงหมวดหมู่เพื่อเอามาแสดงชื่อหมวดหมู่ในการ์ด
|
|
||||||
const catRes = await fetchCategories()
|
const catRes = await fetchCategories()
|
||||||
const catMap = new Map()
|
const catMap = new Map()
|
||||||
if (catRes.success) {
|
if (catRes.success) {
|
||||||
catRes.data?.forEach((c: any) => catMap.set(c.id, c.name))
|
catRes.data?.forEach((c: any) => catMap.set(c.id, c.name))
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Fetch All Courses and Randomize
|
// 2. Fetch 3 Random Courses from Server
|
||||||
// ดึงคอร์สทั้งหมดและสุ่มเลือกมา 3 อัน
|
// ดึงคอร์สแบบสุ่มจาก Server โดยตรง (ผ่าน API ใหม่ที่เพิ่ม parameter random และ limit)
|
||||||
const res = await fetchCourses()
|
const res = await fetchCourses({ random: true, limit: 3, forceRefresh: true })
|
||||||
|
|
||||||
if (res.success && res.data?.length) {
|
if (res.success && res.data?.length) {
|
||||||
// Shuffle array (สุ่มลำดับ)
|
recommendedCourses.value = res.data.map((c: any) => ({
|
||||||
const shuffled = [...res.data].sort(() => 0.5 - Math.random())
|
|
||||||
|
|
||||||
// Pick first 3 (เลือกมา 3 อันแรก)
|
|
||||||
recommendedCourses.value = shuffled.slice(0, 3).map((c: any) => ({
|
|
||||||
id: c.id,
|
id: c.id,
|
||||||
title: getLocalizedText(c.title),
|
title: getLocalizedText(c.title),
|
||||||
category: getLocalizedText(catMap.get(c.category_id)) || 'General', // Map Category ID to Name
|
category: getLocalizedText(catMap.get(c.category_id)) || 'General',
|
||||||
duration: c.lessons ? `${c.lessons} ${t('course.lessonsUnit')}` : '', // Use lesson count or empty
|
duration: c.lessons ? `${c.lessons} ${t('course.lessonsUnit')}` : '',
|
||||||
image: c.thumbnail_url || '',
|
image: c.thumbnail_url || '',
|
||||||
badge: '', // No mock badge
|
badge: '',
|
||||||
badgeType: ''
|
badgeType: ''
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,7 @@ useHead({
|
||||||
})
|
})
|
||||||
|
|
||||||
const { currentUser, updateUserProfile, changePassword, uploadAvatar, sendVerifyEmail, fetchUserProfile } = useAuth()
|
const { currentUser, updateUserProfile, changePassword, uploadAvatar, sendVerifyEmail, fetchUserProfile } = useAuth()
|
||||||
|
const { fetchAllCertificates, getLocalizedText } = useCourse()
|
||||||
const { t } = useI18n()
|
const { t } = useI18n()
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -19,6 +20,10 @@ const isPasswordSaving = ref(false)
|
||||||
const isSendingVerify = ref(false)
|
const isSendingVerify = ref(false)
|
||||||
const isHydrated = ref(false)
|
const isHydrated = ref(false)
|
||||||
|
|
||||||
|
// Certificates State
|
||||||
|
const certificates = ref<any[]>([])
|
||||||
|
const isLoadingCerts = ref(false)
|
||||||
|
|
||||||
const formatDate = (dateString?: string) => {
|
const formatDate = (dateString?: string) => {
|
||||||
if (!dateString) return '-'
|
if (!dateString) return '-'
|
||||||
try {
|
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({
|
const passwordForm = reactive({
|
||||||
currentPassword: '',
|
currentPassword: '',
|
||||||
|
|
@ -188,7 +181,7 @@ const handleUpdatePassword = async () => {
|
||||||
isPasswordSaving.value = false
|
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) => {
|
watch(() => currentUser.value, (newUser) => {
|
||||||
if (newUser) {
|
if (newUser) {
|
||||||
userData.value.photoURL = newUser.photoURL || ''
|
userData.value.photoURL = newUser.photoURL || ''
|
||||||
|
|
@ -197,11 +190,28 @@ watch(() => currentUser.value, (newUser) => {
|
||||||
userData.value.prefix = newUser.prefix?.th || ''
|
userData.value.prefix = newUser.prefix?.th || ''
|
||||||
userData.value.email = newUser.email
|
userData.value.email = newUser.email
|
||||||
userData.value.phone = newUser.phone || ''
|
userData.value.phone = newUser.phone || ''
|
||||||
|
userData.value.emailVerifiedAt = newUser.emailVerifiedAt
|
||||||
}
|
}
|
||||||
}, { deep: true })
|
}, { 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 () => {
|
onMounted(async () => {
|
||||||
await fetchUserProfile(true)
|
await fetchUserProfile(true)
|
||||||
|
loadCertificates()
|
||||||
isHydrated.value = true
|
isHydrated.value = true
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
@ -281,6 +291,35 @@ onMounted(async () => {
|
||||||
</div>
|
</div>
|
||||||
</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">
|
<div v-else class="grid grid-cols-1 lg:grid-cols-2 gap-8 fade-in">
|
||||||
|
|
||||||
<ProfileEditForm
|
<ProfileEditForm
|
||||||
|
|
@ -311,21 +350,42 @@ onMounted(async () => {
|
||||||
}
|
}
|
||||||
|
|
||||||
.card-premium {
|
.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-radius: 1.5rem;
|
||||||
border-width: 1px;
|
border-width: 1px;
|
||||||
box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.05);
|
box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.05);
|
||||||
transition: all 0.3s ease;
|
transition: all 0.3s ease;
|
||||||
}
|
}
|
||||||
|
|
||||||
.dark .card-premium {
|
.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);
|
box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.3);
|
||||||
}
|
}
|
||||||
|
|
||||||
.info-group .label {
|
.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 {
|
.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) {
|
.premium-q-input :deep(.q-field__control) {
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue