import React, { useState, useRef } from 'react'; import { MessageSquare, ShoppingCart, IndianRupee, Cpu, Database, FileSpreadsheet, Bell, ArrowRight, CheckCircle2, Clock, ExternalLink, ShieldCheck, Search, Zap, Layers, Activity, Server, Terminal } from 'lucide-react'; import { apiClient } from './api'; interface Entity { item?: string; qty?: string; customer?: string; amount?: string; } interface AppEvent { id?: string; source: string; icon: React.ReactNode; title: string; message: string; type: string; entity: Entity; timestamp?: string; } interface SheetRow { id?: string; [key: string]: string | undefined; } interface SheetsState { [key: string]: SheetRow[]; } const VyaparFlow = () => { // --- State Management --- const [notifications, setNotifications] = useState([]); const [activeEvent, setActiveEvent] = useState(null); const [backendResult, setBackendResult] = useState(null); const [processingStep, setProcessingStep] = useState(0); // 0: idle, 1: API Request, 2: Reasoning, 3: Completed, 4: Error const [pipelineError, setPipelineError] = useState(null); const [view, setView] = useState('dashboard'); const [activeSheet, setActiveSheet] = useState('Orders'); // Ref to track processing to avoid race conditions const isProcessingRef = useRef(false); // --- Mock Data --- const [sheets, setSheets] = useState({ Orders: [ { id: 'ORD-882', source: 'Amazon', customer: 'Suresh K.', item: 'Kurti (XL)', qty: '2', status: 'Delivered' }, { id: 'ORD-881', source: 'WhatsApp', customer: 'Anjali', item: 'Aata', qty: '5kg', status: 'Paid' }, ], Ledger: [ { customer: 'Rahul Sharma', type: 'Credit', amount: '₹12,400', date: '14 Mar', status: 'Settled' }, { customer: 'Mohit', type: 'Debit', amount: '₹1,200', date: '15 Mar', status: 'Pending' }, ], Inventory: [ { item: 'Aata (Premium)', stock: '142kg', alert: 'Normal' }, { item: 'Silk Kurti', stock: '8', alert: 'Low' }, ] }); // --- Generate Random Notification --- const products = ["Silk Kurti", "Cotton Saree", "Jeans", "T-shirt", "Leather Jacket"]; const groceryItems = ["aata", "chawal", "dal", "cheeni", "tel"]; const customers = ["Rahul", "Amit Kumar", "Suresh", "Pooja", "Neha"]; const sources = ["whatsapp", "gpay", "amazon seller"]; const generateNotification = () => { const source = sources[Math.floor(Math.random() * sources.length)]; if (source === "whatsapp") { const qty = Math.floor(Math.random() * 5) + 1; const item = groceryItems[Math.floor(Math.random() * groceryItems.length)]; return { source: "whatsapp", message: `bhaiya ${qty} kilo ${item} bhej dena kal tak` }; } if (source === "gpay") { const amount = Math.floor(Math.random() * 15000) + 500; const customer = customers[Math.floor(Math.random() * customers.length)]; return { source: "gpay", message: `₹${amount} received from ${customer}` }; } const product = products[Math.floor(Math.random() * products.length)]; const qty = Math.floor(Math.random() * 3) + 1; const total = Math.floor(Math.random() * 3000) + 500; return { source: "amazon seller", message: `Product: ${product}. Qty: ${qty}. Total: ₹${total}` }; }; const handleGenerateNotification = async () => { // Prevent double-click or multiple rapid requests if (isProcessingRef.current) return; isProcessingRef.current = true; try { // Step 1: Generate random notification const notification = generateNotification(); // Step 2: Map source to UI properties const sourceMap: { [key: string]: { icon: React.ReactNode; title: string } } = { 'whatsapp': { icon: , title: 'WhatsApp Order' }, 'gpay': { icon: , title: 'GPay Payment' }, 'amazon seller': { icon: , title: 'Amazon Order' }, }; const sourceProps = sourceMap[notification.source] || { icon: , title: 'New Notification' }; // Step 3: Create AppEvent object const uniqueId = `event-${Date.now()}-${Math.floor(Math.random() * 1000)}`; const newEvent: AppEvent = { id: uniqueId, source: notification.source.charAt(0).toUpperCase() + notification.source.slice(1), icon: sourceProps.icon, title: sourceProps.title, message: notification.message, type: notification.source === 'gpay' ? 'payment' : 'order', entity: {}, timestamp: new Date().toLocaleTimeString() }; // Step 4: Add to UI notifications list setNotifications(prev => [newEvent, ...prev].slice(0, 5)); setActiveEvent(newEvent); setBackendResult(null); setProcessingStep(1); // Stage 1: API Endpoint hit // Step 5: SINGLE API CALL (the ONLY place where backend is triggered) const response = await apiClient.sendNotification({ source: notification.source.toLowerCase(), message: notification.message }); // Step 6: Store backend response setBackendResult(response); setProcessingStep(2); // Stage 2: Reasoning Phase (Nova 2 Lite) // Simulate slight delay for visual feedback await new Promise(r => setTimeout(r, 1000)); setProcessingStep(3); // Stage 3: Skill Execution / Record Completion // Step 7: Update Sheets with the response data setSheets(prev => { const newSheets = { ...prev }; const rowId = `RECORD-${Date.now()}`; // Extract entity info from API response const entityData = response.data || {}; if (response.intent === 'payment') { newSheets.Ledger = [{ id: rowId, customer: entityData.customer || newEvent.entity.customer || 'Unknown', type: 'Credit', amount: entityData.amount || newEvent.entity.amount || '₹0', date: 'Today', status: 'Settled' }, ...prev.Ledger].slice(0, 10); } else { newSheets.Orders = [{ id: `ORD-${Math.floor(Math.random()*900 + 100)}`, source: newEvent.source, customer: entityData.customer || newEvent.entity.customer || 'Unknown', item: entityData.item || newEvent.entity.item || 'Item', qty: entityData.quantity || newEvent.entity.qty || '1', status: 'Confirmed' }, ...prev.Orders].slice(0, 10); } return newSheets; }); } catch (error: any) { console.error('Backend error:', error); const msg = error?.message || 'Both models unavailable'; setPipelineError( msg.includes('quota') || msg.includes('429') ? 'Quota exceeded — wait ~1 min' : msg.includes('unavailable') || msg.includes('500') ? 'Models unavailable — retry shortly' : 'Request failed' ); setProcessingStep(4); // Error state — shows red button } finally { // Reset lock after 5s so user clearly sees the error before re-enabling setTimeout(() => { setProcessingStep(0); setPipelineError(null); isProcessingRef.current = false; }, 5000); } }; return (
{/* SIDEBAR */}
{/* MOBILE SIMULATION PANEL */}

NotiFlow

Live Agent
{/* Device Frame */}
9:41
Signal Stream
{notifications.length === 0 && (

Listening for business events...

)} {notifications.map((notif) => (
{notif.icon}
{notif.source}
Live
{notif.title}

{notif.message}

{activeEvent?.id === notif.id && (
Ingesting...
)}
))}
Connection: Stable
{/* MAIN CONTENT AREA */}
Nova-2-Lite
V-ENGINE-BETA
{view === 'dashboard' ? (

AI Processing Pipeline

Realtime Trace
{!activeEvent ? (

System Polling Underway

NotiFlow is continuously monitoring marketplace APIs and messaging webhooks.

) : (
{/* Step 1 */}
= 1 ? 'bg-white/[0.03] border-indigo-500/30 shadow-2xl' : 'bg-white/[0.01] border-white/5 opacity-40'}`}>
= 1 ? 'bg-indigo-600 text-white' : 'bg-slate-800 text-slate-500'}`}>01
POST /Ingest
Payload Received:
"{activeEvent.message}"
Validation Check {processingStep >= 1 && }
{processingStep === 1 &&
}
{/* Step 2 */}
= 2 ? 'bg-white/[0.03] border-indigo-500/30 shadow-2xl' : 'bg-white/[0.01] border-white/5 opacity-40'}`}>
= 2 ? 'bg-indigo-600 text-white' : 'bg-slate-800 text-slate-500'}`}>02
AI Reasoning
{processingStep === 2 && (
Processing...
)}
Detected Intent
{(backendResult?.intent || activeEvent?.type || 'unknown').replace('_', ' ')} Pattern Matched
Extracted Entities
{Object.entries(backendResult?.data || activeEvent?.entity || {}).map(([k, v]) => ( {k}: {String(v)} ))}
{processingStep === 2 &&
}
{/* Step 3 */}
= 3 ? 'bg-indigo-600/5 border-indigo-500/40 shadow-2xl' : 'bg-white/[0.01] border-white/5 opacity-40'}`}>
= 3 ? 'bg-green-500 text-black' : 'bg-slate-800 text-slate-500'}`}>03
Skills Applied
Record Finalized
DB Synchronization: Success
)}
Global Success Rate 99.2%
Active Connectors 14
Model Performance Ultra-Low Nova-2-L-optimized
) : (

Business Operations Console

Real-time structured business data extracted from the unified signal stream.

{['Orders', 'Ledger', 'Inventory'].map((s) => ( ))}
{sheets[activeSheet] && sheets[activeSheet].length > 0 && Object.keys(sheets[activeSheet][0]).filter(k => k !== 'id').map(key => ( ))} {sheets[activeSheet].map((row, i) => ( {Object.entries(row).filter(([k]) => k !== 'id').map(([key, val = ''], j) => ( ))} ))}
{key}
{val} {i === 0 && j === 0 && Recent}
Auto-sync with VyaparFlow Cloud v1.0.4 - Connection Secure
)}
); }; export default VyaparFlow;