From b2721cd1eea6d53ada7cad4db9b31acf4668f440 Mon Sep 17 00:00:00 2001 From: Lei OT Date: Wed, 31 Jan 2024 14:26:30 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=9A=E8=AF=9D=E5=88=87=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Conversations/ConversationContext.js | 49 ++++++++++--- src/views/Conversations/ChatWindow.jsx | 3 +- .../Components/ConversationsList.jsx | 24 +++++-- .../Components/CustomerProfile.jsx | 12 ++-- .../Conversations/Components/InputBox.jsx | 71 +++++++++++-------- tailwind.config.js | 20 ++++-- 6 files changed, 119 insertions(+), 60 deletions(-) diff --git a/src/stores/Conversations/ConversationContext.js b/src/stores/Conversations/ConversationContext.js index 583b2a7..198eb39 100644 --- a/src/stores/Conversations/ConversationContext.js +++ b/src/stores/Conversations/ConversationContext.js @@ -17,7 +17,24 @@ export async function fetchJSON(url, data) { const response = await fetch(`${host}${url}${ifp}${params}`); return await response.json(); } - +export async function postJSON(url, obj) { + try { + const response = await fetch(url, { + method: 'POST', + body: JSON.stringify(obj), + headers: { + 'Content-Type': 'application/json', + }, + }); + if (!response.ok) { + throw new Error('Network response was not ok'); + } + return await response.json(); + } catch (error) { + console.error('fetch error:', error); + throw error; + } +} // const API_HOST = 'http://202.103.68.144:8888'; const API_HOST = 'https://p9axztuwd7x8a7.mycht.cn/whatsapp_callback'; @@ -54,7 +71,7 @@ export const useConversations = ({loginUser, realtimeAPI}) => { }, []); useEffect(() => { - getConversationsList(); + getConversationsList(); // todo: 和刷新订单会话页面有冲突 getTemplates(); return () => {}; }, []); @@ -66,12 +83,15 @@ export const useConversations = ({loginUser, realtimeAPI}) => { // return () => {}; // }, [conversationsList]); + const poseConversationItemClose = async (item) => { + const res = await postJSON(`${API_HOST}/closeconversation`, { opisn: userId, conversationid: item.sn }); + } const getConversationsList = async () => { const { result: data } = await fetchJSON(`${API_HOST}/getconversations`, { opisn: userId }); // const _data = []; const _data = testConversations; - const list = [..._data, ...data]; + const list = [..._data, ...data.map(ele => ({...ele, customer_name: ele.whatsapp_name.trim()}))]; const dataMapped = list.reduce((r, v) => ({ ...r, [`${v.sn}`]: [] }), {}); setConversationsList(list); setActiveConversations({...dataMapped, ...activeConversations}); @@ -137,7 +157,8 @@ export const useConversations = ({loginUser, realtimeAPI}) => { // Get customer profile when switching conversation useEffect(() => { console.log('currentConversation', currentConversation); - setMessages([...(activeConversations[currentID] || [])]); + setCurrentID(currentConversation.sn); + setMessages([...(activeConversations[currentConversation.sn] || [])]); return () => {}; }, [currentConversation]); @@ -159,8 +180,8 @@ export const useConversations = ({loginUser, realtimeAPI}) => { if (targetId !== currentID) { setConversationsList((prevList) => { return prevList.map((ele) => { - if (ele.id === targetId) { - return { ...ele, new_msgs: ele.new_msgs + 1 }; + if (ele.sn === targetId) { + return { ...ele, new_msgs: ele.new_msgs + 1, last_received_time: message.date }; } return ele; }); @@ -178,8 +199,10 @@ export const useConversations = ({loginUser, realtimeAPI}) => { const addMessage = (message) => { - setMessages((prevMessages) => [...prevMessages, message]); addMessageToConversations(message.conversationid, message); + if (message.conversationid === currentID) { + setMessages((prevMessages) => [...prevMessages, message]); + } }; const updateMessage = (message) => { @@ -202,6 +225,15 @@ export const useConversations = ({loginUser, realtimeAPI}) => { ...prevList, [targetId]: targetMsgs, })); + // 更新列表的时间 + setConversationsList((prevList) => { + return prevList.map((ele) => { + if (ele.sn === targetId) { + return { ...ele, new_msgs: ele.new_msgs + 1, last_received_time: message.date }; + } + return ele; + }); + }); }; @@ -252,7 +284,8 @@ export const useConversations = ({loginUser, realtimeAPI}) => { getConversationsList, switchConversation, templates: templatesList, // setTemplates, getTemplates, - customerOrderProfile, getCustomerProfile + customerOrderProfile, getCustomerProfile, + poseConversationItemClose }; }; diff --git a/src/views/Conversations/ChatWindow.jsx b/src/views/Conversations/ChatWindow.jsx index 1928fd9..1ddbe4a 100644 --- a/src/views/Conversations/ChatWindow.jsx +++ b/src/views/Conversations/ChatWindow.jsx @@ -68,11 +68,10 @@ const ChatWindow = (() => { sendMessage(v)} /> - {/* sendMessage(v)} /> */} - + diff --git a/src/views/Conversations/Components/ConversationsList.jsx b/src/views/Conversations/Components/ConversationsList.jsx index a8fe23c..1095dc3 100644 --- a/src/views/Conversations/Components/ConversationsList.jsx +++ b/src/views/Conversations/Components/ConversationsList.jsx @@ -9,21 +9,27 @@ import { useGetJson } from '@/hooks/userFetch'; */ const Conversations = (() => { const navigate = useNavigate(); - const { switchConversation, conversationsList } = useConversationContext(); + const { switchConversation, conversationsList, poseConversationItemClose } = useConversationContext(); // console.log(conversationsList); const [chatlist, setChatlist] = useState([]); useEffect(() => { setChatlist( (conversationsList || []).map((item) => ({ ...item, - avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=${item.whatsapp_name}`, - alt: item.whatsapp_name, + avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=${item.whatsapp_name.trim() || item.whatsapp_phone_number}`, id: item.sn, - title: item.whatsapp_name, - subtitle: item.whatsapp_phone_number, + alt: item.whatsapp_name, + title: item.whatsapp_name.trim() || item.whatsapp_phone_number, + // subtitle: item.whatsapp_phone_number, // subtitle: item.lastMessage, date: item.last_received_time, // last_send_time unread: item.unread_msg_count, + showMute: true, + muted: false, + // showVideoCall: true, + // statusColor: '#ccd5ae', + // statusColorType: 'badge', + // statusText: 'online' })) ); @@ -39,7 +45,13 @@ const Conversations = (() => { return ( <> - onSwitchConversation(item)} /> + onSwitchConversation(item)} + // onContextMenu={(item, i, e) => { + // console.log(item, i, e); + // return (

