KyleAIers commited on
Commit
941b548
·
verified ·
1 Parent(s): 95b75c3

Update index.html

Browse files
Files changed (1) hide show
  1. index.html +65 -115
index.html CHANGED
@@ -5,12 +5,10 @@
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
  <title>HealthyLifePhil Assistant</title>
7
 
8
- <!-- UMD React Dependencies -->
9
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
10
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
11
  <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.23.5/babel.min.js"></script>
12
-
13
- <!-- Styling & Supabase -->
14
  <script src="https://cdn.tailwindcss.com"></script>
15
  <script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
16
  </head>
@@ -18,9 +16,8 @@
18
  <div id="root"></div>
19
 
20
  <script type="text/babel">
21
- const { useState, useEffect } = React;
22
 
23
- // Supabase Initialization
24
  const SUPABASE_URL = "https://ixntxgqaggkaaekewazu.supabase.co";
25
  const SUPABASE_ANON_KEY = "sb_publishable_7SZ_z5FKbA77vZ04rnJKGQ_zXssCIT0";
26
  const supabase = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
@@ -29,37 +26,24 @@
29
  const validateGuardrails = (text) => {
30
  const exploitPattern = /(drop\s+table|delete\s+from|select\s+\*|insert\s+into|alter\s+table|union\s+select|<script>|javascript:|eval\(|or\s+1=1|--|\/\*)/i;
31
  if (exploitPattern.test(text)) {
32
- return { blocked: true, reason: "🛡️ [Security Guardrail]: Query blocked due to forbidden database operations." };
33
- }
34
-
35
- const forbiddenTerms = ['hack', 'h4ck', 'exploit', 'scam', 'steal', 'bypass', 'jailbreak', 'attack', 'payload'];
36
- const normalized = text.toLowerCase().replace(/[^a-z0-9\s]/g, '');
37
- const words = normalized.split(/\s+/);
38
- if (forbiddenTerms.some(term => words.some(w => w.includes(term)))) {
39
- return { blocked: true, reason: "🛡️ [Security Guardrail]: System limited strictly to store management requests." };
40
  }
41
-
42
  return { blocked: false };
43
  };
44
 
45
- // Intent Router with Reasoning Detection
46
  const analyzeUserIntent = (text) => {
47
  const lower = text.toLowerCase().trim();
48
-
49
- const analysisKeywords = ['why', 'explain', 'reason', 'how come', 'analyze', 'what happened', 'issue', 'details', 'that', 'those'];
50
- const requiresReasoning = analysisKeywords.some(k => lower.includes(k));
51
-
52
- const hasInventory = ['inventory', 'stock', 'items', 'products', 'units'].some(k => lower.includes(k));
53
- const hasSales = ['sales', 'revenue', 'orders', 'earnings', 'performance'].some(k => lower.includes(k));
54
-
55
- if (requiresReasoning) {
56
- return { type: 'REASONING', domain: hasSales ? 'SALES' : 'INVENTORY' };
57
- }
58
 
59
- if (hasInventory) return { type: 'FETCH_DATA', domain: 'INVENTORY' };
60
- if (hasSales) return { type: 'FETCH_DATA', domain: 'SALES' };
 
 
 
61
 
62
- return { type: 'CHAT', domain: null };
 
 
63
  };
64
 
65
  // Card Renderer Component
@@ -67,7 +51,7 @@
67
  if (data.type === 'inventory') {
68
  return (
69
  <div className="space-y-3">
70
- <p className="text-slate-200">Current store inventory details:</p>
71
  <div className="grid grid-cols-2 gap-2 text-xs">
72
  <div className="bg-slate-900 p-2.5 rounded-lg border border-slate-700">
73
  <span className="text-slate-400 block">Product Lines</span>
@@ -81,16 +65,12 @@
81
 
82
  <div className="bg-slate-900 rounded-lg p-3 border border-slate-700 space-y-1 text-xs">
83
  <div className="font-semibold text-slate-300 mb-1">Items List</div>
84
- {data.products.length === 0 ? (
85
- <p className="text-slate-500">No products found in database.</p>
86
- ) : (
87
- data.products.map(p => (
88
- <div key={p.id || p.product_name} className="flex justify-between py-1 border-b border-slate-800 last:border-0">
89
- <span>{p.product_name}</span>
90
- <span className="text-slate-400">{p.stock_quantity} in stock (₱{p.price})</span>
91
- </div>
92
- ))
93
- )}
94
  </div>
95
  </div>
96
  );
@@ -121,120 +101,94 @@
121
  return null;
122
  };
123
 
124
- // Main App Component
125
  function App() {
126
- const [sessionId] = useState(() => 'session_' + Math.random().toString(36).substring(2, 9));
127
  const [messages, setMessages] = useState([
128
- { sender: "bot", type: "text", text: "HealthyLifePhil Assistant Active. Ask about inventory, sales metrics, or chat." }
129
  ]);
130
  const [input, setInput] = useState("");
131
  const [loading, setLoading] = useState(false);
132
 
133
- // Save log entry to Supabase DB for long-term memory / audit
134
- const logMessageToDatabase = async (sender, messageText) => {
135
- try {
136
- await supabase.from('chat_logs').insert([
137
- { session_id: sessionId, sender: sender, message: messageText }
138
- ]);
139
- } catch (e) {
140
- console.warn("Chat log database table not ready:", e);
141
  }
142
- };
143
 
144
- // Helper to build context window from recent chat history
145
- const getRecentConversationContext = (history) => {
146
- return history.slice(-4).map(m =>
147
- `${m.sender === 'user' ? 'User' : 'Assistant'}: ${m.type === 'data' ? '[Displayed Data Card]' : m.text}`
148
- ).join('\n');
 
 
 
 
 
 
 
 
149
  };
150
 
151
  const handleChat = async () => {
152
  if (!input.trim() || loading) return;
153
 
154
  const userText = input.trim();
155
- const updatedMessages = [...messages, { sender: "user", type: "text", text: userText }];
156
- setMessages(updatedMessages);
157
  setInput("");
158
  setLoading(true);
159
 
160
- logMessageToDatabase('user', userText);
161
-
162
  try {
163
  // 1. Guardrail Check
164
  const guardrail = validateGuardrails(userText);
165
  if (guardrail.blocked) {
166
  setMessages(prev => [...prev, { sender: "bot", type: "text", text: guardrail.reason }]);
167
- logMessageToDatabase('bot', guardrail.reason);
168
  setLoading(false);
169
  return;
170
  }
171
 
172
- // 2. Intent Analysis
173
  const intent = analyzeUserIntent(userText);
174
 
175
- // Standard Card Trigger
176
- if (intent.type === 'FETCH_DATA' && intent.domain === 'INVENTORY') {
177
- const { data: products, error } = await supabase.from('products').select('*');
178
- if (error) throw error;
179
-
180
  const totalUnits = products ? products.reduce((acc, p) => acc + Number(p.stock_quantity || 0), 0) : 0;
181
- const dataCardPayload = { type: 'inventory', productCount: products ? products.length : 0, totalUnits, products: products || [] };
182
 
183
- setMessages(prev => [...prev, { sender: "bot", type: "data", data: dataCardPayload }]);
184
- logMessageToDatabase('bot', '[Inventory Data Card Generated]');
 
 
 
185
  setLoading(false);
186
  return;
187
  }
188
 
189
- if (intent.type === 'FETCH_DATA' && intent.domain === 'SALES') {
190
- const { data: sales, error } = await supabase.from('orders').select('*');
191
- if (error) throw error;
192
-
193
  const totalRev = sales ? sales.reduce((acc, i) => acc + Number(i.total_amount || 0), 0) : 0;
194
  const totalOrders = sales ? sales.length : 0;
195
  const avgOrder = totalOrders > 0 ? (totalRev / totalOrders) : 0;
196
- const salesCardPayload = { type: 'sales', totalRev, totalOrders, avgOrder };
197
 
198
- setMessages(prev => [...prev, { sender: "bot", type: "data", data: salesCardPayload }]);
199
- logMessageToDatabase('bot', '[Sales Data Card Generated]');
 
 
 
200
  setLoading(false);
201
  return;
202
  }
203
 
204
- // Reasoning Request (Context Memory + DB Ingestion)
205
- if (intent.type === 'REASONING') {
206
- const { data: products } = await supabase.from('products').select('*');
207
-
208
- const lowStockItems = products ? products.filter(p => p.stock_quantity < 20) : [];
209
- const lowStockNames = lowStockItems.map(p => `${p.product_name} (${p.stock_quantity} left)`).join(', ');
210
-
211
- const recentHistory = getRecentConversationContext(updatedMessages);
212
-
213
- let explanation = "";
214
- if (userText.toLowerCase().includes('why') || userText.toLowerCase().includes('like that')) {
215
- explanation = lowStockItems.length > 0
216
- ? `Analyzing your store database, your total stock is 228 units across 4 lines. However, low inventory levels in specific items are pulling down performance: ${lowStockNames}. Pure Herbal Green Tea and Cold-Pressed Coconut Oil need urgent restocking.`
217
- : `Your inventory levels are balanced across all product lines with a total of 228 units in stock. No critical shortages were detected.`;
218
- } else {
219
- explanation = `Based on our previous exchange:\n${recentHistory}\n\nOur current inventory across all 4 products totals 228 units. Pure Herbal Green Tea (15 left) and Cold-Pressed Coconut Oil (8 left) are running critically low.`;
220
- }
221
-
222
- setMessages(prev => [...prev, { sender: "bot", type: "text", text: explanation }]);
223
- logMessageToDatabase('bot', explanation);
224
- setLoading(false);
225
- return;
226
- }
227
-
228
- // Default Chat Response
229
- const defaultReply = "I am ready to help manage your store. Ask me to show inventory, view sales metrics, or explain stock alerts.";
230
- setMessages(prev => [...prev, { sender: "bot", type: "text", text: defaultReply }]);
231
- logMessageToDatabase('bot', defaultReply);
232
 
233
  } catch (err) {
234
  console.error(err);
235
- const errorMsg = "Database connection failed. Please try again.";
236
- setMessages(prev => [...prev, { sender: "bot", type: "text", text: errorMsg }]);
237
- logMessageToDatabase('bot', errorMsg);
238
  } finally {
239
  setLoading(false);
240
  }
@@ -245,10 +199,7 @@
245
  <div className="w-64 bg-slate-900 p-4 border-r border-slate-800 flex flex-col justify-between hidden md:flex">
246
  <div>
247
  <h1 className="text-md font-bold text-white mb-2">HealthyLifePhil</h1>
248
- <p className="text-xs text-slate-400 mb-4">Memory & Reasoning Active</p>
249
- <div className="bg-slate-950 p-2.5 rounded border border-slate-800 text-[10px] text-slate-400 font-mono">
250
- Session ID: {sessionId}
251
- </div>
252
  </div>
253
  <div className="text-xs text-emerald-400">● Engine Active</div>
254
  </div>
@@ -266,7 +217,7 @@
266
  </div>
267
  </div>
268
  ))}
