Add Context APIs and refactor vocab models
All checks were successful
Deploy to Production / deploy (push) Successful in 25s

Introduce Context and ContextGuide features: add Sequelize models (models/Context.js, models/ContextGuide.js), controllers (controllers/contextController.js, controllers/contextGuideController.js) and authenticated route handlers (routes/contextRoutes.js, routes/contextGuideRoutes.js). Wire the new routes into app.js and export the models from models/index.js. Refactor vocabulary: remove VocabForm, VocabMapping and VocabRelation models and relationships, update models/Vocab.js schema and indexes, and add migrate-vocab.js to drop/recreate the vocab table for the new schema. Also add a lesson editor UI (public/lesson-editor.html) and a small cleanup in models/Lesson.js.
This commit is contained in:
silverpro89
2026-02-02 10:05:46 +07:00
parent 81a7ab5b6c
commit 97dbbd4d12
15 changed files with 1018 additions and 248 deletions

6
app.js
View File

@@ -40,6 +40,8 @@ const grammarRoutes = require('./routes/grammarRoutes');
const storyRoutes = require('./routes/storyRoutes'); const storyRoutes = require('./routes/storyRoutes');
const learningContentRoutes = require('./routes/learningContentRoutes'); const learningContentRoutes = require('./routes/learningContentRoutes');
const uploadRoutes = require('./routes/uploadRoutes'); const uploadRoutes = require('./routes/uploadRoutes');
const contextRoutes = require('./routes/contextRoutes');
const contextGuideRoutes = require('./routes/contextGuideRoutes');
/** /**
* Initialize Express Application * Initialize Express Application
@@ -165,6 +167,8 @@ app.get('/api', (req, res) => {
games: '/api/games', games: '/api/games',
gameTypes: '/api/game-types', gameTypes: '/api/game-types',
vocab: '/api/vocab', vocab: '/api/vocab',
contexts: '/api/contexts',
contextGuides: '/api/context-guides',
upload: '/api/upload', upload: '/api/upload',
}, },
documentation: '/api-docs', documentation: '/api-docs',
@@ -224,6 +228,8 @@ app.use('/api/grammar', grammarRoutes);
app.use('/api/stories', storyRoutes); app.use('/api/stories', storyRoutes);
app.use('/api/learning-content', learningContentRoutes); app.use('/api/learning-content', learningContentRoutes);
app.use('/api/upload', uploadRoutes); app.use('/api/upload', uploadRoutes);
app.use('/api/contexts', contextRoutes);
app.use('/api/context-guides', contextGuideRoutes);
/** /**
* Queue Status Endpoint * Queue Status Endpoint

View File

@@ -0,0 +1,139 @@
const { Context } = require('../models');
/**
* Context Controller
*/
class ContextController {
/**
* Get all contexts with pagination and filters
*/
async getAllContexts(req, res, next) {
try {
const { page = 1, limit = 50, type, title } = req.query;
const offset = (page - 1) * limit;
const where = {};
if (type) where.type = type;
if (title) where.title = title;
const { count, rows } = await Context.findAndCountAll({
where,
limit: parseInt(limit),
offset: parseInt(offset),
order: [['created_at', 'DESC']]
});
res.json({
success: true,
data: {
contexts: rows,
pagination: {
total: count,
page: parseInt(page),
limit: parseInt(limit),
totalPages: Math.ceil(count / limit)
}
}
});
} catch (error) {
next(error);
}
}
/**
* Get context by UUID
*/
async getContextById(req, res, next) {
try {
const { id } = req.params;
const context = await Context.findByPk(id);
if (!context) {
return res.status(404).json({
success: false,
message: 'Context not found'
});
}
res.json({
success: true,
data: context
});
} catch (error) {
next(error);
}
}
/**
* Create new context
*/
async createContext(req, res, next) {
try {
const context = await Context.create(req.body);
res.status(201).json({
success: true,
message: 'Context created successfully',
data: context
});
} catch (error) {
next(error);
}
}
/**
* Update context
*/
async updateContext(req, res, next) {
try {
const { id } = req.params;
const updates = req.body;
const context = await Context.findByPk(id);
if (!context) {
return res.status(404).json({
success: false,
message: 'Context not found'
});
}
await context.update(updates);
res.json({
success: true,
message: 'Context updated successfully',
data: context
});
} catch (error) {
next(error);
}
}
/**
* Delete context
*/
async deleteContext(req, res, next) {
try {
const { id } = req.params;
const context = await Context.findByPk(id);
if (!context) {
return res.status(404).json({
success: false,
message: 'Context not found'
});
}
await context.destroy();
res.json({
success: true,
message: 'Context deleted successfully'
});
} catch (error) {
next(error);
}
}
}
module.exports = new ContextController();

View File

