You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Global-sales/src/lib/msgUtils.js

205 lines
7.2 KiB
JavaScript

import { cloneDeep } from "@/utils/utils";
import { v4 as uuid } from "uuid";
export const replaceTemplateString = (str, replacements) => {
let result = str;
let keys = str.match(/{{(.*?)}}/g).map(key => key.replace(/{{|}}/g, ''));
for (let i = 0; i < keys.length; i++) {
let replaceValue = replacements[i];
let template = new RegExp(`{{${keys[i]}}}`, 'g');
result = result.replace(template, replaceValue);
}
return result;
}
/**
*
// +8618777396951 lyj
{
"to": "+8613317835586", // qqs
"msgtype": "text",
"msgcontent": "{\"body\":\"txtmsgtest\"}"
}
*/
export const sentMsgTypeMapped = {
text: {
type: 'text',
contentToSend: (msg) => ({ action: 'message', actionId: msg.id, renderId: msg.id, to: msg.to, msgtype: 'text', msgcontent: { body: msg.text } }),
contentToRender: (msg) => ({ ...msg }),
},
whatsappTemplate: {
contentToSend: (msg) => ({ action: 'message', actionId: msg.id, renderId: msg.id, to: msg.to, msgtype: 'template', msgcontent: msg.template }),
contentToRender: (msg) => {
console.log(msg);
const templateDataMapped = msg.template?.components ? msg.template.components.reduce((r, v) => ({...r, [v.type]: v}), {}) : null;
const templateParam = (templateDataMapped?.body?.parameters || []).map(e => e.text);
const fillTemplate = templateParam.length ? replaceTemplateString(msg.template_origin.components.body?.[0]?.text || '', templateParam) : (msg.template_origin.components.body?.[0]?.text || '');
// const footer = msg.template_origin.components?.footer?.[0]?.text || '';
return {
...msg,
type: 'text',
title: msg.template_origin.components.header?.[0]?.text || '',
text: `${fillTemplate}`, // msg.template_origin.components.body?.[0]?.text || '',
};
},
},
};
const whatsappMsgMapped = {
'whatsapp.inbound_message.received': {
getMsg: (result) => {
console.log('whatsapp.inbound_message.received', result);
return result?.whatsappInboundMessage || null;
},
contentToRender: (result) => {
console.log('whatsapp.inbound_message.received to render', result);
const contentObj = result?.whatsappInboundMessage || result; // debug:
return parseRenderMessageItem(contentObj);
},
contentToUpdate: () => null,
},
'whatsapp.message.updated': {
getMsg: (result) => {
console.log('getMsg', result);
return result?.whatsappMessage || null;
},
contentToRender: (msgcontent) => {
return null; // * 仅更新消息状态, 没有输出
// let contentObj = msgcontent?.whatsappMessage || msgcontent; // debug:
// if ((contentObj?.status === 'failed' )) {
// contentObj = {
// type: 'error',
// text: {body: '❌ Message failed to send' }, // contentObj.errorMessage
// id: contentObj.id,
// wamid: contentObj.id,
// };
// return contentObj;
// }
// return null;
// console.log('whatsapp.message.updated to render', contentObj);
// const _r = parseRenderMessageItem(contentObj);
// console.log('_r', _r);
// return parseRenderMessageItem(contentObj);
},
contentToUpdate: (msgcontent) => ({ ...msgcontent, id: msgcontent.id, status: msgcontent.status }),
},
};
export const receivedMsgTypeMapped = {
...cloneDeep(whatsappMsgMapped),
'message': {
// 发送消息的同步记录 status: 'accepted'
getMsg: (result) => ({ ...result, conversationId: result.actionId.split('.')[0] }),
contentToRender: () => null,
contentToUpdate: (msgcontent) => ({
...msgcontent,
id: msgcontent.actionId,
status: ['delivered', 'accepted', 'sent'].includes(msgcontent?.status || '' ? 'sent' : 'failed'),
conversationId: msgcontent.conversation.id,
}),
},
'error': {
getMsg: (result) => result,
contentToRender: () => null,
contentToUpdate: (msgcontent) => ({ ...msgcontent, id: msgcontent.actionId, status: msgcontent?.status || 'failed', dateString: '发送失败 ❌' }),
},
};
export const whatsappMsgTypeMapped = {
error: {
type: (_m) => ({ type: 'system' }),
data: (msg) => ({ id: msg.wamid, text: msg.errorCode ? msg.errorMessage : msg.text.body }),
},
text: {
type: (msg) => ({ type: msg.errorCode ? 'system' : 'text' }),
data: (msg) => ({ id: msg.wamid, text: msg.errorCode ? msg.errorMessage : msg.text.body }),
},
image: {
type: 'photo',
data: (msg) => ({
data: { id: msg.wamid, uri: msg.image.link, width: 200, height: 200, alt: '' },
onOpen: () => {
console.log('Open image', msg.image.link);
},
}),
},
sticker: {
type: 'photo',
data: (msg) => ({
data: { id: msg.wamid, uri: msg.sticker.link, width: 150, height: 120, alt: '' },
}),
},
video: {
type: 'video',
data: (msg) => ({
data: {
id: msg.wamid,
videoURL: msg.video.link,
status: {
click: true,
loading: 0,
download: true,
},
},
}),
},
audio: {
type: 'audio',
data: (msg) => ({
id: msg.wamid,
data: {
audioURL: msg.audio.link,
},
}),
},
unsupported: { type: 'system', data: (msg) => ({ text: 'Message type is currently not supported.' }) },
reaction: {
type: 'text',
data: (msg) => ({ id: msg.wamid, text: msg.reaction?.emoji || msg.reaction?.text?.body || 'Reaction', reply: { message: '{content}', title: 'React from' } }),
},
document: {
type: 'file',
data: (msg) => ({ id: msg.wamid, text: msg.document.filename, data: { uri: msg.document.link, extension: 'PDF', status: { click: false, loading: 0, } } }),
},
// location: 'location',
// contact: 'contact',
// 'contact-card': 'contact-card',
// 'contact-card-with-photo': 'contact-card-with-photo',
// 'contact-card-with-photo-and-label': 'contact-card-with-photo-and-label',
};
/**
* render received msg
*/
export const parseRenderMessageItem = (msg) => {
console.log('parseRenderMessageItem', msg);
return {
date: msg?.sendTime || '',
...(whatsappMsgTypeMapped?.[msg.type]?.data(msg) || {}),
...(typeof whatsappMsgTypeMapped[msg.type].type === 'function' ? whatsappMsgTypeMapped[msg.type].type(msg) : { type: whatsappMsgTypeMapped[msg.type].type || 'text' }),
// type: whatsappMsgTypeMapped?.[msg.type]?.type || 'text',
sender: msg.from,
status: msg?.status || 'waiting',
// title: msg.customerProfile.name,
// replyButton: true,
};
};
export const parseRenderMessageList = (messages) => {
return messages.map((msg) => {
return {
...(whatsappMsgTypeMapped?.[msg.type]?.data(msg) || {}),
...(whatsappMsgTypeMapped?.[msg.type]?.type(msg) || { type: 'text' }), // type: whatsappMsgTypeMapped?.[msg.type]?.type || 'text',
id: msg.id,
sender: msg.from,
// title: msg.customerProfile.name,
date: msg.sendTime,
};
});
};
/**
* WhatsApp Templates params
*/
export const whatsappTemplatesParamMapped = {
'say_hello': [['customer_name']],
'asia_highlights_has_receive_your_inquiry': [['agent_name']],
};