更新消息送达状态

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"; import { v4 as uuid } from "uuid";
export const replaceTemplateString = (str, replacements) => { export const replaceTemplateString = (str, replacements) => {
@ -24,11 +25,11 @@ export const replaceTemplateString = (str, replacements) => {
export const sentMsgTypeMapped = { export const sentMsgTypeMapped = {
text: { text: {
type: '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 }), contentToRender: (msg) => ({ ...msg }),
}, },
whatsappTemplate: { 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) => { contentToRender: (msg) => {
console.log(msg); console.log(msg);
const templateDataMapped = msg.template?.components ? msg.template.components.reduce((r, v) => ({...r, [v.type]: v}), {}) : null; 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': { 'whatsapp.inbound_message.received': {
getMsg: (result) => { getMsg: (result) => {
console.log('whatsapp.inbound_message.received', result); console.log('whatsapp.inbound_message.received', result);
@ -62,27 +63,38 @@ export const whatsappMsgMapped = {
return result?.whatsappMessage || null; return result?.whatsappMessage || null;
}, },
contentToRender: (msgcontent) => { contentToRender: (msgcontent) => {
return null; // todo: 仅更新消息状态, 没有输出 return null; // * 仅更新消息状态, 没有输出
let contentObj = msgcontent?.whatsappMessage || msgcontent; // debug: // let contentObj = msgcontent?.whatsappMessage || msgcontent; // debug:
if ((contentObj?.status === 'failed' )) { // if ((contentObj?.status === 'failed' )) {
contentObj = { // contentObj = {
type: 'error', // type: 'error',
text: {body: '❌ Message failed to send' }, // contentObj.errorMessage // text: {body: '❌ Message failed to send' }, // contentObj.errorMessage
id: contentObj.id, // id: contentObj.id,
wamid: contentObj.id, // wamid: contentObj.id,
}; // };
return contentObj; // return contentObj;
} // }
return null; // return null;
console.log('whatsapp.message.updated to render', contentObj); // console.log('whatsapp.message.updated to render', contentObj);
const _r = parseRenderMessageItem(contentObj); // const _r = parseRenderMessageItem(contentObj);
console.log('_r', _r); // console.log('_r', _r);
return parseRenderMessageItem(contentObj); // return parseRenderMessageItem(contentObj);
}, },
contentToUpdate: (msgcontent) => ({ ...msgcontent, id: msgcontent.id, status: msgcontent.status }), 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 = { export const whatsappMsgTypeMapped = {
error: { error: {
type: (_m) => ({ type: 'system' }), type: (_m) => ({ type: 'system' }),
@ -158,7 +170,7 @@ export const parseRenderMessageItem = (msg) => {
return { return {
date: msg?.sendTime || '', date: msg?.sendTime || '',
...(whatsappMsgTypeMapped?.[msg.type]?.data(msg) || {}), ...(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', // type: whatsappMsgTypeMapped?.[msg.type]?.type || 'text',
sender: msg.from, sender: msg.from,
status: msg?.status || 'waiting', status: msg?.status || 'waiting',

@ -1,23 +1,20 @@
import { webSocket } from 'rxjs/webSocket'; 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"; import { v4 as uuid } from "uuid";
export class RealTimeAPI { export class RealTimeAPI {
constructor(param) { constructor(param) {
this.webSocket = webSocket(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)
// )
// )
// );
} }
getObservable() { getObservable() {
return this.webSocket; return this.webSocket.pipe(
retry({
count: 10,
delay: () => timer(1000)
})
);
} }
disconnect() { disconnect() {

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

Loading…
Cancel
Save