shopify-chatbot-widget 0.0.4 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/jaweb-chatbot.css +1 -0
  2. package/dist/jaweb-chatbot.iife.js +685 -0
  3. package/dist/vite.svg +1 -0
  4. package/package.json +1 -1
  5. package/src/App.css +0 -42
  6. package/src/App.tsx +0 -13
  7. package/src/Chatbot/Chatbot.css +0 -154
  8. package/src/Chatbot/Chatbot.tsx +0 -207
  9. package/src/Chatbot/components/ChatInput.css +0 -127
  10. package/src/Chatbot/components/ChatInput.tsx +0 -262
  11. package/src/Chatbot/components/Messages/Addcart.tsx +0 -70
  12. package/src/Chatbot/components/Messages/AgentStatus.tsx +0 -37
  13. package/src/Chatbot/components/Messages/AssistantMesage.tsx +0 -316
  14. package/src/Chatbot/components/Messages/AudioMessage.tsx +0 -123
  15. package/src/Chatbot/components/Messages/CartWidget.tsx +0 -116
  16. package/src/Chatbot/components/Messages/ChatImage.tsx +0 -46
  17. package/src/Chatbot/components/Messages/ChatImageText.tsx +0 -74
  18. package/src/Chatbot/components/Messages/ChatImageTextAssis.tsx +0 -72
  19. package/src/Chatbot/components/Messages/ChatMessages.css +0 -5
  20. package/src/Chatbot/components/Messages/ChatMessages.tsx +0 -284
  21. package/src/Chatbot/components/Messages/Support.tsx +0 -177
  22. package/src/Chatbot/components/Messages/Typing.css +0 -27
  23. package/src/Chatbot/components/Messages/Typing.tsx +0 -14
  24. package/src/Chatbot/components/Messages/ZidAssistantMesage.tsx +0 -142
  25. package/src/Chatbot/components/Messenger/Messenger.tsx +0 -521
  26. package/src/Chatbot/components/Notification.tsx +0 -27
  27. package/src/Chatbot/components/Powered.css +0 -16
  28. package/src/Chatbot/components/Powered.tsx +0 -13
  29. package/src/Chatbot/components/Sessions/CreateSession.tsx +0 -139
  30. package/src/Chatbot/components/Sessions/RenderList.tsx +0 -202
  31. package/src/Chatbot/components/Suggestions.css +0 -34
  32. package/src/Chatbot/components/Suggestions.tsx +0 -28
  33. package/src/assets/react.svg +0 -1
  34. package/src/chatbot-widget/index.tsx +0 -14
  35. package/src/hooks/config.tsx +0 -13
  36. package/src/hooks/useCart.tsx +0 -99
  37. package/src/hooks/useChatbotAPI.tsx +0 -160
  38. package/src/hooks/useChatbotData.tsx +0 -129
  39. package/src/hooks/useSessionMessages.tsx +0 -51
  40. package/src/hooks/useWebsocke.tsx +0 -45
  41. package/src/i18n.tsx +0 -30
  42. package/src/index.css +0 -1
  43. package/src/main.tsx +0 -10
  44. package/src/types/chatbot.ts +0 -38
  45. package/src/utils/cookies.tsx +0 -14
  46. package/src/vite-env.d.ts +0 -1
