38 lines
1.5 KiB
SQL
38 lines
1.5 KiB
SQL
WITH latest_names AS (
|
|
SELECT DISTINCT ON (conversation_id)
|
|
conversation_id,
|
|
NULLIF(BTRIM(additional_attributes->>'senderName'), '') AS visitor_name
|
|
FROM messages
|
|
WHERE message_type = 'incoming'
|
|
AND NULLIF(BTRIM(additional_attributes->>'senderName'), '') IS NOT NULL
|
|
AND BTRIM(additional_attributes->>'senderName') <> '商务通访客'
|
|
ORDER BY conversation_id, created_at DESC, id DESC
|
|
)
|
|
UPDATE contacts
|
|
SET
|
|
name = latest_names.visitor_name,
|
|
updated_at = CURRENT_TIMESTAMP
|
|
FROM conversations
|
|
JOIN latest_names ON latest_names.conversation_id = conversations.id
|
|
JOIN inboxes ON inboxes.id = conversations.inbox_id
|
|
WHERE contacts.id = conversations.contact_id
|
|
AND inboxes.channel_type = 'shangwutong'
|
|
AND contacts.name <> latest_names.visitor_name;
|
|
|
|
-- Existing imported messages used a hard-coded senderName. Contact identity is
|
|
-- the authoritative sender for incoming messages after this repair.
|
|
UPDATE messages
|
|
SET additional_attributes = jsonb_set(
|
|
COALESCE(messages.additional_attributes, '{}'::jsonb),
|
|
'{senderName}',
|
|
to_jsonb(contacts.name)
|
|
)
|
|
FROM conversations
|
|
JOIN contacts ON contacts.id = conversations.contact_id
|
|
JOIN inboxes ON inboxes.id = conversations.inbox_id
|
|
WHERE messages.conversation_id = conversations.id
|
|
AND messages.message_type = 'incoming'
|
|
AND inboxes.channel_type = 'shangwutong'
|
|
AND BTRIM(contacts.name) <> ''
|
|
AND COALESCE(messages.additional_attributes->>'senderName', '') <> contacts.name;
|