ppp

) + // }} + onClickMute={poseConversationItemClose} + /> ); }); diff --git a/src/views/Conversations/Components/CustomerProfile.jsx b/src/views/Conversations/Components/CustomerProfile.jsx index 1b5e87f..2ce3089 100644 --- a/src/views/Conversations/Components/CustomerProfile.jsx +++ b/src/views/Conversations/Components/CustomerProfile.jsx @@ -27,8 +27,8 @@ const CustomerProfile = (({ customer }) => { const { quotes, contact, last_contact, ...order } = orderInfo; return ( -
- + {}} optionType='button' buttonStyle={'solid'} />}> @@ -42,7 +42,7 @@ const CustomerProfile = (({ customer }) => { {contact?.[0]?.name} {contact?.[0]?.phone && {contact?.[0]?.phone}} {contact?.[0]?.email && {contact?.[0]?.email}} - {contact?.[0]?.whatsapp_phone_number} + {contact?.[0]?.whatsapp_phone_number && {contact?.[0]?.whatsapp_phone_number}} {/*
{order?.order_no}
*/} {/*
{order?.location} {order?.local_datetime} @@ -59,11 +59,11 @@ const CustomerProfile = (({ customer }) => { -

-      
+      

+      {/* 
         沟通记录
         
-      
+       */}
     
   );
 });
