diff --git a/src/api/get.ts b/src/api/get.ts index a46fdfac..d2791de3 100644 --- a/src/api/get.ts +++ b/src/api/get.ts @@ -1,22 +1,22 @@ import { getInstance, getPublicInstance } from './axios'; -//admin + +/** + * Admin Controller + */ export const getAdminsUnpaidConsults = async () => await getInstance('/admins/unpaid-consults'); export const getAdminsPedningProfilse = async () => await getInstance('/admins/pending-profiles'); export const getAdminsRefundWaiting = async () => await getInstance('/admins/refund-waiting'); -// //밑에 두개 지우기 -// export const getChats = async (params: any) => -// await getInstance('/chats', params); -// export const getLetters = async (params: any) => -// await getInstance('/letters', params); // 판매자 사이드 letter list export const getConselorLetters = async (params: any) => await getInstance('/letters/counselors', params); -//Chat Controller +/** + * Chat Controller + */ //채팅 목록 반환 export const getChatsCustomers = async (params: any) => await getInstance('/chats/customers', params); @@ -32,14 +32,19 @@ export const getChatMessagesCounselors = async (chatId: string, params: any) => export const getChatsMinder = async (params: any) => await getInstance('/chats/counselors', params); -//Consult Controller + +/** + * Consult Controller + */ export const getConsultsCustomers = async () => await getPublicInstance('/consults/customers'); export const getConsultsMinder = async () => await getPublicInstance('/consults/counselors'); -//Letter Controller +/** + * Letter Controller + */ //편지 목록 반환 export const getLettersCustomers = async (params: any) => await getInstance('/letters/customers', params); @@ -63,11 +68,16 @@ export const getLetterDeadline = async (letterId: string | undefined) => export const getLettersNickname = async (letterId: string | undefined) => await getInstance(`/letters/nickname/${letterId}`); -//Customer Controller +/** + * Customer Controller + */ +export const getCustomers = async () => await getInstance('customers'); export const getCustomersNickname = async () => await getPublicInstance('/customers/nickname'); -//LetterMessage Controller +/** + * LetterMessage Controller + */ export const getLetterMessages = async ( params: any, letterId: string | undefined, @@ -82,7 +92,10 @@ export const getReviewsCustomer = async (params: any) => export const getReviewsAll = async (counselorId: number, params: any) => await getPublicInstance(`/reviews/all/${counselorId}`, params); -// Conuselor Controller +/** + * Counselor Controller + */ +export const getCounselors = async () => await getInstance('counselors'); export const getMyInfo = async () => await getInstance('counselors/my-info'); export const getProfiles = async () => await getInstance('counselors/profiles'); export const getIsPassQuiz = async () => await getInstance('counselors/quiz'); @@ -93,12 +106,18 @@ export const getCounselorConsults = async ( //마인더 프로필 페이지 마인더 프로필 조회 export const getCounselorsAll = async (counselorId: string | undefined) => await getPublicInstance(`/counselors/all/${counselorId}`); -// SearchWord Controller + +/** + * SearchWord Controller + */ export const getSearchWords = async () => await getPublicInstance('/searchWords'); export const getCounselorsChats = async (chatId: string, params: any) => await getInstance(`/counselors/chats/${chatId}`, params); -//Payment Controller + +/** + * Payment Controller + */ export const getPaymentsCustomers = async (params: any) => await getInstance('/payments/customers', params); @@ -107,8 +126,10 @@ export const getPaymentsMinder = async (params: any) => export const getPaymentsHome = async () => await getInstance('/payments/counselors/home'); -//Review Controller +/** + * Review Controller + */ export const getMinderReviews = async (params: any) => await getInstance('/reviews/counselors', params); export const getMinderReviewsHome = async () => diff --git a/src/components/Buyer/BuyerConsult/BuyerChatSection.tsx b/src/components/Buyer/BuyerConsult/BuyerChatSection.tsx index b2ab3ebc..6bc244e8 100644 --- a/src/components/Buyer/BuyerConsult/BuyerChatSection.tsx +++ b/src/components/Buyer/BuyerConsult/BuyerChatSection.tsx @@ -3,23 +3,31 @@ import styled from 'styled-components'; import { ConsultCard } from 'components/Buyer/Common/ConsultCard'; import { useEffect, useLayoutEffect, useRef, useState } from 'react'; import { consultApiObject } from 'pages/Buyer/BuyerConsult'; -import { getChatsCustomers } from 'api/get'; +import { getChatsCustomers, getCustomers } from 'api/get'; import { useStompContext } from 'contexts/StompContext'; import { LoadingSpinner } from 'utils/LoadingSpinner'; import { Heading } from 'styles/font'; import { ReactComponent as Empty } from 'assets/icons/graphic-noting.svg'; import { convertChatListDate } from 'utils/convertDate'; + +// +// +// + interface BuyerChatSectionProps { sortType: number; isChecked: boolean; } +// +// +// + export const BuyerChatSection = ({ sortType, isChecked, }: BuyerChatSectionProps) => { const [cardData, setCardData] = useState([]); //card에 넘길 데이터 - const [isLoading, setIsLoading] = useState(true); const roomIdsRef = useRef([]); //unmout 시 unsubscibe를 위함 @@ -30,7 +38,10 @@ export const BuyerChatSection = ({ */ const cardDataRef = useRef([]); const { stompClient, isConnected } = useStompContext(); - //채팅 readId, 가장 최근 unread message, 정렬 업데이트 + + /** + * 채팅 readId, 가장 최근 unread message, 정렬 업데이트 + */ const updateChatData = ( chatId: number, content: string, @@ -57,85 +68,34 @@ export const BuyerChatSection = ({ } }; - useEffect(() => { - if (!isConnected) { - return; - } - - if (stompClient.current) { - stompClient.current.subscribe( - '/queue/chattings/connect/customers/', - (rooms) => { - const response = JSON.parse(rooms.body); - roomIdsRef.current = response.roomIds; - - response.roomIds.forEach((chatId: number) => { - //모든 채팅방 subscribe - stompClient.current?.subscribe( - '/queue/chatMessages/customers/' + chatId, - (message) => { - const response = JSON.parse(message.body); - updateChatData( - chatId, - response.content, - convertChatListDate(response.sendTime), - ); - }, - ); - }); - if (response.userId !== null) { - userIdRef.current = response.userId; - //채팅방 생성, 종료 readid tab 갱신 - stompClient.current?.subscribe( - '/queue/chattings/notifications/customers/' + response.userId, - (message) => { - const notification = JSON.parse(message.body); - if ( - notification.chatRoomWebsocketStatus === 'CHAT_ROOM_CREATE' - ) { - //add cardData - const addedChatRoomItem: consultApiObject = { - consultStyle: notification.consultStyle, - id: notification.chatId, - latestMessageContent: `${notification.opponentNickname}님께 고민 내용을 남겨 주세요. ${notification.opponentNickname}님이 24시간 이내 답장을 드릴 거예요.`, - latestMessageIsCustomer: null, - latestMessageUpdatedAt: convertChatListDate( - notification.createTime, - ), - opponentNickname: notification.opponentNickname, - status: '상담 대기', - unreadMessageCount: 0, - reviewCompleted: null, - consultId: null, - }; - //add roomIds for unsubscribe - roomIdsRef.current.unshift(notification.chatId); + /** + * 채팅방 생성 시 chat data add + */ + const addChatData = (notification: any) => { + //add cardData + const addedChatRoomItem: consultApiObject = { + consultStyle: notification.consultStyle, + id: notification.chatId, + latestMessageContent: `${notification.opponentNickname}님께 고민 내용을 남겨 주세요. ${notification.opponentNickname}님이 24시간 이내 답장을 드릴 거예요.`, + latestMessageIsCustomer: null, + latestMessageUpdatedAt: convertChatListDate(notification.createTime), + opponentNickname: notification.opponentNickname, + status: '상담 대기', + unreadMessageCount: 0, + reviewCompleted: null, + consultId: null, + }; + //add roomIds for unsubscribe + roomIdsRef.current.unshift(notification.chatId); - cardDataRef.current = [ - addedChatRoomItem, - ...cardDataRef.current, - ]; + cardDataRef.current = [addedChatRoomItem, ...cardDataRef.current]; - setCardData(cardDataRef.current); + setCardData(cardDataRef.current); + }; - //subscribe new chatroom - stompClient.current?.subscribe( - '/queue/chatMessages/customers/' + notification.chatId, - (message) => { - const response = JSON.parse(message.body); - updateChatData( - notification.chatId, - response.content, - convertChatListDate(response.sendTime), - ); - }, - ); - } - }, - ); - } - }, - ); + useEffect(() => { + if (!isConnected) { + return; } const sendConnectRequest = () => { @@ -148,10 +108,79 @@ export const BuyerChatSection = ({ } }; - sendConnectRequest(); + const getCustomerUserIdAndSubscribe = async () => { + try { + const response: any = await getCustomers(); + userIdRef.current = response.data; + subscribeChatList(); + sendConnectRequest(); + } catch (e) { + console.error(e); + } + }; + + const subscribeChatList = () => { + if (stompClient.current) { + // 이거 전에 먼저 userId 를 받고 userId 기준으로 subscribe 한다. + stompClient.current.subscribe( + `/queue/chattings/connect/customers/${userIdRef.current}`, + (rooms) => { + const response = JSON.parse(rooms.body); + roomIdsRef.current = response.roomIds; + response.roomIds.forEach((chatId: number) => { + //모든 채팅방 subscribe + stompClient.current?.subscribe( + '/queue/chatMessages/customers/' + chatId, + (message) => { + const response = JSON.parse(message.body); + updateChatData( + chatId, + response.content, + convertChatListDate(response.sendTime), + ); + }, + ); + }); + if (response.userId !== null) { + // userIdRef.current = response.userId; + //채팅방 생성, 종료 readid tab 갱신 + stompClient.current?.subscribe( + '/queue/chattings/notifications/customers/' + response.userId, + (message) => { + const notification = JSON.parse(message.body); + if ( + notification.chatRoomWebsocketStatus === 'CHAT_ROOM_CREATE' + ) { + addChatData(notification); + + //subscribe new chatroom + stompClient.current?.subscribe( + '/queue/chatMessages/customers/' + notification.chatId, + (message) => { + const response = JSON.parse(message.body); + updateChatData( + notification.chatId, + response.content, + convertChatListDate(response.sendTime), + ); + }, + ); + } + }, + ); + } + }, + ); + } + }; + + getCustomerUserIdAndSubscribe(); + + // + // + // return () => { - console.log('effect callback'); roomIdsRef.current.forEach((value) => { stompClient.current?.unsubscribe( '/queue/chatMessages/customers/' + value, diff --git a/src/components/Seller/SellerConsult/SellerChatList.tsx b/src/components/Seller/SellerConsult/SellerChatList.tsx index c9223e33..ed7c0a49 100644 --- a/src/components/Seller/SellerConsult/SellerChatList.tsx +++ b/src/components/Seller/SellerConsult/SellerChatList.tsx @@ -1,4 +1,4 @@ -import { getChatsMinder } from 'api/get'; +import { getChatsMinder, getCounselors } from 'api/get'; import { ConsultModal } from 'components/Buyer/BuyerConsult/ConsultModal'; import React, { useCallback, useEffect, useRef, useState } from 'react'; import { SetURLSearchParams, useNavigate } from 'react-router-dom'; @@ -12,8 +12,10 @@ import { LoadingSpinner } from 'utils/LoadingSpinner'; import { useStompContext } from 'contexts/StompContext'; import { convertChatListDate } from 'utils/convertDate'; import { ConsultInfoItem, ConsultInfoList } from 'utils/type'; -//buyer consult에 저장돼있고, 나중에 type으로 뺴고 consultinfoLIst 지우기 -//consultinfolist type에 더미값 들어가 있음 + +// +// +// interface SellerConsultProps { sortType: number; @@ -23,6 +25,10 @@ interface SellerConsultProps { setSearchParams: SetURLSearchParams; } +// +// +// + function SellerChatList({ sortType, isChecked, @@ -30,13 +36,14 @@ function SellerChatList({ searchParams, setSearchParams, }: SellerConsultProps) { + const navigate = useNavigate(); + const setScrollLock = useSetRecoilState(scrollLockState); + const [consultInfo, setConsultInfo] = useState([]); const [isLoading, setIsLoading] = useState(true); const [isModalOpen, setIsModalOpen] = useRecoilState( isConsultModalOpenState, ); - const setScrollLock = useSetRecoilState(scrollLockState); - const navigate = useNavigate(); const roomIdsRef = useRef([]); //unmout 시 unsubscibe를 위함 const userIdRef = useRef(-1); @@ -46,7 +53,10 @@ function SellerChatList({ */ const cardDataRef = useRef([]); const { stompClient, isConnected } = useStompContext(); - //채팅 readId, 가장 최근 unread message, 정렬 업데이트 + + /** + * 새로운 채팅 도착 시 업데이트 + */ const updateChatData = ( chatId: number, content: string, @@ -72,87 +82,40 @@ function SellerChatList({ setConsultInfo(updatedCardData); } }; - useEffect(() => { - if (!isConnected) { - return; - } - - if (stompClient.current) { - stompClient.current.subscribe( - '/queue/chattings/connect/counselors/', - (rooms) => { - const response = JSON.parse(rooms.body); - roomIdsRef.current = response.roomIds; - response.roomIds.forEach((chatId: number) => { - //모든 채팅방 subscribe - stompClient.current?.subscribe( - '/queue/chatMessages/counselors/' + chatId, - (message) => { - const response = JSON.parse(message.body); - updateChatData( - chatId, - response.content, - convertChatListDate(response.sendTime), - ); - }, - ); - }); - if (response.userId !== null) { - userIdRef.current = response.userId; - //채팅방 생성, 종료 readid tab 갱신 - stompClient.current?.subscribe( - '/queue/chattings/notifications/counselors/' + response.userId, - (message) => { - const notification = JSON.parse(message.body); - if ( - notification.chatRoomWebsocketStatus === 'CHAT_ROOM_CREATE' - ) { - //add cardData - const addedChatRoomItem: ConsultInfoItem = { - consultStyle: notification.consultStyle, - id: notification.chatId, - latestMessageContent: `${notification.opponentNickname}님께 고민 내용을 남겨 주세요. ${notification.opponentNickname}님이 24시간 이내 답장을 드릴 거예요.`, - latestMessageIsCustomer: null, - latestMessageUpdatedAt: convertChatListDate( - notification.createTime, - ), - opponentNickname: notification.opponentNickname, - status: '상담 대기', - unreadMessageCount: 0, - reviewCompleted: null, - consultId: null, - }; - //add roomIds for unsubscribe - roomIdsRef.current.unshift(notification.chatId); + /** + * 채팅방 생성 시 chat data add + */ + const addChatData = (notification: any) => { + //add cardData + const addedChatRoomItem: ConsultInfoItem = { + consultStyle: notification.consultStyle, + id: notification.chatId, + latestMessageContent: `${notification.opponentNickname}님께 고민 내용을 남겨 주세요. ${notification.opponentNickname}님이 24시간 이내 답장을 드릴 거예요.`, + latestMessageIsCustomer: null, + latestMessageUpdatedAt: convertChatListDate(notification.createTime), + opponentNickname: notification.opponentNickname, + status: '상담 대기', + unreadMessageCount: 0, + reviewCompleted: null, + consultId: null, + }; + //add roomIds for unsubscribe + roomIdsRef.current.unshift(notification.chatId); - cardDataRef.current = [ - addedChatRoomItem, - ...cardDataRef.current, - ]; + cardDataRef.current = [addedChatRoomItem, ...cardDataRef.current]; - setConsultInfo(cardDataRef.current); + setConsultInfo(cardDataRef.current); + }; - //subscribe new chatroom - stompClient.current?.subscribe( - '/queue/chatMessages/counselors/' + notification.chatId, - (message) => { - const response = JSON.parse(message.body); - updateChatData( - notification.chatId, - response.content, - convertChatListDate(response.sendTime), - ); - }, - ); - } - }, - ); - } - }, - ); + useEffect(() => { + if (!isConnected) { + return; } + /** + * + */ const sendConnectRequest = () => { if (stompClient.current) { stompClient.current.send( @@ -163,7 +126,75 @@ function SellerChatList({ } }; - sendConnectRequest(); + const getCounselorUserIdAndSubscribe = async () => { + try { + const response: any = await getCounselors(); + userIdRef.current = response.data; + subscribeChatList(); + sendConnectRequest(); + } catch (e) { + console.error(e); + } + }; + + const subscribeChatList = () => { + if (stompClient.current) { + stompClient.current.subscribe( + `/queue/chattings/connect/counselors/${userIdRef.current}`, + (rooms) => { + const response = JSON.parse(rooms.body); + roomIdsRef.current = response.roomIds; + + response.roomIds.forEach((chatId: number) => { + //모든 채팅방 subscribe + stompClient.current?.subscribe( + '/queue/chatMessages/counselors/' + chatId, + (message) => { + const response = JSON.parse(message.body); + updateChatData( + chatId, + response.content, + convertChatListDate(response.sendTime), + ); + }, + ); + }); + if (response.userId !== null) { + //채팅방 생성, 종료 readid tab 갱신 + stompClient.current?.subscribe( + '/queue/chattings/notifications/counselors/' + response.userId, + (message) => { + const notification = JSON.parse(message.body); + if ( + notification.chatRoomWebsocketStatus === 'CHAT_ROOM_CREATE' + ) { + addChatData(notification); + //subscribe new chatroom + stompClient.current?.subscribe( + '/queue/chatMessages/counselors/' + notification.chatId, + (message) => { + const response = JSON.parse(message.body); + updateChatData( + notification.chatId, + response.content, + convertChatListDate(response.sendTime), + ); + }, + ); + } + }, + ); + } + }, + ); + } + }; + + getCounselorUserIdAndSubscribe(); + + // + // + // return () => { roomIdsRef.current.forEach((value) => {