@@ -0,0 +1,139 @@
const { ContextGuide } = require('../models');
/**
* ContextGuide Controller
*/
class ContextGuideController {
/**
* Get all context guides with pagination and filters
*/
async getAllContextGuides(req, res, next) {
try {
const { page = 1, limit = 50, name, title } = req.query;
const offset = (page - 1) * limit;
const where = {};
if (name) where.name = name;
if (title) where.title = title;
const { count, rows } = await ContextGuide.findAndCountAll({
where,
limit: parseInt(limit),
offset: parseInt(offset),
order: [['created_at', 'DESC']]
});
res.json({
success: true,
data: {
guides: rows,
pagination: {
total: count,
page: parseInt(page),
limit: parseInt(limit),
totalPages: Math.ceil(count / limit)
}
}
});
} catch (error) {
next(error);
}
}
/**
* Get context guide by UUID
*/
async getContextGuideById(req, res, next) {
try {
const { id } = req.params;
const guide = await ContextGuide.findByPk(id);
if (!guide) {
return res.status(404).json({
success: false,
message: 'Context guide not found'
});
}
res.json({
success: true,
data: guide
});
} catch (error) {
next(error);
}
}
/**
* Create new context guide
*/
async createContextGuide(req, res, next) {
try {
const guide = await ContextGuide.create(req.body);
res.status(201).json({
success: true,
message: 'Context guide created successfully',
data: guide
});
} catch (error) {
next(error);
}
}
/**
* Update context guide
*/
async updateContextGuide(req, res, next) {
try {
const { id } = req.params;
const updates = req.body;
const guide = await ContextGuide.findByPk(id);
if (!guide) {
return res.status(404).json({
success: false,
message: 'Context guide not found'
});
}
await guide.update(updates);
res.json({
success: true,
message: 'Context guide updated successfully',
data: guide
});
} catch (error) {
next(error);
}
}
/**
* Delete context guide
*/
async deleteContextGuide(req, res, next) {
try {
const { id } = req.params;
const guide = await ContextGuide.findByPk(id);
if (!guide) {
return res.status(404).json({
success: false,
message: 'Context guide not found'
});
}
await guide.destroy();
res.json({
success: true,
message: 'Context guide deleted successfully'
});
} catch (error) {
next(error);
}
}
}
module.exports = new ContextGuideController();

36
migrate-vocab.js Normal file
View File

@@ -0,0 +1,36 @@
/**
* Drop and recreate Vocab table with new schema
*/
const { sequelize } = require('./config/database');
const { Vocab } = require('./models');
async function migrateVocabTable() {
try {
console.log('🔄 Starting vocab table migration...');
await sequelize.authenticate();
console.log('✅ Database connection OK');
// Drop old vocab-related tables
console.log('🗑️ Dropping old vocab-related tables...');
await sequelize.query('DROP TABLE IF EXISTS `vocab_relation`');
await sequelize.query('DROP TABLE IF EXISTS `vocab_form`');
await sequelize.query('DROP TABLE IF EXISTS `vocab_mapping`');
await sequelize.query('DROP TABLE IF EXISTS `vocab`');
console.log('✅ Old tables dropped');
// Recreate vocab table with new schema
console.log('📊 Creating new vocab table...');
await Vocab.sync({ force: true });
console.log('✅ Vocab table created with new schema');
console.log('\n✅ Vocab migration complete!');
process.exit(0);
} catch (error) {
console.error('❌ Error migrating vocab table:', error.message);
console.error(error.stack);
process.exit(1);
}
}
migrateVocabTable();

92
models/Context.js Normal file
View File

@@ -0,0 +1,92 @@
const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');
const Context = sequelize.define('Context', {
uuid: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
comment: 'Unique identifier for context'
},
title: {
type: DataTypes.STRING(255),
allowNull: false,
comment: 'Title of the context item'
},
context: {
type: DataTypes.TEXT,
allowNull: false,
comment: 'Context description'
},
knowledge: {
type: DataTypes.TEXT,
comment: 'Additional knowledge or information'
},
type: {
type: DataTypes.STRING(50),
allowNull: false,
comment: 'Context type (e.g., vocabulary, grammar)'
},
desc: {
type: DataTypes.TEXT,
comment: 'Detailed description or requirement'
},
prompt: {
type: DataTypes.JSON,
comment: 'Prompt configuration object'
},
image: {
type: DataTypes.JSON,
comment: 'Array of image URLs'
},
difficulty: {
type: DataTypes.INTEGER,
defaultValue: 1,
comment: 'Difficulty level (1-10)'
},
max: {
type: DataTypes.INTEGER,
defaultValue: 0,
comment: 'Maximum number of images or items'
},
isPrompt: {
type: DataTypes.BOOLEAN,
defaultValue: false,
comment: 'Prompt created (0/1)'
},
isList: {
type: DataTypes.BOOLEAN,
defaultValue: false,
comment: 'Waiting for more images (0/1)'
},
isApprove: {
type: DataTypes.BOOLEAN,
defaultValue: false,
comment: 'Teacher approval status (0/1)'
},
created_at: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW
},
updated_at: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW
}
}, {
tableName: 'context',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
indexes: [
{
name: 'idx_context_type',
fields: ['type']
},
{
name: 'idx_context_title',
fields: ['title']
}
]
});
module.exports = Context;