@@ -1,202 +0,0 @@
1
- import React, { useEffect, useState } from 'react';
2
- import { List, Avatar, Typography, Button, Spin } from 'antd';
3
- import { UserOutlined, LoadingOutlined,CloseOutlined,WhatsAppOutlined } from '@ant-design/icons';
4
- import config from '../../../hooks/config';
5
- import { getCookie } from '../../../utils/cookies';
6
-
7
- const { Text, Title } = Typography;
8
-
9
- type ChatSession = {
10
- id: string;
11
- agentName?: string;
12
- createdAt: string;
13
- isBlurred?: boolean;
14
- agentImage?: string;
15
-
16
- };
17
-
18
- type ChatSessionsProps = {
19
- setOpen: (v: boolean) => void;
20
- Opened: boolean;
21
- Phone:string;
22
- chatbotLogo: string;
23
- colorCode?: string;
24
- onNewSession: () => void;
25
- visitorId: string;
26
- onSessionSelect: (sessionId: string,agentName:string,agentImage:string) => void;
27
-
28
- };
29
-
30
- const ChatSessions: React.FC<ChatSessionsProps> = ({ chatbotLogo, colorCode, onNewSession, visitorId ,onSessionSelect, setOpen,
31
- Opened,Phone}) => {
32
- const [sessions, setSessions] = useState<ChatSession[]>([]);
33
- const [loading, setLoading] = useState(true);
34
-
35
- const fetchSessions = async () => {
36
- try {
37
- setLoading(true);
38
- const res = await fetch(`${config.apiUrl}get-chatlogs-by-ip/?visitor_id=${visitorId}&company_username=${getCookie('company_username')}`);
39
- const data = await res.json();
40
- const mapped: ChatSession[] = data.map((item: any) => ({
41
- id: item.user_session_id,
42
- agentName: item.assignee || 'AI Agent',
43
- createdAt: item.date,
44
- isBlurred: item.closed,
45
- agentImage:item.assignee_picture
46
- }));
47
- setSessions(mapped);
48
-
49
-
50
- } catch (err) {
51
- console.error('Failed to load sessions:', err);
52
- } finally {
53
- setLoading(false);
54
- }
55
- };
56
-
57
- useEffect(() => {
58
- if (visitorId) {
59
- fetchSessions();
60
- }
61
- }, [visitorId]);
62
-
63
- const loadingIcon = <LoadingOutlined style={{ fontSize: 24 }} spin />;
64
-
65
- // const canCreateNewSession =
66
- // sessions.length === 0 ||
67
- // sessions[sessions.length - 1].isBlurred === true;
68
-
69
-
70
- return (
71
- <div
72
- style={{
73
- maxWidth: '100%',
74
- height: '100%',
75
- border: '1px solid #f0f0f0',
76
- borderRadius: 8,
77
- overflow: 'hidden',
78
- display: 'flex',
79
- flexDirection: 'column',
80
- paddingTop: 20,
81
- }}
82
- >
83
- <div style={{ padding: '0 16px 10px', display:'flex' }}>
84
- <Title level={4} style={{ margin: 0 }}>
85
- Conversations
86
- </Title>
87
-
88
-
89
- <CloseOutlined
90
- onClick={() => setOpen(!Opened)}
91
- className="chatbot-close"
92
- style={{ marginLeft: 'auto' }}
93
- />
94
- </div>
95
-
96
-
97
- <div style={{ flex: 1, overflowY: 'auto' }}>
98
- {loading ? (
99
- <div style={{ textAlign: 'center', padding: '2rem' }}>
100
- <Spin indicator={loadingIcon} />
101
- </div>
102
- ) : sessions.length > 0 ? (
103
- <List
104
- itemLayout="horizontal"
105
- dataSource={sessions}
106
- split={true}
107
- renderItem={(session) => (
108
- <List.Item
109
- key={session.id}
110
- onClick={() => !session.isBlurred && onSessionSelect(session.id,session.agentName||'Ai Agent',session.agentImage||chatbotLogo)} // ✅ Click logic
111
- style={{
112
- padding: '12px',
113
- opacity: session.isBlurred ? 0.5 : 1,
114
- cursor: session.isBlurred ? 'not-allowed' : 'pointer',
115
- borderBottom: '1px solid #f0f0f0',
116
- }}
117
- >
118
- <List.Item.Meta
119
- avatar={
120
- <Avatar
121
- size="large"
122
- src={session.agentImage || chatbotLogo}
123
- icon={!session.agentImage && !chatbotLogo ? <UserOutlined /> : undefined}
124
- />
125
- }
126
- title={
127
- <span style={{ fontWeight: 600 }}>
128
- {session.agentName || 'AI Agent'}
129
- </span>
130
- }
131
- description={
132
- <>
133
- <Text type="secondary">
134
- Created: {new Date(session.createdAt).toLocaleDateString()}
135
- </Text>
136
- {session.isBlurred && (
137
- <div style={{ color: 'red', fontSize: '12px', marginTop: 4 }}>
138
- This session is closed and cannot be reopened.
139
- </div>
140
- )}
141
- </>
142
- }
143
- />
144
- </List.Item>
145
- )}
146
- />
147
-
148
- ) : (
149
- <div style={{ padding: '1rem', textAlign: 'center', color: '#888' }}>
150
- No conversations yet.
151
- </div>
152
- )}
153
- </div>
154
-
155
-
156
- <div style={{ padding: '12px', borderTop: '1px solid #f0f0f0',display:'flex',gap:4 }}>
157
- <Button
158
- type="primary"
159
- size="large"
160
- block
161
- style={{
162
- backgroundColor: colorCode,
163
- color: '#fff',
164
- }}
165
- onClick={onNewSession}
166
- >
167
- Ask a question ?
168
- </Button>
169
-
170
- {Phone?
171
- (
172
- <Button
173
- type="default"
174
- style={{
175
- backgroundColor: 'white',
176
- color: colorCode,
177
- }}
178
- className='hover:border-black'
179
- size="large"
180
- icon={<WhatsAppOutlined style={{color:colorCode}}/>}
181
- onClick={() => {
182
- const waLink = `https://wa.me/${Phone}`;
183
- window.open(waLink, '_blank');
184
- }}
185
- >
186
- Chat on WhatsApp
187
- </Button>
188
-
189
- ):(
190
- <></>
191
- )
192
- }
193
-
194
-
195
- </div>
196
-
197
-
198
- </div>
199
- );
200
- };
201
-
202
- export default ChatSessions;
@@ -1,34 +0,0 @@
1
- /* Suggestions.css */
2
- .suggestions-wrapper {
3
- overflow-x: auto;
4
- overflow-y: hidden;
5
- white-space: nowrap;
6
- padding-top: 4px;
7
- padding-bottom: 8px;
8
- width: 100%; /* ensures it respects screen boundaries */
9
- box-sizing: border-box;
10
- margin-left: 4%;
11
- margin-top: 4px;
12
-
13
- }
14
-
15
- .suggestions-scroll {
16
- display: inline-flex; /* horizontal scroll with inline behavior */
17
- gap: 0.5rem;
18
- }
19
-
20
- .suggestion-button {
21
- white-space: nowrap;
22
- padding: 0.5rem 1rem;
23
- border: 1px solid #ccc;
24
- border-radius: 9999px;
25
- background-color: white;
26
- cursor: pointer;
27
- font-size: 0.9rem;
28
- flex-shrink: 0; /* prevents shrinking inside flex */
29
- }
30
-
31
- .suggestion-button:hover {
32
- background-color: #f3f3f3;
33
- }
34
-
@@ -1,28 +0,0 @@
1
- // Suggestions.tsx
2
- import './Suggestions.css';
3
-
4
- interface SuggestionsProps {
5
- suggestions: string[];
6
- colorCode:string;
7
- sendMessageSuggestion: (message: string) => Promise<void>;
8
- }
9
-
10
- export default function Suggestions({ suggestions,colorCode,sendMessageSuggestion }: SuggestionsProps) {
11
-
12
- return (
13
- <div className="suggestions-wrapper">
14
- <div className="suggestions-scroll">
15
- {suggestions?.map((text, index) => (
16
- <button
17
- key={index}
18
- className="suggestion-button"
19
- style={{ borderColor: colorCode, color: colorCode }}
20
- onClick={() => sendMessageSuggestion(text)}
21
- >
22
- {text}
23
- </button>
24
- ))}
25
- </div>
26
- </div>
27
- );
28
- }
@@ -1 +0,0 @@
1
- <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
@@ -1,14 +0,0 @@
1
- import ReactDOM from 'react-dom/client';
2
- import Chatbot from '../Chatbot/Chatbot';
3
- import 'antd/dist/reset.css'; // AntD global styles
4
- import '../index.css'
5
-
6
- const containerId = 'jaweb-chatbot-container';
7
-
8
- if (!document.getElementById(containerId)) {
9
- const container = document.createElement('div');
10
- container.id = containerId;
11
- document.body.appendChild(container);
12
-
13
- ReactDOM.createRoot(container).render(<Chatbot />);
14
- }
@@ -1,13 +0,0 @@
1
-
2
-
3
- const config = {
4
- // apiUrl:'https://jawebcrm.onrender.com/api/',
5
- // websocketUrl:'wss://jawebcrm.onrender.com/ws' ,
6
-
7
- apiUrl:'http://localhost:8000/api/',
8
- websocketUrl:'ws://localhost:8000/ws',
9
-
10
- };
11
- export default config;
12
-
13
-
@@ -1,99 +0,0 @@
1
- import { useState, useEffect, useCallback } from 'react';
2
- import config from './config';
3
-
4
- export interface CartItem {
5
- variantId: string;
6
- name: string;
7
- quantity: number;
8
- }
9
-
10
- export function useCart(sessionId: string) {
11
- const [items, setItems] = useState<CartItem[]>([]);
12
- const [loading, setLoading] = useState(false);
13
-
14
- const fetchCart = useCallback(async () => {
15
- if (!sessionId) return;
16
-
17
- setLoading(true);
18
- try {
19
- const res = await fetch(`${config.apiUrl}cart?session_id=${sessionId}`);
20
- const json = await res.json();
21
- setItems(json.items || []);
22
- } catch (err) {
23
- console.error('Failed to fetch cart', err);
24
- } finally {
25
- setLoading(false);
26
- }
27
- }, [sessionId]);
28
-
29
- const addToCart = async (variantId: string, name: string, qty: number) => {
30
- if (!sessionId) return;
31
-
32
- // Optimistic update
33
- setItems(current => {
34
- const found = current.find(i => i.variantId === variantId);
35
- if (found) {
36
- return current.map(i =>
37
- i.variantId === variantId
38
- ? { ...i, quantity: i.quantity + qty }
39
- : i
40
- );
41
- }
42
- return [...current, { variantId, name, quantity: qty }];
43
- });
44
-
45
- try {
46
- await fetch(`${config.apiUrl}cart/add/`, {
47
- method: 'POST',
48
- headers: { 'Content-Type': 'application/json' },
49
- body: JSON.stringify({
50
- session_id: sessionId,
51
- variantId,
52
- name,
53
- quantity: qty,
54
- }),
55
- });
56
- } catch (err) {
57
- console.error('Failed to sync addToCart to server', err);
58
- }
59
-
60
- await fetchCart(); // reconcile server data
61
- };
62
-
63
- const removeFromCart = async (variantId: string, qty: number) => {
64
- if (!sessionId) return;
65
-
66
- // Optimistic update
67
- setItems(current =>
68
- current
69
- .map(i =>
70
- i.variantId === variantId
71
- ? { ...i, quantity: i.quantity - qty }
72
- : i
73
- )
74
- .filter(i => i.quantity > 0)
75
- );
76
-
77
- try {
78
- await fetch(`${config.apiUrl}cart/remove/`, {
79
- method: 'POST',
80
- headers: { 'Content-Type': 'application/json' },
81
- body: JSON.stringify({
82
- session_id: sessionId,
83
- variantId,
84
- quantity: qty,
85
- }),
86
- });
87
- } catch (err) {
88
- console.error('Failed to sync removeFromCart to server', err);
89
- }
90
-
91
- await fetchCart(); // reconcile server data
92
- };
93
-
94
- useEffect(() => {
95
- fetchCart();
96
- }, [fetchCart]);
97
-
98
- return { items, loading, addToCart, removeFromCart, refresh: fetchCart };
99
- }
@@ -1,160 +0,0 @@
1
- import { useCallback } from 'react';
2
- import { getCookie } from '../utils/cookies';
3
- import config from './config';
4
-
5
- interface Params {
6
- disableChatbot: boolean;
7
- disableChatbotGlobally: boolean;
8
- isChatlogCreated: boolean;
9
- createNew: boolean;
10
- disableForm: boolean;
11
- calendlyLink: string | null;
12
- socket: WebSocket | null;
13
- newSession:Boolean;
14
- setNewSession: (v: boolean) => void;
15
- setMessages: React.Dispatch<React.SetStateAction<any[]>>;
16
- setIsChatlogCreated: (v: boolean) => void;
17
- setChatLogWaiting: (v: boolean) => void;
18
- setNewUser: (v: boolean) => void;
19
- setCreateNew: (v: boolean) => void;
20
- setSessionCreated: (v: boolean) => void;
21
- }
22
-
23
- export const useChatbotAPI = (params: Params) => {
24
- const {
25
- disableChatbot,
26
- disableChatbotGlobally,
27
- isChatlogCreated,
28
- createNew,
29
- disableForm,
30
- calendlyLink,
31
- socket,
32
- newSession,
33
- setNewSession,
34
- setMessages,
35
- } = params;
36
-
37
- const apiCall = useCallback(
38
- async (
39
- userMessage: string,
40
- newSession:boolean,
41
- sessionId: string,
42
- finalImageUrl?: string,
43
- isImage?: boolean
44
- ) => {
45
- if (newSession) {
46
- await fetch(`${config.apiUrl}chatlog-create/`, {
47
- method: 'POST',
48
- headers: { 'Content-Type': 'application/json' },
49
- body: JSON.stringify({ visitor_id: localStorage.getItem('visitor_id') , company_username: getCookie('company_username'),session_id:sessionId}),
50
- });
51
-
52
- setNewSession(false)
53
-
54
- }
55
-
56
- if (!disableChatbot && !disableChatbotGlobally) {
57
- setMessages((prev) => [
58
- ...prev,
59
- { role: 'assistant', content: 'typing', typing: true },
60
- ]);
61
- }
62
-
63
- try {
64
- const res = await fetch(`${config.apiUrl}message-create/`, {
65
- method: 'POST',
66
- headers: { 'Content-Type': 'application/json' },
67
- body: JSON.stringify({
68
- message: userMessage,
69
- isBusiness: true,
70
- session_id: sessionId,
71
- organization: getCookie('company_username'),
72
- isImage,
73
- image_url: finalImageUrl,
74
- }),
75
- });
76
-
77
- if (res.ok) {
78
- const data = await res.json();
79
-
80
- if (data.message_history) {
81
- const assistantMessage = data.isConnect
82
- ? {
83
- role: 'assistant',
84
- content: 'Your support request is on its way—please stand by!',
85
- isConnect: true,
86
- sender: 'Ai Agent',
87
- isBusiness: false,
88
- isHtml: data.isHtml,
89
- }
90
- : {
91
- role: 'assistant',
92
- content: data.message,
93
- sender: 'Ai Agent',
94
- isBusiness: false,
95
- isHtml: data.isHtml,
96
- };
97
-
98
- // Send message through WebSocket if available
99
- if (socket?.readyState === WebSocket.OPEN) {
100
- socket.send(
101
- JSON.stringify({
102
- message: data.message,
103
- additionalData: {
104
- isBusiness: false,
105
- SessionId: sessionId,
106
- sender: 'AI',
107
- response: 'from_ai_web',
108
- },
109
- })
110
- );
111
- }
112
-
113
-
114
- // Update messages safely
115
- setMessages((prev) => {
116
- const filtered = prev.filter((msg) => !msg.typing);
117
- const updated = [...filtered, assistantMessage];
118
-
119
- // Add Calendly message if applicable
120
- if (
121
- data.message &&
122
- calendlyLink &&
123
- /book\s?(a\s?)?meeting|schedule\s?(a\s?)?(call|meeting)|let\s?('s)?\s?meet|set\s?up\s?(a\s?)?meeting|book\s?(an\s?)?appointment/i.test(
124
- data.message
125
- )
126
- ) {
127
- updated.push({
128
- role: 'assistant',
129
- content: 'Scheduling a meeting...',
130
- isBusiness: false,
131
- callCalendly: true,
132
- });
133
- }
134
-
135
- return updated;
136
- });
137
- } else if (data.status === 'success') {
138
- setMessages((prev) => prev.filter((msg) => !msg.typing));
139
- }
140
- } else {
141
- console.error('message-create failed');
142
- }
143
- } catch (error) {
144
- console.error('Message error:', error);
145
- }
146
- },
147
- [
148
- disableChatbot,
149
- disableChatbotGlobally,
150
- isChatlogCreated,
151
- createNew,
152
- disableForm,
153
- calendlyLink,
154
- socket,
155
- newSession,
156
- ]
157
- );
158
-
159
- return { apiCall };
160
- };
@@ -1,129 +0,0 @@
1
- // hooks/useChatbotData.ts
2
- import { useEffect, useState } from 'react';
3
- import axios from 'axios';
4
- import { getCookie } from '../utils/cookies';
5
- import config from './config';
6
- import i18n from '../i18n';
7
- import type { ChatbotDetailsResponse, SuggestionResponse } from '../types/chatbot';
8
-
9
-
10
- const MAX_RETRIES = 3;
11
- const RETRY_DELAY = 3000;
12
-
13
- export const useChatbotData = () => {
14
-
15
- const [isFetchingDetails, setIsFetchingDetails] = useState(true);
16
- const [disableForm, setDisableForm] = useState(false);
17
- const [colorCode, setColorCode] = useState('');
18
- const [chatbotLogo, setChatbotLogo] = useState('');
19
- const [disableChatbotGlobally, setDisableChatbotGlobally] = useState(false);
20
- const [removePoweredByJaweb, setRemovePoweredByJaweb] = useState(false);
21
- const [initialMessageText, setInitialMessageText] = useState('');
22
- const [subscription, setSubscription] = useState('');
23
- const [calendly, setCalendly] = useState('');
24
- const [merchantPhone, setMerchantPhone] = useState('');
25
- const [messagesSuggestions, setMessagesSuggestions] = useState<string[]>([]);
26
- const [restSuggestions, setRestSuggestions] = useState<string[]>([]);
27
- const [userType,setUserType]=useState('')
28
-
29
- const fetchData = async (retryCount = 0) => {
30
- const company_name = getCookie('company_username');
31
- setIsFetchingDetails(true);
32
-
33
- const configObj = {
34
- headers: {
35
- 'Content-Type': 'application/json',
36
- Accept: 'application/json',
37
- },
38
- params: {
39
- username: company_name,
40
- },
41
- };
42
-
43
- try {
44
- const chatbotDetailsResponse = await axios.get<ChatbotDetailsResponse>(
45
- `${config.apiUrl}chatbot-details/`,
46
- configObj
47
- );
48
-
49
- const data = chatbotDetailsResponse.data.data;
50
-
51
- if (data.language === 'Arabic') {
52
- i18n.changeLanguage('ar');
53
- } else {
54
- i18n.changeLanguage('en');
55
- }
56
-
57
-
58
-
59
- setDisableForm(data.chatbot_form);
60
- setColorCode(data.chatbot_color);
61
- setChatbotLogo(data.chatbot_logo);
62
- setDisableChatbotGlobally(data.disable_chatbot_globally);
63
- setRemovePoweredByJaweb(data.remove_powered_by_jaweb);
64
- setInitialMessageText(data.chatbot_initial_msg);
65
- setSubscription(data.status);
66
- setUserType(data.mode)
67
-
68
- console.log(data)
69
-
70
-
71
- if (data.calendly_link) setCalendly(data.calendly_link);
72
- if (data.phone_number_id) setMerchantPhone(`+${data.phone_number_id}`);
73
-
74
- const suggestionsResponse = await axios.get<SuggestionResponse>(
75
- `${config.apiUrl}chatbot-plugin-suggestions/`,
76
- configObj
77
- );
78
-
79
-
80
- // 💡 Safe fallback logic
81
- let suggestions: string[] = [];
82
-
83
- if (Array.isArray(suggestionsResponse.data.data)) {
84
- suggestions = suggestionsResponse.data.data;
85
- } else if (Array.isArray((suggestionsResponse.data as any).user_questions)) {
86
- suggestions = (suggestionsResponse.data as any).user_questions;
87
- }
88
-
89
- if (suggestions.length > 0) {
90
- setMessagesSuggestions(suggestions.slice(0, 3));
91
- setRestSuggestions(suggestions.slice(3));
92
- } else {
93
- setMessagesSuggestions([]);
94
- setRestSuggestions([]);
95
- }
96
-
97
- setIsFetchingDetails(false);
98
- } catch (error) {
99
- console.error('Error fetching data:', error);
100
- if (retryCount < MAX_RETRIES) {
101
- setTimeout(() => fetchData(retryCount + 1), RETRY_DELAY);
102
- } else {
103
- console.error('Max retries reached. Could not fetch data.');
104
- }
105
- }
106
- };
107
-
108
-
109
-
110
- useEffect(() => {
111
- fetchData();
112
- }, []);
113
-
114
- return {
115
- isFetchingDetails,
116
- disableForm,
117
- colorCode,
118
- chatbotLogo,
119
- disableChatbotGlobally,
120
- removePoweredByJaweb,
121
- initialMessageText,
122
- subscription,
123
- calendly,
124
- merchantPhone,
125
- messagesSuggestions,
126
- restSuggestions,
127
- userType
128
- };
129
- };