更新消息送达状态

dev/chat
Lei OT 1 year ago
parent 74966d2730
commit 6c6989accd

@ -1,3 +1,4 @@
import { cloneDeep } from "@/utils/utils";
import { v4 as uuid } from "uuid";
export const replaceTemplateString = (str, replacements) => {
@ -24,11 +25,11 @@ export const replaceTemplateString = (str, replacements) => {
export const sentMsgTypeMapped = {
text: {
type: 'text',
contentToSend: (msg) => ({ action: 'message', actionId: uuid(), renderId: msg.id, to: msg.to, msgtype: 'text', msgcontent: { body: msg.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: uuid(), renderId: msg.id, to: msg.to, msgtype: 'template', msgcontent: msg.template }),
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;
@ -44,7 +45,7 @@ export const sentMsgTypeMapped = {
},
},
};
export const whatsappMsgMapped = {
const whatsappMsgMapped = {
'whatsapp.inbound_message.received': {
getMsg: (result) => {
console.log('whatsapp.inbound_message.received', result);
@ -62,27 +63,38 @@ export const whatsappMsgMapped = {
return result?.whatsappMessage || null;
},
contentToRender: (msgcontent) => {
return null; // todo: 仅更新消息状态, 没有输出
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);
// 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 }),
},
'message': {
getMsg: (result) => {
return result;
},
contentToRender: (msgcontent) => {
return null; // todo: 仅更新消息状态, 没有输出
},
contentToUpdate: (msgcontent) => ({ ...msgcontent, id: msgcontent.actionId, status: msgcontent?.status || ('failed'), dateString: '发送失败 ❌' }),
},
};
// whatsappMsgMapped.message = cloneDeep(whatsappMsgMapped['whatsapp.message.updated']);
export const receivedMsgTypeMapped = whatsappMsgMapped;
export const whatsappMsgTypeMapped = {
error: {
type: (_m) => ({ type: 'system' }),
@ -158,7 +170,7 @@ export const 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' }),
...(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',

@ -1,23 +1,20 @@
import { webSocket } from 'rxjs/webSocket';
import { filter, buffer, map, tap, retryWhen, delay, take } from 'rxjs/operators';
import { of, timer, concatMap } from 'rxjs';
import { filter, buffer, map, tap, retryWhen, retry, delay, take, } from 'rxjs/operators';
import { v4 as uuid } from "uuid";
export class RealTimeAPI {
constructor(param) {
this.webSocket = webSocket(param)
// .pipe(
// retryWhen(errors =>
// errors.pipe(
// tap(val => console.error(`WebSocket connection failed with error: ${val}`)),
// delay(5000), // retry after 5 seconds
// take(5)
// )
// )
// );
this.webSocket = webSocket(param);
}
getObservable() {
return this.webSocket;
return this.webSocket.pipe(
retry({
count: 10,
delay: () => timer(1000)
})
);
}
disconnect() {

@ -1,6 +1,6 @@
import React, { createContext, useContext, useState, useEffect, useRef } from 'react';
import { RealTimeAPI } from '@/lib/realTimeAPI';
import { whatsappMsgMapped, sentMsgTypeMapped } from '@/lib/msgUtils';
import { receivedMsgTypeMapped, sentMsgTypeMapped } from '@/lib/msgUtils';
import { groupBy, isEmpty } from '@/utils/utils';
export const ConversationContext = createContext();
@ -21,6 +21,7 @@ export async function fetchJSON(url, data) {
const API_HOST = 'http://202.103.68.144:8888';
export const useConversations = ({loginUser, realtimeAPI}) => {
const { userId } = loginUser;
const [errors, setErrors] = useState([]);
const [messages, setMessages] = useState([]); // active conversation
@ -89,29 +90,29 @@ export const useConversations = ({loginUser, realtimeAPI}) => {
};
const [customerOrderProfile, setCustomerProfile] = useState({});
const getCustomerProfile = async (customerId) => {
console.log(customerId, 'getCustomerProfile');
const data = await fetchJSON(`http://127.0.0.1:4523/m2/3888351-0-default/144062941`);
setCustomerProfile(data);
const getCustomerProfile = async (colisn) => {
const data = await fetchJSON(`${API_HOST}/getorderinfo`, { colisn });
setCustomerProfile(data.result?.[0] || {});
};
const switchConversation = (cc) => {
setCurrentID(cc.id);
setCurrentConversation(cc);
const _all = [];
// const _all = all.map((ele) => whatsappMsgMapped['whatsapp.inbound_message.received'].contentToRender(ele)); // debug: 0
// const _all = all.map((ele) => receivedMsgTypeMapped['whatsapp.inbound_message.received'].contentToRender(ele)); // debug: 0
// todo: update msg status
// const _all = all2.map((ele) => whatsappMsgMapped['whatsapp.message.updated'].contentToRender(ele)); // debug: 0
// const _all = all2.map((ele) => receivedMsgTypeMapped['whatsapp.message.updated'].contentToRender(ele)); // debug: 0
setMessages([..._all, ...(activeConversations[cc.id] || [])]);
// Get customer profile when switching conversation
// getCustomerProfile(cc.id);
// getCustomerProfile(??);
};
useEffect(() => {
return () => {
getCustomerProfile(currentID);
};
}, [currentID]);
// Get customer profile when switching conversation
// useEffect(() => {
// return () => {
// getCustomerProfile(currentID);
// };
// }, [currentID]);
/**
* *****************************************************************************************************
@ -157,9 +158,8 @@ export const useConversations = ({loginUser, realtimeAPI}) => {
setMessages((prevMessages) => {
return prevMessages.map(ele => {
if (ele.id === message.id) {
return {...ele, id: message.id, status: message.status}; // todo: renderId 需要返回
return {...ele, id: message.id, status: message.status, dateString: message.dateString};
}
// return {...ele, status: 'failed', dateString: '❌'}; // debug: 0
return ele;
});
});
@ -175,18 +175,17 @@ export const useConversations = ({loginUser, realtimeAPI}) => {
if (!result) {
return false;
}
let resultType = result.type;
if (errcode !== 0) {
// addError('Error Connecting to Server');
resultType = result.action;
}
if (typeof result.type === 'string' && result.type === 'error') {
// addError('Error Connecting to Server');
}
console.log(result.type, 'result.type');
const msgObj = whatsappMsgMapped[result.type].getMsg(result);
const msgRender = whatsappMsgMapped[result.type].contentToRender(msgObj);
const msgUpdate = whatsappMsgMapped[result.type].contentToUpdate(msgObj);
console.log(resultType, 'result.type');
const msgObj = receivedMsgTypeMapped[resultType].getMsg(result);
const msgRender = receivedMsgTypeMapped[resultType].contentToRender(msgObj);
const msgUpdate = receivedMsgTypeMapped[resultType].contentToUpdate(msgObj);
console.log('msgRender msgUpdate', msgRender, msgUpdate);
if (result.type === 'whatsapp.message.updated') {
if ( ['whatsapp.message.updated', 'message'].includes(resultType)) {
updateMessage(msgUpdate);
// return false;
}
@ -198,7 +197,7 @@ export const useConversations = ({loginUser, realtimeAPI}) => {
const sendMessage = (msgObj) => {
const contentToSend = sentMsgTypeMapped[msgObj.type].contentToSend(msgObj);
realtimeAPI.sendMessage(contentToSend);
realtimeAPI.sendMessage({ ...contentToSend, opi_sn: userId });
const contentToRender = sentMsgTypeMapped[msgObj.type].contentToRender(msgObj);
console.log(contentToRender, 'contentToRender sendMessage------------------');
addMessage(contentToRender);
@ -214,7 +213,7 @@ export const useConversations = ({loginUser, realtimeAPI}) => {
switchConversation,
templates: templatesList, // setTemplates, getTemplates,
// templates, // debug: 0
customerOrderProfile,
customerOrderProfile, getCustomerProfile
};
};

Loading…
Cancel
Save