const cloud = require('wx-server-sdk'); cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }); const VALID_STATUS = new Set(['draft', 'active', 'hidden']); const STATUS_ORDER = { draft: 0, hidden: 1, active: 2 }; function mergeSeedStats(items) { for (const item of items) { item.likes = (item.likes || 0) + (item.likes_seed || 0); item.downloads = (item.downloads || 0) + (item.downloads_seed || 0); } } exports.main = async (event) => { try { const db = cloud.database(); const collection = db.collection('worksheets'); const category = String(event.category || '').trim(); const status = String(event.status || '').trim(); const rawStats = event.rawStats === true; // Build query condition const where = {}; if (category) where.category = category; if (status && VALID_STATUS.has(status)) where.status = status; // Query worksheets (cloud DB limit is 100 per call) const { data } = await collection .where(where) .orderBy('sortOrder', 'asc') .orderBy('updatedAt', 'desc') .limit(100) .get(); // Sort by status order: draft → hidden → active data.sort((a, b) => { const orderA = STATUS_ORDER[a.status] ?? 99; const orderB = STATUS_ORDER[b.status] ?? 99; return orderA - orderB; }); // Compute stats for the category (all statuses) let allData = data; if (status) { // If filtered by status, need a separate query for stats const statsWhere = {}; if (category) statsWhere.category = category; const { data: allItems } = await collection .where(statsWhere) .limit(100) .get(); allData = allItems; } const stats = { total: 0, draft: 0, active: 0, hidden: 0 }; for (const item of allData) { stats.total++; if (item.status === 'draft') stats.draft++; else if (item.status === 'active') stats.active++; else if (item.status === 'hidden') stats.hidden++; } if (!rawStats) { mergeSeedStats(data); } return { success: true, data, stats, }; } catch (error) { return { success: false, message: error instanceof Error ? error.message : '查询 worksheet 失败', }; } };