Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactored Code: Removed redundant window.androidIntract, added GetBotList and SocketComponents, implemented expired bot logic #126

Merged
merged 5 commits into from
Jul 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions apps/uci/web/src/app/chats/[chatid]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,6 @@ const Chats: NextPage<{ params: { chatid: string } }> = ({ params }) => {
if (!params?.chatid) router.push('/');
}, [router, params?.chatid]);

useEffect(() => {
window && window?.androidInteract?.onBotListingScreenFocused(false);
window &&
window?.androidInteract?.log(`On Home Page onBotListingScreenFocused:false triggered`);
}, []);



Expand Down
10 changes: 0 additions & 10 deletions apps/uci/web/src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,16 +82,6 @@ export default function Home() {
borderRadius: "50%",
fontSize: "14px",
}}
onClick={(): void => {
try {
window && window?.androidInteract?.onDestroyScreen();
} catch (err) {
window &&
window?.androidInteract?.log(
`error in destroying screen:${JSON.stringify(err)}`
);
}
}}
size="sm"
variant="ghost"
>
Expand Down
5 changes: 0 additions & 5 deletions apps/uci/web/src/app/starred-chat/[chatId]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,6 @@ const StarredChat: NextPage<{ params: { chatId: string } }> = ({ params }) => {
const history = useRouter();
const user = useMemo(() => find(context?.allUsers, { id: params?.chatId }), [context?.allUsers, params?.chatId]);

useEffect(() => {
window && window?.androidInteract?.onBotListingScreenFocused(false);
window &&
window?.androidInteract?.onEvent(`On Home Page onBotListingScreenFocused:false triggered`);
}, []);

return (
<Flex bgColor="var(--primarydarkblue)" flexDirection="column" height="100vh" width="100%">
Expand Down
20 changes: 16 additions & 4 deletions apps/uci/web/src/components/common/chat-item/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useCallback, useContext } from 'react';
import React, { useCallback, useContext, useMemo } from 'react';
import { Box, useColorModeValue } from '@chakra-ui/react';
import styles from './index.module.css';
import profilePic from '../../../assets/images/bot_icon_2.png';
Expand All @@ -7,6 +7,7 @@ import { useRouter } from 'next/navigation';
import Image from 'next/image';
import { User } from '@/types';
import { AppContext } from '@/context';
import moment from 'moment';

interface chatItemProps {
active: boolean;
Expand All @@ -16,22 +17,30 @@ interface chatItemProps {
isBlank?: boolean;
}


const ChatItem: React.FC<chatItemProps> = ({ active, name, phoneNumber, user, isBlank }) => {
const history = useRouter();
const context = useContext(AppContext);

const fontColorToggle = useColorModeValue(styles.darkFontColor, styles.lightFontColor);

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use useMemo for calculated variables

const onChangingCurrentUserHandler = useCallback(() => {
const expiredItem = useMemo(() => {
return user?.endDate !== undefined && user.endDate < moment().format() && user?.status === 'ENABLED';
}, [user]);


const onChangeUser = useCallback(() => {
localStorage.setItem('currentUser', JSON.stringify(user));
context?.toChangeCurrentUser(user);
// console.log('user Date', user?.endDate);
// console.log('user Status', user?.status);
history.push(`/chats/${user?.id}`);
}, [context, history, user]);

return (
<React.Fragment>
<button
onClick={onChangingCurrentUserHandler}
onClick={onChangeUser}
disabled={isBlank}
className={` ${active ? styles.activeContainer : styles.container}`}
>
Expand All @@ -53,7 +62,8 @@ const ChatItem: React.FC<chatItemProps> = ({ active, name, phoneNumber, user, is
maxWidth: '70vw',
overflow: 'hidden',
whiteSpace: 'nowrap',
marginBottom: '0'
marginBottom: '0',
color: expiredItem ? 'lightgrey' : 'black'
}}
>
{name}
Expand All @@ -62,7 +72,9 @@ const ChatItem: React.FC<chatItemProps> = ({ active, name, phoneNumber, user, is
</Box>
</button>
</React.Fragment>

);

};

export default ChatItem;
33 changes: 1 addition & 32 deletions apps/uci/web/src/components/common/chat-ui-component/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,6 @@ export const ChatUiComponent: FC<{
if (res?.data?.result?.records?.length > 0) {
const normalizedChats = normalizedChat(res.data.result.records);
console.log("debug:", { normalizedChats });
window &&
window?.androidInteract?.log(JSON.stringify(normalizedChats));
localStorage.setItem("userMsgs", JSON.stringify(normalizedChats));
setMessages(normalizedChats);
} else {
Expand All @@ -97,14 +95,9 @@ export const ChatUiComponent: FC<{
console.log("chatUi=>:",{err})
setLoading(false);
toast.error(JSON.stringify(err?.message));
window &&
window?.androidInteract?.log(
`error in fetching chat history(online):${JSON.stringify(err)}`
);
});
} else {
setLoading(false);
try {
if (localStorage.getItem("chatHistory")) {
const offlineMsgs = filter(
// @ts-ignore
Expand All @@ -113,40 +106,16 @@ export const ChatUiComponent: FC<{
// @ts-ignore
{ botUuid: JSON.parse(localStorage.getItem("currentUser"))?.id }
);
window &&
window?.androidInteract?.log(localStorage.getItem("chatHistory"));


setMessages(offlineMsgs);
}
} catch (err) {

window &&
window?.androidInteract?.log(
`error in getting chat history(offline):${JSON.stringify(err)}`
);
}
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [conversationHistoryUrl, context?.socket?.connected
]);

useEffect(() => {
try {
window &&
window?.androidInteract?.onChatCompleted?.(
String(currentUser?.id),
JSON.stringify(context?.state?.messages)
);
window &&
window?.androidInteract?.log(JSON.stringify(context?.state?.messages));
} catch (err) {
window &&
window?.androidInteract?.log(
`error in onChatCompleted func:${JSON.stringify(err)}`
);
}
}, [context?.state?.messages, currentUser?.id]);

const handleSend = useCallback(
(type: string, val: any) => {
Expand Down
95 changes: 0 additions & 95 deletions apps/uci/web/src/components/common/message-item/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -87,77 +87,9 @@ export const MessageItem: FC<any> = ({
const t = omit(newStarredMsgs, [msgToStarred?.botUuid]);
context?.setStarredMsgs(t);
localStorage.setItem("starredChats", JSON.stringify(t));
try {
window &&
window?.androidInteract?.onMsgSaveUpdate(JSON.stringify(t));
window &&
window?.androidInteract?.onEvent(
"nl-chatbotscreen-starmessage",
JSON.stringify({
starred: false,
botid: msgToStarred?.botUuid,
messageid: msgToStarred?.messageId,
timestamp: moment().valueOf(),
})
);
window &&
window?.androidInteract?.log(
"nl-chatbotscreen-starmessage event:",
JSON.stringify({
starred: false,
botid: msgToStarred?.botUuid,
messageid: msgToStarred?.messageId,
timestamp: moment().valueOf(),
})
);
window &&
window?.androidInteract?.log(
`new starred : ${JSON.stringify(t)}`
);
} catch (err) {
window &&
window?.androidInteract?.log(
`error in onMsgSaveUpdate func:${JSON.stringify(err)}`
);
}
} else {
context?.setStarredMsgs(newStarredMsgs);
localStorage.setItem("starredChats", JSON.stringify(newStarredMsgs));
try {
window &&
window?.androidInteract?.onMsgSaveUpdate(
JSON.stringify(newStarredMsgs)
);
window &&
window?.androidInteract?.onEvent(
"nl-chatbotscreen-starmessage",
JSON.stringify({
starred: true,
botid: msgToStarred?.botUuid,
messageid: msgToStarred?.messageId,
timestamp: moment().valueOf(),
})
);
window &&
window?.androidInteract?.log(
"nl-chatbotscreen-starmessage event:",
JSON.stringify({
starred: true,
botid: msgToStarred?.botUuid,
messageid: msgToStarred?.messageId,
timestamp: moment().valueOf(),
})
);
window &&
window?.androidInteract?.log(
`new starred : ${JSON.stringify(newStarredMsgs)}`
);
} catch (err) {
window &&
window?.androidInteract?.log(
`error in onMsgSaveUpdate func:${JSON.stringify(err)}`
);
}
}
setMsgToStarred({});
setIsInLocal(false);
Expand Down Expand Up @@ -185,21 +117,6 @@ export const MessageItem: FC<any> = ({
}

localStorage.setItem("starredChats", JSON.stringify(valueToReturn));
try {
window &&
window?.androidInteract?.onMsgSaveUpdate(
JSON.stringify(valueToReturn)
);
window &&
window?.androidInteract?.log(
`new starred : ${JSON.stringify(valueToReturn)}`
);
} catch (err) {
window &&
window?.androidInteract?.log(
`error in onMsgSaveUpdate func:${JSON.stringify(err)}`
);
}
return valueToReturn;
});
}
Expand Down Expand Up @@ -248,18 +165,6 @@ export const MessageItem: FC<any> = ({
[handleSend]
);

const download = (url: string): void => {
try {
window && window?.androidInteract?.onImageDownload(url);
console.log("onImageDownload function executed");
} catch (err) {
console.log("onImageDownload function failed");
window &&
window?.androidInteract?.log(
`error in onImageDownload: ${JSON.stringify(err)}`
);
}
};

const { content, type } = msg;

Expand Down
84 changes: 84 additions & 0 deletions apps/uci/web/src/components/get-bot-list.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { getBotDetailsList } from "@/utils/api-handler";
import { normalizeUsers } from "@/utils/normalize-user";
import { reverse, sortBy, without } from "lodash";
import moment from "moment";
import { useEffect } from "react";
import { toast } from "react-hot-toast";
import { setUsers, setCurrentUser, setLoading } from "@/types/react-dispatch";

interface GetBotItemProp{
setUsers: setUsers,
setCurrentUser: setCurrentUser,
setLoading: setLoading
}


const GetBotList: React.FC<GetBotItemProp> = ({ setUsers, setCurrentUser, setLoading }) => {

useEffect(() => {
try {
const checkOnline = async (): Promise<void> => {
if (window.navigator.onLine) {

const botIds = JSON.parse(localStorage.getItem("botList") || '{}');
getBotDetailsList()
.then((response): any => {
console.log({ response })
const botDetailsList = without(
reverse(
sortBy(
response?.data?.result?.map((bot: any, index: number) => {
if (
// bot?.logicIDs?.[0]?.transformers?.[0]?.meta?.type !==
// "broadcast" &&
// includes(botIds, bot?.id)
true
) {
if (index === 0) localStorage.setItem('userID', bot?.id);
return normalizeUsers({
...bot,
active: index === 0,
botUuid: bot?.id,
createTime: moment(bot?.createdAt).valueOf(),
});
}
return null;
}),
["createTime"]
)
),
null
);


// @ts-ignore
setUsers(botDetailsList);
setLoading(false);

if (localStorage.getItem("currentUser")) {

// @ts-ignore
setCurrentUser(JSON.parse(localStorage.getItem("currentUser")));

// @ts-ignore
} else setCurrentUser(botDetailsList?.[0]);
})
.catch((err: any) => console.log("qwerty:", { err }));
} else {
setLoading(false);
if (localStorage.getItem("botDetails")) {
setUsers(JSON.parse(localStorage.getItem("botDetails") || '[]'));
setCurrentUser(JSON.parse(localStorage.getItem("botDetails") || '[]')?.[0]);
}
}
};
checkOnline();
} catch (err: any) {
toast.error(err?.message);
}
}, []);

return null;
}

export default GetBotList;
Loading