269
- {loading && <div className="text-xs text-emerald-400 italic animate-pulse">Analyzing store context & history...</div>}
270
  </div>
271
 
272
  <div className="p-4 bg-slate-900 border-t border-slate-800 flex gap-2">
@@ -278,7 +229,7 @@
278
  onChange={(e) => setInput(e.target.value)}
279
  onKeyDown={(e) => e.key === 'Enter' && handleChat()}
280
  />
281
- <button onClick={handleChat} disabled={loading} className="bg-emerald-600 hover:bg-emerald-500 px-5 py-2 rounded-lg font-bold text-sm text-black font-semibold">
282
  Send
283
  </button>
284
  </div>
@@ -287,7 +238,6 @@
287
  );
288
  }
289
 
290
- // Mount React App
291
  const rootElement = document.getElementById('root');
292
  const root = ReactDOM.createRoot(rootElement);
293
  root.render(<App />);
 
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
  <title>HealthyLifePhil Assistant</title>
7
 
8
+ <!-- React & Dependencies -->
9
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
10
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
11
  <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.23.5/babel.min.js"></script>
 
 
12
  <script src="https://cdn.tailwindcss.com"></script>
13
  <script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
14
  </head>
 
16
  <div id="root"></div>
17
 
18
  <script type="text/babel">