51
models/ContextGuide.js Normal file
View File

@@ -0,0 +1,51 @@
const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');
const ContextGuide = sequelize.define('ContextGuide', {
uuid: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
comment: 'Unique identifier for context guide'
},
title: {
type: DataTypes.STRING(255),
allowNull: false,
comment: 'Guide title'
},
name: {
type: DataTypes.STRING(255),
allowNull: false,
comment: 'Target field name for AI processing'
},
data: {
type: DataTypes.JSON,
allowNull: false,
comment: 'Guide data (text or json)'
},
created_at: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW
},
updated_at: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW
}
}, {
tableName: 'context_guide',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
indexes: [
{
name: 'idx_context_guide_title',
fields: ['title']
},
{
name: 'idx_context_guide_name',
fields: ['name']
}
]
});
module.exports = ContextGuide;

View File

@@ -63,7 +63,6 @@ const Lesson = sequelize.define('lessons', {
type: DataTypes.STRING(50), type: DataTypes.STRING(50),
comment: 'Loại content cho URL: video, audio, pdf, external_link, youtube, etc.' comment: 'Loại content cho URL: video, audio, pdf, external_link, youtube, etc.'
}, },
duration_minutes: { duration_minutes: {
type: DataTypes.INTEGER, type: DataTypes.INTEGER,
comment: 'Thời lượng (phút)' comment: 'Thời lượng (phút)'

View File

@@ -8,21 +8,32 @@ const Vocab = sequelize.define('Vocab', {
primaryKey: true, primaryKey: true,
comment: 'Unique identifier for vocabulary entry' comment: 'Unique identifier for vocabulary entry'
}, },
vocab_code: { // Từ thực tế (wash, washes, washing, ate, eaten...)
type: DataTypes.STRING(50), text: {
unique: true, type: DataTypes.STRING(100),
allowNull: false, allowNull: false,
comment: 'Unique code for vocabulary (e.g., vocab-001-eat)' index: true
}, },
// Từ gốc để nhóm lại (wash, eat...)
base_word: { base_word: {
type: DataTypes.STRING(100), type: DataTypes.STRING(100),
allowNull: false, allowNull: false,
comment: 'Base form of the word' index: true
}, },
// Đã xuất hiện trong khối nào, bài học nào, lesson nào
// Ví dụ 111 là grade 1, unit 1, lesson 1
location: {
type: DataTypes.INTEGER,
comment: 'Location or source of the vocabulary'
},
// Loại biến thể (V1, V2, V3, V_ing, Noun_Form...)
form_key: {
type: DataTypes.STRING(20),
defaultValue: 'base'
},
// Nội dung dùng chung (có thể lưu JSON để dễ quản lý hoặc dùng chung cho cả group)
translation: { translation: {
type: DataTypes.STRING(200), type: DataTypes.STRING(200)
allowNull: false,
comment: 'Vietnamese translation'
}, },
difficulty_score: { difficulty_score: {
type: DataTypes.INTEGER, type: DataTypes.INTEGER,
@@ -33,6 +44,10 @@ const Vocab = sequelize.define('Vocab', {
type: DataTypes.STRING(100), type: DataTypes.STRING(100),
comment: 'Category of the word (e.g., Action Verbs, Nouns)' comment: 'Category of the word (e.g., Action Verbs, Nouns)'
}, },
topic: {
type: DataTypes.STRING(100),
comment: 'Topic of the word (e.g., Food, Travel, Education)'
},
images: { images: {
type: DataTypes.JSON, type: DataTypes.JSON,
comment: 'Array of image URLs' comment: 'Array of image URLs'
@@ -73,8 +88,8 @@ const Vocab = sequelize.define('Vocab', {
updatedAt: 'updated_at', updatedAt: 'updated_at',
indexes: [ indexes: [
{ {
name: 'idx_vocab_code', name: 'idx_vocab_text',
fields: ['vocab_code'] fields: ['text']
}, },
{ {
name: 'idx_base_word', name: 'idx_base_word',
@@ -83,6 +98,10 @@ const Vocab = sequelize.define('Vocab', {
{ {
name: 'idx_category', name: 'idx_category',
fields: ['category'] fields: ['category']
},
{
name: 'idx_location',
fields: ['location']
} }
] ]
}); });

View File

@@ -1,78 +0,0 @@
const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');
const VocabForm = sequelize.define('VocabForm', {
form_id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
comment: 'Unique identifier for word form'
},
vocab_id: {
type: DataTypes.UUID,
allowNull: false,
references: {
model: 'vocab',
key: 'vocab_id'
},
onDelete: 'CASCADE',
comment: 'Reference to vocabulary entry'
},
form_key: {
type: DataTypes.STRING(50),
allowNull: false,
comment: 'Form identifier (v1, v2, v3, v_s_es, v_ing, etc.)'
},
text: {
type: DataTypes.STRING(100),
allowNull: false,
comment: 'The actual word form (e.g., eat, eats, eating, ate)'
},
phonetic: {
type: DataTypes.STRING(100),
comment: 'IPA phonetic transcription (e.g., /iːt/)'
},
audio_url: {
type: DataTypes.STRING(500),
comment: 'URL to audio pronunciation file'
},
min_grade: {
type: DataTypes.INTEGER,
defaultValue: 1,
comment: 'Minimum grade level to unlock this form'
},
description: {
type: DataTypes.TEXT,
comment: 'Description or usage note for this form'
},
created_at: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW
},
updated_at: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW
}
}, {
tableName: 'vocab_form',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
indexes: [
{
name: 'idx_vocab_form_vocab',
fields: ['vocab_id']
},
{
name: 'idx_vocab_form_key',
fields: ['form_key']
},
{
name: 'idx_vocab_form_unique',
unique: true,
fields: ['vocab_id', 'form_key']
}
]
});
module.exports = VocabForm;

View File

@@ -1,72 +0,0 @@
const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');
const VocabMapping = sequelize.define('VocabMapping', {
mapping_id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
comment: 'Unique identifier for curriculum mapping'
},
vocab_id: {
type: DataTypes.UUID,
allowNull: false,
references: {
model: 'vocab',
key: 'vocab_id'
},
onDelete: 'CASCADE',
comment: 'Reference to vocabulary entry'
},
book_id: {
type: DataTypes.STRING(100),
allowNull: false,
comment: 'Book/curriculum identifier (e.g., global-success-1)'
},
grade: {
type: DataTypes.INTEGER,
allowNull: false,
comment: 'Grade level'
},
unit: {
type: DataTypes.INTEGER,
comment: 'Unit number in the book'
},
lesson: {
type: DataTypes.INTEGER,
comment: 'Lesson number in the unit'
},
form_key: {
type: DataTypes.STRING(50),
comment: 'Which form to use (v1, v_s_es, v_ing, v2, v3, etc.)'
},
context_note: {
type: DataTypes.TEXT,
comment: 'Additional context for this mapping'
},
created_at: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW
}
}, {
tableName: 'vocab_mapping',
timestamps: true,
createdAt: 'created_at',
updatedAt: false,
indexes: [
{
name: 'idx_vocab_mapping_vocab',
fields: ['vocab_id']
},
{
name: 'idx_vocab_mapping_book_grade',
fields: ['book_id', 'grade']
},
{
name: 'idx_vocab_mapping_unit_lesson',
fields: ['unit', 'lesson']
}
]
});
module.exports = VocabMapping;

View File

@@ -1,65 +0,0 @@
const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');
const VocabRelation = sequelize.define('VocabRelation', {
relation_id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
comment: 'Unique identifier for vocabulary relation'
},
vocab_id: {
type: DataTypes.UUID,
allowNull: false,
references: {
model: 'vocab',
key: 'vocab_id'
},
onDelete: 'CASCADE',
comment: 'Reference to vocabulary entry'
},
relation_type: {
type: DataTypes.ENUM('synonym', 'antonym', 'related'),
allowNull: false,
comment: 'Type of relation (synonym, antonym, related)'
},
related_word: {
type: DataTypes.STRING(100),
allowNull: false,
comment: 'The related word (e.g., consume, dine, fast)'
},
related_vocab_id: {
type: DataTypes.UUID,
references: {
model: 'vocab',
key: 'vocab_id'
},
onDelete: 'SET NULL',
comment: 'Reference to related vocab entry if it exists in system'
},
created_at: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW
}
}, {
tableName: 'vocab_relation',
timestamps: true,
createdAt: 'created_at',
updatedAt: false,
indexes: [
{
name: 'idx_vocab_relation_vocab',
fields: ['vocab_id']
},
{
name: 'idx_vocab_relation_type',
fields: ['relation_type']
},
{
name: 'idx_vocab_relation_related',
fields: ['related_vocab_id']
}
]
});
module.exports = VocabRelation;

View File

@@ -35,9 +35,6 @@ const LessonLeaderboard = require('./LessonLeaderboard');
// Group 3.2: Vocabulary System (NEW) // Group 3.2: Vocabulary System (NEW)
const Vocab = require('./Vocab'); const Vocab = require('./Vocab');
const VocabMapping = require('./VocabMapping');
const VocabForm = require('./VocabForm');
const VocabRelation = require('./VocabRelation');
// Group 3.3: Grammar System (NEW) // Group 3.3: Grammar System (NEW)
const Grammar = require('./Grammar'); const Grammar = require('./Grammar');
@@ -47,6 +44,10 @@ const GrammarMediaStory = require('./GrammarMediaStory');
// Group 3.4: Story System (NEW) // Group 3.4: Story System (NEW)
const Story = require('./Story'); const Story = require('./Story');
// Group 3.5: Context (NEW)
const Context = require('./Context');
const ContextGuide = require('./ContextGuide');
// Group 4: Attendance // Group 4: Attendance
const AttendanceLog = require('./AttendanceLog'); const AttendanceLog = require('./AttendanceLog');
const AttendanceDaily = require('./AttendanceDaily'); const AttendanceDaily = require('./AttendanceDaily');
@@ -164,18 +165,7 @@ const setupRelationships = () => {
Lesson.hasMany(LessonLeaderboard, { foreignKey: 'lesson_id', as: 'leaderboard' }); Lesson.hasMany(LessonLeaderboard, { foreignKey: 'lesson_id', as: 'leaderboard' });
// Vocabulary relationships (NEW) // Vocabulary relationships (NEW)
// Vocab -> VocabMapping (1:N) // No additional relationships needed
Vocab.hasMany(VocabMapping, { foreignKey: 'vocab_id', as: 'mappings' });
VocabMapping.belongsTo(Vocab, { foreignKey: 'vocab_id', as: 'vocab' });
// Vocab -> VocabForm (1:N)
Vocab.hasMany(VocabForm, { foreignKey: 'vocab_id', as: 'forms' });
VocabForm.belongsTo(Vocab, { foreignKey: 'vocab_id', as: 'vocab' });
// Vocab -> VocabRelation (1:N)
Vocab.hasMany(VocabRelation, { foreignKey: 'vocab_id', as: 'relations' });
VocabRelation.belongsTo(Vocab, { foreignKey: 'vocab_id', as: 'vocab' });
VocabRelation.belongsTo(Vocab, { foreignKey: 'related_vocab_id', as: 'relatedVocab' });
// Grammar relationships (NEW) // Grammar relationships (NEW)
// Grammar -> GrammarMapping (1:N) // Grammar -> GrammarMapping (1:N)
@@ -299,9 +289,6 @@ module.exports = {
// Group 3.2: Vocabulary System (NEW) // Group 3.2: Vocabulary System (NEW)
Vocab, Vocab,
VocabMapping,
VocabForm,
VocabRelation,
// Group 3.3: Grammar System (NEW) // Group 3.3: Grammar System (NEW)
Grammar, Grammar,
@@ -311,6 +298,10 @@ module.exports = {
// Group 3.4: Story System (NEW) // Group 3.4: Story System (NEW)
Story, Story,
// Group 3.5: Context (NEW)
Context,
ContextGuide,
// Group 4: Attendance // Group 4: Attendance
AttendanceLog, AttendanceLog,
AttendanceDaily, AttendanceDaily,

463
public/lesson-editor.html Normal file
View File

@@ -0,0 +1,463 @@
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Lesson Editor - SENA</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
color: #1f2937;
}
.container {
max-width: 1100px;
margin: 0 auto;
background: #fff;
border-radius: 16px;
box-shadow: 0 10px 40px rgba(0,0,0,0.2);
overflow: hidden;
}
.header {
padding: 24px 30px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: #fff;
}
.header h1 { font-size: 2rem; margin-bottom: 6px; }
.header p { opacity: 0.9; }
.content { padding: 24px 30px; }
.grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; }
.form-group { margin-bottom: 16px; }
label { display: block; margin-bottom: 6px; font-weight: 600; }
input, select, textarea {
width: 100%;
padding: 12px 14px;
border: 1px solid #e5e7eb;
border-radius: 10px;
font-size: 14px;
background: #fff;
transition: border-color 0.2s;
}
input:focus, select:focus, textarea:focus { outline: none; border-color: #667eea; }
textarea { min-height: 120px; resize: vertical; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace; }
.row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
.btn {
padding: 10px 16px;
border: none;
border-radius: 10px;
cursor: pointer;
font-weight: 600;
transition: transform 0.2s, box-shadow 0.2s;
}
.btn-primary { background: #4f46e5; color: #fff; }
.btn-primary:hover { transform: translateY(-1px); box-shadow: 0 6px 15px rgba(79,70,229,0.35); }
.btn-secondary { background: #6b7280; color: #fff; }
.btn-danger { background: #dc2626; color: #fff; }
.badge { display: inline-block; padding: 6px 10px; border-radius: 999px; font-size: 12px; }
.badge.ok { background: #dcfce7; color: #166534; }
.badge.err { background: #fee2e2; color: #991b1b; }
.section-title { margin: 18px 0 8px; font-weight: 700; color: #374151; }
.hint { color: #6b7280; font-size: 12px; margin-top: 6px; }
.status { margin-top: 10px; }
.full { grid-column: 1 / -1; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Lesson Editor</h1>
<p>Cập nhật nội dung Lesson qua API /api/lessons/:id</p>
</div>
<div class="content">
<div class="grid">
<div class="form-group">
<label for="baseUrl">API Base URL</label>
<input id="baseUrl" placeholder="http://localhost:3000" />
<div class="hint">Mặc định theo domain hiện tại</div>
</div>
<div class="form-group">
<label for="token">Bearer Token</label>
<input id="token" placeholder="Nhập token" />
</div>
<div class="form-group full">
<label for="subjectSelect">Chọn Subject</label>
<select id="subjectSelect"></select>
</div>
<div class="form-group">
<label for="chapterSelect">Chọn Chapter</label>
<select id="chapterSelect"></select>
</div>
<div class="form-group">
<label for="lessonSelect">Chọn Lesson</label>
<select id="lessonSelect"></select>
</div>
<div class="form-group">
<label for="lessonId">Lesson ID (UUID)</label>
<input id="lessonId" placeholder="e.g. 550e8400-e29b-41d4-a716-446655440000" />
</div>
<div class="form-group row">
<button class="btn btn-primary" id="loadBtn">Tải Lesson</button>
<button class="btn btn-secondary" id="clearBtn">Xóa Form</button>
<span class="badge" id="statusBadge" style="display:none"></span>
</div>
</div>
<div class="section-title">Thông tin cơ bản</div>
<div class="grid">
<div class="form-group">
<label for="chapterId">Chapter ID</label>
<input id="chapterId" />
</div>
<div class="form-group">
<label for="lessonNumber">Lesson Number</label>
<input id="lessonNumber" type="number" />
</div>
<div class="form-group">
<label for="lessonTitle">Lesson Title</label>
<input id="lessonTitle" />
</div>
<div class="form-group">
<label for="lessonType">Lesson Type</label>
<select id="lessonType">
<option value="json_content">json_content</option>
<option value="url_content">url_content</option>
</select>
</div>
<div class="form-group">
<label for="lessonContentType">Lesson Content Type</label>
<select id="lessonContentType">
<option value="">(none)</option>
<option value="vocabulary">vocabulary</option>
<option value="grammar">grammar</option>
<option value="phonics">phonics</option>
<option value="review">review</option>
<option value="mixed">mixed</option>
</select>
</div>
<div class="form-group">
<label for="displayOrder">Display Order</label>
<input id="displayOrder" type="number" />
</div>
<div class="form-group full">
<label for="lessonDescription">Lesson Description</label>
<textarea id="lessonDescription"></textarea>
</div>
</div>
<div class="section-title">Content JSON</div>
<div class="form-group">
<label for="contentJson">content_json (JSON)</label>
<textarea id="contentJson" placeholder='{"type":"vocabulary","vocabulary_ids":[]}'></textarea>
<div class="hint">Nếu rỗng thì không gửi content_json</div>
</div>
<div class="section-title">Content URL</div>
<div class="grid">
<div class="form-group full">
<label for="contentUrl">content_url</label>
<input id="contentUrl" />
</div>
<div class="form-group">
<label for="contentType">content_type</label>
<input id="contentType" placeholder="video, audio, pdf..." />
</div>
<div class="form-group">
<label for="thumbnailUrl">thumbnail_url</label>
<input id="thumbnailUrl" />
</div>
<div class="form-group">
<label for="durationMinutes">duration_minutes</label>
<input id="durationMinutes" type="number" />
</div>
</div>
<div class="section-title">Trạng thái</div>
<div class="grid">
<div class="form-group">
<label for="isPublished">is_published</label>
<select id="isPublished">
<option value="">(không đổi)</option>
<option value="true">true</option>
<option value="false">false</option>
</select>
</div>
<div class="form-group">
<label for="isFree">is_free</label>
<select id="isFree">
<option value="">(không đổi)</option>
<option value="true">true</option>
<option value="false">false</option>
</select>
</div>
</div>
<div class="row">
<button class="btn btn-primary" id="saveBtn">Cập nhật Lesson</button>
<button class="btn btn-danger" id="deleteBtn">Xóa Lesson</button>
</div>
<div class="status" id="status"></div>
</div>
</div>
<script>
const $ = (id) => document.getElementById(id);
const baseUrlInput = $('baseUrl');
const tokenInput = $('token');
baseUrlInput.value = localStorage.getItem('lessonEditorBaseUrl') || window.location.origin;
tokenInput.value = localStorage.getItem('lessonEditorToken') || '';
const setStatus = (ok, message) => {
const badge = $('statusBadge');
const status = $('status');
badge.style.display = 'inline-block';
badge.className = `badge ${ok ? 'ok' : 'err'}`;
badge.textContent = ok ? 'OK' : 'ERROR';
status.textContent = message || '';
};
const setSelectOptions = (selectEl, items, placeholder) => {
selectEl.innerHTML = '';
const ph = document.createElement('option');
ph.value = '';
ph.textContent = placeholder;
selectEl.appendChild(ph);
items.forEach((item) => {
const opt = document.createElement('option');
opt.value = item.value;
opt.textContent = item.label;
selectEl.appendChild(opt);
});
};
const fetchJson = async (url) => {
const res = await fetch(url, { headers: getHeaders() });
const data = await res.json();
if (!res.ok || !data.success) {
throw new Error(data.message || 'Request failed');
}
return data.data;
};
const loadSubjects = async () => {
const data = await fetchJson(`${getBaseUrl()}/api/subjects?limit=2000`);
const subjects = data.subjects || [];
setSelectOptions(
$('subjectSelect'),
subjects.map((s) => ({
value: s.id,
label: `${s.subject_code || ''} ${s.subject_name || ''}`.trim()
})),
'Chọn subject'
);
};
const loadChaptersBySubject = async (subjectId) => {
if (!subjectId) {
setSelectOptions($('chapterSelect'), [], 'Chọn chapter');
setSelectOptions($('lessonSelect'), [], 'Chọn lesson');
return;
}
const data = await fetchJson(`${getBaseUrl()}/api/subjects/${subjectId}/chapters?limit=2000`);
const chapters = data.chapters || [];
setSelectOptions(
$('chapterSelect'),
chapters.map((c) => ({
value: c.id,
label: `Ch${c.chapter_number || ''} - ${c.chapter_title || ''}`.trim()
})),
'Chọn chapter'
);
setSelectOptions($('lessonSelect'), [], 'Chọn lesson');
};
const loadLessonsByChapter = async (chapterId) => {
if (!chapterId) {
setSelectOptions($('lessonSelect'), [], 'Chọn lesson');
return;
}
const data = await fetchJson(`${getBaseUrl()}/api/chapters/${chapterId}/lessons?limit=2000`);
const lessons = data.lessons || [];
setSelectOptions(
$('lessonSelect'),
lessons.map((l) => ({
value: l.id,
label: `L${l.lesson_number || ''} - ${l.lesson_title || ''}`.trim()
})),
'Chọn lesson'
);
};
const getHeaders = () => {
const token = tokenInput.value.trim();
const headers = { 'Content-Type': 'application/json' };
if (token) headers.Authorization = `Bearer ${token}`;
return headers;
};
const getBaseUrl = () => baseUrlInput.value.trim().replace(/\/$/, '');
const loadLessonById = async () => {
try {
const id = $('lessonId').value.trim();
if (!id) return setStatus(false, 'Vui lòng nhập Lesson ID');
localStorage.setItem('lessonEditorBaseUrl', getBaseUrl());
localStorage.setItem('lessonEditorToken', tokenInput.value.trim());
const res = await fetch(`${getBaseUrl()}/api/lessons/${id}`, {
headers: getHeaders()
});
const data = await res.json();
if (!res.ok || !data.success) {
return setStatus(false, data.message || 'Không tải được lesson');
}
const lesson = data.data;
$('chapterId').value = lesson.chapter_id || '';
$('lessonNumber').value = lesson.lesson_number ?? '';
$('lessonTitle').value = lesson.lesson_title || '';
$('lessonType').value = lesson.lesson_type || 'json_content';
$('lessonDescription').value = lesson.lesson_description || '';
$('lessonContentType').value = lesson.lesson_content_type || '';
$('displayOrder').value = lesson.display_order ?? '';
$('contentUrl').value = lesson.content_url || '';
$('contentType').value = lesson.content_type || '';
$('thumbnailUrl').value = lesson.thumbnail_url || '';
$('durationMinutes').value = lesson.duration_minutes ?? '';
$('isPublished').value = lesson.is_published === true ? 'true' : lesson.is_published === false ? 'false' : '';
$('isFree').value = lesson.is_free === true ? 'true' : lesson.is_free === false ? 'false' : '';
$('contentJson').value = lesson.content_json ? JSON.stringify(lesson.content_json, null, 2) : '';
setStatus(true, 'Đã tải lesson');
} catch (err) {
setStatus(false, err.message || 'Lỗi không xác định');
}
};
$('loadBtn').addEventListener('click', loadLessonById);
$('subjectSelect').addEventListener('change', async (e) => {
try {
await loadChaptersBySubject(e.target.value);
} catch (err) {
setStatus(false, err.message || 'Không tải được chapter');
}
});
$('chapterSelect').addEventListener('change', async (e) => {
try {
await loadLessonsByChapter(e.target.value);
} catch (err) {
setStatus(false, err.message || 'Không tải được lesson');
}
});
$('lessonSelect').addEventListener('change', async (e) => {
if (!e.target.value) return;
$('lessonId').value = e.target.value;
await loadLessonById();
});
$('saveBtn').addEventListener('click', async () => {
try {
const id = $('lessonId').value.trim();
if (!id) return setStatus(false, 'Vui lòng nhập Lesson ID');
localStorage.setItem('lessonEditorBaseUrl', getBaseUrl());
localStorage.setItem('lessonEditorToken', tokenInput.value.trim());
const payload = {
chapter_id: $('chapterId').value.trim() || undefined,
lesson_number: $('lessonNumber').value ? parseInt($('lessonNumber').value, 10) : undefined,
lesson_title: $('lessonTitle').value.trim() || undefined,
lesson_type: $('lessonType').value || undefined,
lesson_description: $('lessonDescription').value.trim() || undefined,
lesson_content_type: $('lessonContentType').value || undefined,
display_order: $('displayOrder').value ? parseInt($('displayOrder').value, 10) : undefined,
content_url: $('contentUrl').value.trim() || undefined,
content_type: $('contentType').value.trim() || undefined,
thumbnail_url: $('thumbnailUrl').value.trim() || undefined,
duration_minutes: $('durationMinutes').value ? parseInt($('durationMinutes').value, 10) : undefined
};
const contentJsonText = $('contentJson').value.trim();
if (contentJsonText) {
try {
payload.content_json = JSON.parse(contentJsonText);
} catch (e) {
return setStatus(false, 'content_json không hợp lệ (JSON)');
}
}
const isPublished = $('isPublished').value;
if (isPublished !== '') payload.is_published = isPublished === 'true';
const isFree = $('isFree').value;
if (isFree !== '') payload.is_free = isFree === 'true';
Object.keys(payload).forEach((k) => payload[k] === undefined && delete payload[k]);
const res = await fetch(`${getBaseUrl()}/api/lessons/${id}`, {
method: 'PUT',
headers: getHeaders(),
body: JSON.stringify(payload)
});
const data = await res.json();
if (!res.ok || !data.success) {
return setStatus(false, data.message || 'Cập nhật thất bại');
}
setStatus(true, 'Cập nhật thành công');
} catch (err) {
setStatus(false, err.message || 'Lỗi không xác định');
}
});
$('deleteBtn').addEventListener('click', async () => {
try {
const id = $('lessonId').value.trim();
if (!id) return setStatus(false, 'Vui lòng nhập Lesson ID');
if (!confirm('Bạn chắc chắn muốn xóa lesson này?')) return;
const res = await fetch(`${getBaseUrl()}/api/lessons/${id}`, {
method: 'DELETE',
headers: getHeaders()
});
const data = await res.json();
if (!res.ok || !data.success) {
return setStatus(false, data.message || 'Xóa thất bại');
}
setStatus(true, 'Đã xóa lesson');
} catch (err) {
setStatus(false, err.message || 'Lỗi không xác định');
}
});
$('clearBtn').addEventListener('click', () => {
['chapterId','lessonNumber','lessonTitle','lessonType','lessonDescription','lessonContentType','displayOrder','contentJson','contentUrl','contentType','thumbnailUrl','durationMinutes','isPublished','isFree'].forEach((id) => {
const el = $(id);
if (!el) return;
if (el.tagName === 'SELECT') el.value = '';
else el.value = '';
});
setStatus(true, 'Đã xóa form');
});
(async () => {
try {
await loadSubjects();
} catch (err) {
setStatus(false, err.message || 'Không tải được subject');
}
})();
</script>
</body>
</html>

View File

@@ -0,0 +1,25 @@
const express = require('express');
const router = express.Router();
const contextGuideController = require('../controllers/contextGuideController');
const { authenticateToken } = require('../middleware/auth');
/**
* ContextGuide Routes
*/
// Get all context guides
router.get('/', authenticateToken, contextGuideController.getAllContextGuides);
// Get context guide by UUID
router.get('/:id', authenticateToken, contextGuideController.getContextGuideById);
// Create context guide
router.post('/', authenticateToken, contextGuideController.createContextGuide);
// Update context guide
router.put('/:id', authenticateToken, contextGuideController.updateContextGuide);
// Delete context guide
router.delete('/:id', authenticateToken, contextGuideController.deleteContextGuide);
module.exports = router;

25
routes/contextRoutes.js Normal file
View File

@@ -0,0 +1,25 @@
const express = require('express');
const router = express.Router();
const contextController = require('../controllers/contextController');
const { authenticateToken } = require('../middleware/auth');
/**
* Context Routes
*/
// Get all contexts
router.get('/', authenticateToken, contextController.getAllContexts);
// Get context by UUID
router.get('/:id', authenticateToken, contextController.getContextById);
// Create context
router.post('/', authenticateToken, contextController.createContext);
// Update context
router.put('/:id', authenticateToken, contextController.updateContext);
// Delete context
router.delete('/:id', authenticateToken, contextController.deleteContext);
module.exports = router;