Skip to content

Commit

Permalink
feat: setup createAsyncThunk, added logger (#140)
Browse files Browse the repository at this point in the history
* Updated branch  (#129)

* to be edited

* Update .env.sample

* Update set-local-storage.ts

* fix: enhancement done for #126

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

* to be edited

* Update .env.sample

* Update set-local-storage.ts

* fix: enhancement done for #126

* style: layout modified to look similar like whatsapp (#132)

* Config for components
* env sample
* removed unnecessary config
* ui changes

* chore: revert ui changes

* Revert "style: layout modified to look similar like whatsapp (#132)" (#134)

This reverts commit fcbb545.

* chore: base setup

* refactor: added socket class  (#136)

* feat: added class for socket

* refactor: created socket

* chore: new socket class tested

* feat: using deployed socket package, added suppressHydrationWarning for extensions giving warning

* feat: added logger, setup store using createAsyncThunk

* change: reverted few changes

---------

Co-authored-by: Tushar Banik <[email protected]>
Co-authored-by: Saiyan Abhishek <[email protected]>
  • Loading branch information
3 people authored Aug 11, 2023
1 parent 83f47df commit 2970d5b
Show file tree
Hide file tree
Showing 37 changed files with 30,527 additions and 349 deletions.
1 change: 1 addition & 0 deletions apps/uci/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"autoprefixer": "10.4.14",
"axios": "^1.4.0",
"chatui": "*",
"socketclass": "*",
"framer-motion": "^10.12.10",
"lodash": "^4.17.21",
"moment": "^2.29.4",
Expand Down
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);

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;
37 changes: 3 additions & 34 deletions apps/uci/web/src/components/common/chat-ui-component/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,10 @@ export const ChatUiComponent: FC<{
useEffect(() => {
const phone = localStorage.getItem("mobile");
if (phone === "") toast.error("Mobile Number required");

console.log({context})
if (navigator.onLine) {
console.log("chatUi=>:",{navigator:navigator.onLine,conversationHistoryUrl})
if (conversationHistoryUrl && context?.socket?.connected) {
if (conversationHistoryUrl && context?.newSocket?.socket?.connected) {
axios
.get(conversationHistoryUrl)
.then((res) => {
Expand All @@ -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

0 comments on commit 2970d5b

Please sign in to comment.