readme.md // app/api/export-to-tutor-lms/route.js // Next.js API route for exporting generated courses to Tutor LMS Pro
import { TutorLMSCourseCreator } from '@/lib/tutor-lms/api-client';
export async function POST(request) { try { const courseData = await request.json(); console.log('Exporting course to Tutor LMS Pro:', courseData.title);
// Transform AI-generated content to Tutor LMS format
const tutorLMSData = await transformToTutorFormat(courseData);
// Initialize Tutor LMS API client
const tutorClient = new TutorLMSCourseCreator({
wordpressUrl: process.env.WORDPRESS_URL,
tutorApiKey: process.env.TUTOR_LMS_API_KEY,
tutorApiSecret: process.env.TUTOR_LMS_API_SECRET,
wpUsername: process.env.WP_API_USERNAME,
wpPassword: process.env.WP_API_PASSWORD
});
// Create course in Tutor LMS
const result = await tutorClient.createCompleteCourse(tutorLMSData);
return Response.json({
success: true,
message: 'Course exported successfully to Tutor LMS',
courseId: result.courseId,
tutorLmsUrl: `${process.env.WORDPRESS_URL}/courses/${result.courseId}`
});
} catch (error) { console.error('Export to Tutor LMS failed:', error); return Response.json( { error: 'Failed to export course', details: error.message }, { status: 500 } ); } }
/**
-
Transform AI-generated content to Tutor LMS JSON format */ async function transformToTutorFormat(aiGeneratedData) { return { course: { post_title: aiGeneratedData.title, post_content: formatCourseDescription(aiGeneratedData), post_excerpt: aiGeneratedData.summary, post_status: aiGeneratedData.publishStatus || 'draft', post_author: 1, post_type: 'courses', featured_image: aiGeneratedData.featuredImage,
course_meta: { _tutor_course_level: aiGeneratedData.level || 'beginner', _tutor_course_duration: '60,minutes', _tutor_course_max_students: 0, _tutor_course_requirements: aiGeneratedData.requirements || [], _tutor_course_target_audience: aiGeneratedData.targetAudience || [], _tutor_course_material_includes: generateMaterialList(aiGeneratedData), _tutor_course_benefits: aiGeneratedData.benefits || [], _tutor_course_price_type: aiGeneratedData.pricing || 'free', _tutor_course_price: aiGeneratedData.price || '0', _tutor_enable_qa: 'yes', _tutor_is_public_course: 'yes', _tutor_course_certificate: 'yes', course_category: aiGeneratedData.category, course_tag: aiGeneratedData.tags || [] },
video: aiGeneratedData.introVideo || null,
topics: await Promise.all(aiGeneratedData.topics.map(async (topic, topicIndex) => ({ topic_title: topic.title, topic_summary: topic.summary, topic_author: 1, topic_order: topicIndex + 1, topic_featured_image: topic.bannerImage, topic_key_takeaways: topic.keyTakeaways,
avatar_scripts: { topic_introduction: topic.avatarScripts?.introduction || generateTopicIntroScript(topic, 'en-GB'), topic_key_takeaways: topic.avatarScripts?.keyTakeaways || generateKeyTakeawayScript(topic.keyTakeaways, 'en-GB') }, lessons: await Promise.all(topic.lessons.map(async (lesson, lessonIndex) => ({ post_title: lesson.title, post_content: formatLessonContent(lesson), post_excerpt: lesson.summary, post_type: 'lesson', post_status: 'publish', lesson_order: lessonIndex + 1, lesson_duration: `${lesson.duration || 5},minutes`, lesson_preview: lessonIndex === 0, // First lesson as preview lesson_featured_image: lesson.thumbnail, lesson_media: { images: lesson.images || [], illustrations: lesson.illustrations || [], video_snippets: lesson.videoSnippets || [] }, lesson_key_takeaways: lesson.keyTakeaways, avatar_scripts: { lesson_introduction: lesson.avatarScripts?.introduction || generateLessonIntroScript(lesson, 'en-GB'), lesson_key_takeaways: lesson.avatarScripts?.keyTakeaways || generateLessonKeyTakeawayScript(lesson.keyTakeaways, 'en-GB') }, video: lesson.video || null }))), quiz: generateQuizStructure(topic.quiz, topicIndex + 1)}))),
assignments: aiGeneratedData.assignments || [],
avatar_scripts: { course_introduction: aiGeneratedData.avatarScripts?.courseIntro || generateCourseIntroScript(aiGeneratedData, 'en-GB'), course_conclusion: aiGeneratedData.avatarScripts?.courseConclusion || generateCourseConclusionScript(aiGeneratedData, 'en-GB'), transition_scripts: generateTransitionScripts(aiGeneratedData.topics, 'en-GB') },
certificates: { certificate_template: 'default', certificate_title: 'Certificate of Completion', certificate_content:
This certifies that {student_name} has successfully completed the course '${aiGeneratedData.title}' on {completion_date}} } }; }
/**
-
Format course description with proper HTML structure */ function formatCourseDescription(courseData) { return `
${courseData.description}
-
${courseData.learningObjectives?.map(obj => `
- ${obj} `).join('') || ''}
This comprehensive course includes:
- ${courseData.topics?.length || 4} in-depth topics
- ${(courseData.topics?.length || 4) * 3}+ engaging lessons
- ${(courseData.topics?.length || 4) * 5} assessment questions
- Mixed multimedia content (text, images, illustrations, videos)
- AI avatar narration throughout
${courseData.targetAudience?.join(', ') || 'Anyone interested in learning'}
`; }
/**
-
Format lesson content with multimedia elements */ function formatLessonContent(lesson) { return `
`; }
/**
- Generate quiz structure with 5 questions per topic */ function generateQuizStructure(quizData, topicNumber) { if (!quizData) return null;
return {
quiz_title: quizData.title || Topic ${topicNumber} Assessment,
quiz_description: quizData.description || 'Test your understanding of this topic',
quiz_author: 1,
quiz_settings: {
time_limit: {
time_value: 10,
time_type: 'minutes'
},
feedback_mode: 'default',
attempts_allowed: 3,
passing_grade: 70,
max_questions_for_answer: 5,
question_layout_view: 'single_question',
questions_order: 'rand'
},
questions: quizData.questions || generateDefaultQuestions(topicNumber)
};
}
/**
- Generate material list for course */ function generateMaterialList(courseData) { const lessonCount = (courseData.topics?.length || 4) * 3; const quizCount = (courseData.topics?.length || 4) * 5;
return [
${lessonCount}+ video lessons,
${courseData.topics?.length || 4} comprehensive topics,
${quizCount}+ quiz questions,
'Downloadable resources',
'British English avatar narration',
'Mixed multimedia content',
'Certificate of completion'
];
}
// Avatar Script Generation Functions (British English)
function generateCourseIntroScript(courseData, language = 'en-GB') {
return Welcome to '${courseData.title}'. I'm delighted to be your guide on this fascinating journey. Over the next hour, we'll explore ${courseData.topics?.length || 4} comprehensive topics that will transform your understanding of this subject. This course is designed specifically for ${courseData.targetAudience?.[0] || 'learners like you'}, ensuring you'll feel confident and capable throughout. By the end of our time together, you'll have gained practical skills and knowledge you can apply immediately. Shall we begin?;
}
function generateCourseConclusionScript(courseData, language = 'en-GB') {
return Brilliant work! You've successfully completed '${courseData.title}'. Throughout this course, you've mastered ${courseData.topics?.length || 4} essential topics and demonstrated your understanding through comprehensive assessments. The knowledge and skills you've gained will serve you well in your continued journey. Remember, learning is an ongoing process, and you've taken an important step forward today. Well done, and best of luck in applying what you've learnt!;
}
function generateTopicIntroScript(topic, language = 'en-GB') {
return Welcome to ${topic.title}. In this section, we'll explore ${topic.summary}. This topic contains ${topic.lessons?.length || 3} carefully crafted lessons that will build your understanding step by step. By the end, you'll have mastered key concepts and be ready to apply them practically. Let's dive in!;
}
function generateLessonIntroScript(lesson, language = 'en-GB') {
return Hello! In this lesson on ${lesson.title}, we'll discover ${lesson.summary || 'important concepts'}. This ${lesson.duration || 5}-minute lesson combines text, images, and practical examples to ensure clear understanding. Ready? Let's begin!;
}
function generateKeyTakeawayScript(takeaways, language = 'en-GB') {
return Let's review the key points: ${takeaways.join('. ')}. These insights will be valuable as we continue our learning journey.;
}
function generateLessonKeyTakeawayScript(takeaways, language = 'en-GB') {
return Excellent progress! Here are the essential points to remember: ${takeaways.join('. ')}. Take a moment to reflect on these before we move forward.;
}
function generateTransitionScripts(topics, language = 'en-GB') {
return topics.map((topic, index) => {
if (index === 0) return null;
return Well done completing ${topics[index - 1].title}! Now let's build on that foundation as we explore ${topic.title}. This next section will ${topic.summary?.toLowerCase() || 'expand your knowledge further'}.;
}).filter(Boolean);
}
function generateDefaultQuestions(topicNumber) {
// Generate 5 default questions if none provided
return Array(5).fill(null).map((_, i) => ({
question_title: Question ${i + 1} for Topic ${topicNumber},
question_type: i % 2 === 0 ? 'multiple_choice' : 'true_false',
question_mark: 1,
question_settings: {
answer_required: 1,
randomize_options: 1
},
question_answers: [],
avatar_feedback: {
correct: "Well done! That's absolutely correct.",
incorrect: "Not quite right. Let's review this concept again."
}
}));
}
// Export the transformation function for use in other parts of the app export { transformToTutorFormat };