import Parse from '../db/parse-client.js'; export interface AggregateCountsResult { memberCountByRoom: Map; todayMsgCountByRoom: Map; totalMsgCountByRoom: Map; groupCountByCommunity: Map; } /** 按 roomId 字段分组计数 */ function countByRoomId(rows: any[], roomIdField = 'roomId'): Map { const map = new Map(); for (const r of rows) { const rid = typeof r.get === 'function' ? (r.get(roomIdField) as string) : (r[roomIdField] as string); if (rid) map.set(rid, (map.get(rid) || 0) + 1); } return map; } export async function fetchAggregateCounts(): Promise { const todayStart = new Date(); todayStart.setHours(0, 0, 0, 0); const [memberCounts, todayMsgCounts, totalMsgCounts, groupCounts] = await Promise.all([ // 1. 活跃成员数 — select 只取 roomId (async () => { const q = new Parse.Query('GroupMember'); q.equalTo('status', 'active'); q.select('roomId'); q.limit(100000); const rows = await q.find({ useMasterKey: true }); return countByRoomId(rows); })(), // 2. 今日消息数 — select 只取 roomId (async () => { const q = new Parse.Query('Message'); q.containedIn('msgType', [0, 2]); q.notEqualTo('content', ''); q.greaterThanOrEqualTo('timestamp', todayStart); q.select('roomId'); q.limit(100000); const rows = await q.find({ useMasterKey: true }); return countByRoomId(rows); })(), // 3. 总消息数 — select 只取 roomId (async () => { const q = new Parse.Query('Message'); q.select('roomId'); q.limit(200000); const rows = await q.find({ useMasterKey: true }); return countByRoomId(rows); })(), // 4. 群数按小区 — select 只取 community 指针 (async () => { const q = new Parse.Query('GroupChat'); q.select('community'); q.limit(5000); const rows = await q.find({ useMasterKey: true }); const map = new Map(); for (const r of rows) { const community = r.get('community'); const cid = community?.id || '_null'; map.set(cid, (map.get(cid) || 0) + 1); } return map; })(), ]); return { memberCountByRoom: memberCounts, todayMsgCountByRoom: todayMsgCounts, totalMsgCountByRoom: totalMsgCounts, groupCountByCommunity: groupCounts, }; }