diff --git a/server/src/index.js b/server/src/index.js index 06862ac..461c89f 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -3506,6 +3506,51 @@ async function mergeLegacyWhatsAppConversations(tenantId, channel, jid, aliasJid return imported } +async function migrateDeviceQualifiedWhatsAppConversations() { + const { rows } = await pool.query( + `SELECT tenant_id, data + FROM resources + WHERE kind='conversations' + AND data->>'channel'='whatsapp' + AND data->>'whatsappJid' LIKE '%:%@s.whatsapp.net'`, + ) + let migrated = 0 + for (const row of rows) { + const tenantId = String(row.tenant_id) + const source = row.data + const rawJid = String(source.whatsappJid || '') + const jid = canonicalWhatsAppJid(rawJid) + if (!jid || jid === rawJid) continue + const channel = await getResource(tenantId, 'channels', source.channelId) + if (!channel || channel.type !== 'whatsapp') continue + const targetId = `${channel.id}:${jid}` + if (await getResource(tenantId, 'conversation-tombstones', targetId)) continue + let target = await getResource(tenantId, 'conversations', targetId) + if (!target) { + target = await putResource(tenantId, 'conversations', { + ...source, + id: targetId, + whatsappJid: jid, + whatsappJidAliases: Array.from(new Set([ + ...(source.whatsappJidAliases || []), + rawJid, + jid, + ])), + }) + } + const imported = await mergeLegacyWhatsAppConversations(tenantId, channel, jid, [rawJid]) + migrated += imported + 1 + const updated = await getResource(tenantId, 'conversations', target.id) + if (updated) broadcast(tenantId, { + type: 'conversation.updated', + conversationId: updated.id, + conversation: updated, + }) + } + if (migrated) console.log(`已迁移 ${migrated} 个 WhatsApp 设备 JID 会话或消息`) + return migrated +} + async function performWhatsAppTenantSync(tenantId, channel, options = {}) { const state = await whatsappRequest(`/accounts/${channel.gatewayAccountId}/auth/state`) if (state.status !== 'connected' || !['open', 'ready'].includes(state.connectionState)) { @@ -5392,6 +5437,14 @@ for (const row of existingWhatsAppChannels.rows) { }) }) } +setTimeout(() => { + void migrateDeviceQualifiedWhatsAppConversations().catch((error) => { + console.error(JSON.stringify({ + message: 'WhatsApp 设备 JID 历史迁移失败', + error: error.message, + })) + }) +}, 2_000).unref?.() async function reconcileFailedChannelWebhooks() { const { rows } = await pool.query(