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 toHomeDisplayItem(ws) { return { id: ws._id, title: ws.title || '', subtitle: ws.subtitle || '', category: ws.category || '', ageBand: ageBand(ws.ageMin || 0, ws.ageMax || 0), difficulty: DIFFICULTY_LABELS[ws.difficulty] || '基础', icon: '', img: ws.previewImg || '', badge: ws.isNew ? 'NEW' : ws.isHot ? 'HOT' : '', path: ws.path || '', available: true, }; } async function readCurrentConfig() { const db = cloud.database(); try { const { data } = await db .collection('page_configs') .doc('current') .get(); return data; } catch { return { home: null, category: null, age: null, version: 0 }; } } async function saveConfig(config) { const db = cloud.database(); const toSave = { ...config }; delete toSave._id; try { await db.collection('page_configs').doc('current').get(); await db.collection('page_configs').doc('current').update({ data: toSave, }); } catch { await db.collection('page_configs').doc('current').set({ data: toSave, }); } const buffer = Buffer.from(JSON.stringify(config), 'utf-8'); await cloud.uploadFile({ cloudPath: CONFIG_PATH, fileContent: buffer, }); } async function isEnabled(db) { try { const { data } = await db .collection('settings') .doc('homeAutoRefresh') .get(); return data.enabled !== false; } catch { // Document doesn't exist yet — default to enabled return true; } } exports.main = async () => { try { const db = cloud.database(); // Check if timer is enabled if (!(await isEnabled(db))) { return { success: true, message: '定时任务已暂停,跳过执行' }; } // Query top 5 by downloads const { data: topDownloads } = await db .collection('worksheets') .where({ status: 'active' }) .orderBy('downloads', 'desc') .limit(5) .get(); // Query top 5 by likes const { data: topLikes } = await db .collection('worksheets') .where({ status: 'active' }) .orderBy('likes', 'desc') .limit(5) .get(); const featured = topDownloads.map(toHomeDisplayItem); const hot = topLikes.map(toHomeDisplayItem); // Read current config, only update featured & hot const config = await readCurrentConfig(); if (!config.home) { config.home = {}; } config.home.featured = featured; config.home.hot = hot; config.version = (config.version || 0) + 1; config.updatedAt = new Date().toISOString(); await saveConfig(config); return { success: true, data: { version: config.version, featured: featured.length, hot: hot.length, }, }; } catch (error) { return { success: false, message: error instanceof Error ? error.message : '自动刷新首页推荐失败', }; } };