diff --git a/src/views/Conversations/Components/InputBox.jsx b/src/views/Conversations/Components/InputBox.jsx
index 0ce2e2a..cd5e8ca 100644
--- a/src/views/Conversations/Components/InputBox.jsx
+++ b/src/views/Conversations/Components/InputBox.jsx
@@ -4,14 +4,14 @@ import { Input, Button, Tabs, List, Space, Popover, Flex } from 'antd';
 import { useConversationContext } from '@/stores/Conversations/ConversationContext';
 import { LikeOutlined, MessageOutlined, StarOutlined, SendOutlined, PlusOutlined, PlusCircleOutlined } from '@ant-design/icons';
 import { cloneDeep, getNestedValue, isEmpty } from '@/utils/utils';
-import { v4 as uuid } from "uuid";
+import { v4 as uuid } from 'uuid';
 import { whatsappTemplatesParamMapped } from '@/lib/msgUtils';
 
-const InputBox = (({ onSend }) => {
+const InputBox = ({ onSend }) => {
   const { currentConversation, templates } = useConversationContext();
   const [textContent, setTextContent] = useState('');
 
-  const talkabled = ! isEmpty( currentConversation.sn);
+  const talkabled = !isEmpty(currentConversation.sn);
 
   const handleSendText = () => {
     if (typeof onSend === 'function' && textContent.trim() !== '') {
@@ -32,7 +32,7 @@ const InputBox = (({ onSend }) => {
   const handleSendTemplate = (fromTemplate) => {
     console.log(fromTemplate, 'fromTemplate');
     if (typeof onSend === 'function') {
-      const _conversation = {...cloneDeep(currentConversation), };
+      const _conversation = { ...cloneDeep(currentConversation) };
       const msgObj = {
         type: 'whatsappTemplate',
         to: currentConversation.whatsapp_phone_number,
@@ -45,22 +45,24 @@ const InputBox = (({ onSend }) => {
           name: fromTemplate.name,
           language: { code: fromTemplate.language },
           ...(fromTemplate.components.body[0]?.example?.body_text?.[0]?.length > 0
-            ? { components: [
-              {
-                'type': 'body',
-                'parameters': whatsappTemplatesParamMapped[fromTemplate.name].map((v) => ({ type: 'text', text: getNestedValue(_conversation, v) || '' }))
-                // [
-                //   {
-                //     'type': 'text',
-                //     'text': getNestedValue(_conversation, whatsappTemplatesParamMapped[fromTemplate.name][0]) ,
-                //   },
-                //   { // debug:
-                //     'type': 'text',
-                //     'text': getNestedValue(_conversation, whatsappTemplatesParamMapped[fromTemplate.name]?.[1] || whatsappTemplatesParamMapped[fromTemplate.name][0]) ,
-                //   },
-                // ],
-              },
-            ], }
+            ? {
+                components: [
+                  {
+                    'type': 'body',
+                    'parameters': whatsappTemplatesParamMapped[fromTemplate.name].map((v) => ({ type: 'text', text: getNestedValue(_conversation, v) || '' })),
+                    // [
+                    //   {
+                    //     'type': 'text',
+                    //     'text': getNestedValue(_conversation, whatsappTemplatesParamMapped[fromTemplate.name][0]) ,
+                    //   },
+                    //   { // debug:
+                    //     'type': 'text',
+                    //     'text': getNestedValue(_conversation, whatsappTemplatesParamMapped[fromTemplate.name]?.[1] || whatsappTemplatesParamMapped[fromTemplate.name][0]) ,
+                    //   },
+                    // ],
+                  },
+                ],
+              }
             : {}),
         },
         template_origin: fromTemplate,
@@ -84,13 +86,19 @@ const InputBox = (({ onSend }) => {
               itemLayout='horizontal'
               dataSource={templates}
               renderItem={(item, index) => (
-                 handleSendTemplate(item)} size={'small'} type='link' key={'send'} icon={}>
-                      Send
-                    ,
-                  ]}>
-                  
+                
+                  
+                        <>{item.components.header?.[0]?.text || item.name}
+                        
+                      
+                    }
+                    description={item.components.body?.[0]?.text}
+                  />
                 
               )}
             />
@@ -99,12 +107,13 @@ const InputBox = (({ onSend }) => {
           trigger='click'
           open={openTemplates}
           onOpenChange={handleOpenChange}>
-          {/*  */}