import type { Request, Response } from 'express'; import { AppError } from '../../../../shared/errors/app-error.js'; import { sendSuccess } from '../../../../shared/http/response.js'; import { checkParseDatabase } from '../../../../shared/db/parse-health.service.js'; import { reconcileGroupCatalog } from '../services/sync.service.js'; import { backfillGroupChatsFromMessages } from '../services/groups.service.js'; import { getQiWeConfig } from '../services/qiwe-api.service.js'; export async function handleSyncGroups(_req: Request, res: Response): Promise { const config = getQiWeConfig(); if (!config.token || !config.guid) { throw new AppError(500, 'MISSING_CONFIG', '请在 .env 中配置 QIWE_TOKEN 和 QIWE_GUID'); } const dbBefore = await checkParseDatabase(); if (!dbBefore.connected) { throw new AppError(503, 'DB_UNAVAILABLE', dbBefore.error || '无法连接 Parse 数据库', { database: dbBefore }); } const catalog = await reconcileGroupCatalog(); const dbAfter = await checkParseDatabase(); sendSuccess(res, { catalog, sync: catalog.rooms, database: dbAfter }); if (catalog.rooms.errors.length > 0) { console.warn(`[Sync] 部分群写入失败: ${catalog.rooms.errors.length} 条`); } } /** 按 Message 表中的 roomId 补全 GroupChat,不调用企微接口 */ export async function handleBackfillGroupsFromMessages(_req: Request, res: Response): Promise { const config = getQiWeConfig(); if (!config.guid) { throw new AppError(500, 'MISSING_CONFIG', '请在 .env 中配置 QIWE_GUID'); } const created = await backfillGroupChatsFromMessages(config.guid); sendSuccess(res, { created }); }