feat:开发分类页内容管理

This commit is contained in:
R524809
2026-04-29 18:17:48 +08:00
parent 2cb9ec55d6
commit fa39938e5a
12 changed files with 853 additions and 0 deletions
+131
View File
@@ -0,0 +1,131 @@
const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const CONFIG_PATH = 'content/page-config.json';
const DIFFICULTY_LABELS = {
1: '入门',
2: '基础',
3: '进阶',
4: '挑战',
};
function ageBand(min, max) {
return `${min}-${max}`;
}
function toDisplayItem(ws) {
return {
id: ws._id,
title: ws.title || '',
subtitle: ws.subtitle || '',
previewImg: ws.previewImg || '',
ageBand: ageBand(ws.ageMin || 0, ws.ageMax || 0),
ageMin: ws.ageMin || 0,
ageMax: ws.ageMax || 0,
difficulty: ws.difficulty || 2,
difficultyLabel: DIFFICULTY_LABELS[ws.difficulty] || '基础',
path: ws.path || '',
available: true,
likes: ws.likes || 0,
downloads: ws.downloads || 0,
date: ws.updatedAt
? new Date(ws.updatedAt).toISOString().slice(0, 10)
: new Date().toISOString().slice(0, 10),
};
}
async function readCurrentConfig() {
try {
const res = await cloud.downloadFile({ fileID: CONFIG_PATH });
return JSON.parse(res.fileContent.toString('utf-8'));
} catch {
return { home: null, category: null, age: null, version: 0 };
}
}
async function buildCategoryData(db) {
// Get all categories
const { data: categories } = await db
.collection('categories')
.orderBy('sortOrder', 'asc')
.get();
// Get all active worksheets
const { data: worksheets } = await db
.collection('worksheets')
.where({ status: 'active' })
.orderBy('sortOrder', 'asc')
.orderBy('updatedAt', 'desc')
.limit(100)
.get();
// Group by category
const grouped = {};
for (const ws of worksheets) {
const cat = ws.category || 'unknown';
if (!grouped[cat]) grouped[cat] = [];
grouped[cat].push(toDisplayItem(ws));
}
const categoryData = {
searchPlaceholder: '搜索练习纸...',
categories: categories.map((cat) => ({
id: cat._id,
name: cat.name || '',
icon: cat.icon || '',
items: grouped[cat._id] || [],
})),
};
const stats = {};
for (const cat of categoryData.categories) {
stats[cat.id] = cat.items.length;
}
return { categoryData, stats };
}
exports.main = async (event) => {
try {
const db = cloud.database();
const page = String(event.page || '').trim();
if (page !== 'category') {
throw new Error('当前仅支持 page=category');
}
const { categoryData, stats } = await buildCategoryData(db);
// Read current config, merge, bump version
const config = await readCurrentConfig();
config.category = categoryData;
config.version = (config.version || 0) + 1;
config.updatedAt = new Date().toISOString();
// Upload to cloud storage
const buffer = Buffer.from(JSON.stringify(config), 'utf-8');
await cloud.uploadFile({
cloudPath: CONFIG_PATH,
fileContent: buffer,
});
return {
success: true,
data: {
version: config.version,
updatedAt: config.updatedAt,
stats,
},
};
} catch (error) {
return {
success: false,
message:
error instanceof Error
? error.message
: '生成分类页数据失败',
};
}
};