19
+ const { useState } = React;
20
 
 
21
  const SUPABASE_URL = "https://ixntxgqaggkaaekewazu.supabase.co";
22
  const SUPABASE_ANON_KEY = "sb_publishable_7SZ_z5FKbA77vZ04rnJKGQ_zXssCIT0";
23
  const supabase = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
 
26
  const validateGuardrails = (text) => {
27
  const exploitPattern = /(drop\s+table|delete\s+from|select\s+\*|insert\s+into|alter\s+table|union\s+select|<script>|javascript:|eval\(|or\s+1=1|--|\/\*)/i;
28
  if (exploitPattern.test(text)) {
29
+ return { blocked: true, reason: "🛡️ [Security Violation]: Database manipulation commands are restricted." };
 
 
 
 
 
 
 
30
  }
 
31
  return { blocked: false };
32
  };
33
 
34
+ // Intent Router
35
  const analyzeUserIntent = (text) => {
36
  const lower = text.toLowerCase().trim();
 
 
 
 
 
 
 
 
 
 
37
 
38
+ const invTerms = ['inventory', 'stock', 'product', 'items', 'supplies', 'units'];
39
+ const salesTerms = ['sales', 'revenue', 'orders', 'earnings', 'performance', 'stat'];
40
+
41
+ const isExplicitInv = invTerms.some(term => lower.includes(term));
42
+ const isExplicitSales = salesTerms.some(term => lower.includes(term));
43
 
44
+ if (isExplicitInv) return 'INVENTORY';
45
+ if (isExplicitSales) return 'SALES';
46
+ return 'CHAT';
47
  };
48
 
49
  // Card Renderer Component
 
51
  if (data.type === 'inventory') {
52
  return (
53
  <div className="space-y-3">
54
+ <p className="text-slate-200">Current store inventory status:</p>
55
  <div className="grid grid-cols-2 gap-2 text-xs">
56
  <div className="bg-slate-900 p-2.5 rounded-lg border border-slate-700">
57
  <span className="text-slate-400 block">Product Lines</span>
 
65
 
66
  <div className="bg-slate-900 rounded-lg p-3 border border-slate-700 space-y-1 text-xs">
67
  <div className="font-semibold text-slate-300 mb-1">Items List</div>
68
+ {data.products.map(p => (
69
+ <div key={p.id || p.product_name} className="flex justify-between py-1 border-b border-slate-800 last:border-0">
70
+ <span>{p.product_name}</span>
71
+ <span className="text-slate-400">{p.stock_quantity} in stock (₱{p.price})</span>
72
+ </div>
73
+ ))}
 
 
 
 
74
  </div>
75
  </div>
76
  );
 
101
  return null;
102
  };
103
 
 
104
  function App() {
 
105
  const [messages, setMessages] = useState([
106
+ { sender: "bot", type: "text", text: "Hey! HealthyLifePhil Assistant here. What can I do for you today?" }
107
  ]);
108
  const [input, setInput] = useState("");
109
  const [loading, setLoading] = useState(false);
110
 
111
+ const generateConversationalReply = (userText, history) => {
112
+ const lower = userText.toLowerCase().trim();
113
+ const lastBotMessage = history.filter(m => m.sender === 'bot').slice(-1)[0]?.text || "";
114
+
115
+ if (lower === "okay" || lower === "ok" || lower === "alright") {
116
+ return "Got it! Let me know whenever you want to check database numbers or look into specific items.";
 
 
117
  }
 
118
 
119
+ if (lower === "what" || lower === "what do you mean" || lower === "huh") {
120
+ return `I was referring to: "${lastBotMessage}". You can ask me conversational questions or have me pull live data for sales and stock levels.`;
121
+ }
122
+
123
+ if (lower.includes("hello") || lower.includes("hi") || lower.includes("hey")) {
124
+ return "Hey there! How's your day going? Need any help with store operations?";
125
+ }
126
+
127
+ if (lower.includes("who are you") || lower.includes("what can you do")) {
128
+ return "I'm your store assistant for HealthyLifePhil! I can chat casually or query live inventory and financial metrics directly from Supabase.";
129
+ }
130
+
131
+ return `I'm here! You can talk to me naturally, or ask specific technical queries like "check inventory" or "show sales performance".`;
132
  };
133
 
134
  const handleChat = async () => {
135
  if (!input.trim() || loading) return;
136
 
137
  const userText = input.trim();
138
+ const updatedHistory = [...messages, { sender: "user", type: "text", text: userText }];
139
+ setMessages(updatedHistory);
140
  setInput("");
141
  setLoading(true);
142
 
 
 
143
  try {
144
  // 1. Guardrail Check
145
  const guardrail = validateGuardrails(userText);
146
  if (guardrail.blocked) {
147
  setMessages(prev => [...prev, { sender: "bot", type: "text", text: guardrail.reason }]);
 
148
  setLoading(false);
149
  return;
150
  }
151
 
152
+ // 2. Intent Router
153
  const intent = analyzeUserIntent(userText);
154
 
155
+ // Technical Data Query: Inventory
156
+ if (intent === 'INVENTORY') {
157
+ const { data: products } = await supabase.from('products').select('*');
 
 
158
  const totalUnits = products ? products.reduce((acc, p) => acc + Number(p.stock_quantity || 0), 0) : 0;
 
159
 
160
+ setMessages(prev => [...prev, {
161
+ sender: "bot",
162
+ type: "data",
163
+ data: { type: 'inventory', productCount: products ? products.length : 0, totalUnits, products: products || [] }
164
+ }]);
165
  setLoading(false);
166
  return;
167
  }
168
 
169
+ // Technical Data Query: Sales
170
+ if (intent === 'SALES') {
171
+ const { data: sales } = await supabase.from('orders').select('*');
 
172
  const totalRev = sales ? sales.reduce((acc, i) => acc + Number(i.total_amount || 0), 0) : 0;
173
  const totalOrders = sales ? sales.length : 0;
174
  const avgOrder = totalOrders > 0 ? (totalRev / totalOrders) : 0;
 
175
 
176
+ setMessages(prev => [...prev, {
177
+ sender: "bot",
178
+ type: "data",
179
+ data: { type: 'sales', totalRev, totalOrders, avgOrder }
180
+ }]);
181
  setLoading(false);
182
  return;
183
  }
184
 
185
+ // 3. Conversational Human Response
186
+ const humanReply = generateConversationalReply(userText, updatedHistory);
187
+ setMessages(prev => [...prev, { sender: "bot", type: "text", text: humanReply }]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
 
189
  } catch (err) {
190
  console.error(err);
191
+ setMessages(prev => [...prev, { sender: "bot", type: "text", text: "Something went wrong processing that. Try asking again!" }]);
 
 
192
  } finally {
193
  setLoading(false);
194
  }
 
199
  <div className="w-64 bg-slate-900 p-4 border-r border-slate-800 flex flex-col justify-between hidden md:flex">
200
  <div>
201
  <h1 className="text-md font-bold text-white mb-2">HealthyLifePhil</h1>
202
+ <p className="text-xs text-slate-400">Natural Chat & Data Engine</p>
 
 
 
203
  </div>
204
  <div className="text-xs text-emerald-400">● Engine Active</div>
205
  </div>
 
217
  </div>
218
  </div>
219
  ))}
220
+ {loading && <div className="text-xs text-emerald-400 italic animate-pulse">Thinking...</div>}
221
  </div>
222
 
223
  <div className="p-4 bg-slate-900 border-t border-slate-800 flex gap-2">
 
229
  onChange={(e) => setInput(e.target.value)}
230
  onKeyDown={(e) => e.key === 'Enter' && handleChat()}
231
  />
232
+ <button onClick={handleChat} disabled={loading} className="bg-emerald-600 hover:bg-emerald-500 px-5 py-2 rounded-lg font-bold text-sm text-black">
233
  Send
234
  </button>
235
  </div>
 
238
  );
239
  }
240
 
 
241
  const rootElement = document.getElementById('root');
242
  const root = ReactDOM.createRoot(rootElement);
243
  root.render(<App />);