Sarva - Comprehensive Platform Documentation
Table of Contents
- Executive Summary
- Platform Overview
- Core Architecture
- Role-Based Features
- AI-Powered Capabilities
- SEO & AI Discoverability
- API Infrastructure
- Payment & Financial Systems
- Technical Stack
Executive Summary
Sarva is a production-ready, AI-first multi-tenant delivery platform specifically designed for South Asian grocery delivery. The platform bridges cultural identity gaps by providing South Asian communities with access to authentic groceries through modern technology.
Live Platform: https://www.sarvabazaar.com
Service Area: Within 15 miles of Carlisle, PA 17013 (includes Mechanicsburg, Camp Hill, Shippensburg, and surrounding areas)
Key Differentiators
- Multi-role architecture: Customers, Vendors, Drivers, and Guests with isolated authentication
- AI-powered across all roles: 4 dedicated AI chatbots with 90+ language support
- Voice-first design: Whisper STT enables hands-free operations in any language
- Production-grade: Live platform with real transactions, Stripe payments, and Firebase backend
- Cultural focus: Built specifically for South Asian communities and their unique needs
- SEO & AI-optimized: Discoverable by Google, ChatGPT, Claude, and other AI assistants
Platform Statistics
- 4 AI Chatbots: Role-specific conversational assistants
- 7 Specialized AI Tools: Product enrichment, pricing, nutrition, analytics
- 450+ Demo Examples: Comprehensive feature demonstrations
- 90+ Languages Supported: Whisper-powered automatic translation
- Multi-vendor marketplace: Support for unlimited grocery vendors
- Real-time tracking: Live order and delivery status updates
- 12+ FAQs: Comprehensive help center with schema markup
- AI-discoverable: llms.txt, sitemap, structured data for AI systems
Platform Overview
Mission Statement
"These are not just logistics gaps. They are identity gaps. SARVA is our answer."
Sarva was founded during the pandemic from a simple desire to get paan delivered. The platform evolved into a comprehensive solution that:
- Empowers small South Asian vendors with modern AI tools
- Provides customers with access to authentic cultural groceries
- Enables drivers to maximize earnings through intelligent routing
- Eliminates language and technology barriers
Recognition
2025 Starting Dock Finalists - Shippensburg's Entrepreneurial Launchpad
Team
Co-Founders:
- Dipseka Timsina - CEO & Co-founder [LinkedIn] (Environmental Science & Community Research)
- Nishtha Sharma - Chief Data Officer & Co-founder [LinkedIn] (Data Strategy & Ethics)
- Farhan Azim Aurronoy - CFO & Co-founder [LinkedIn] (Finance & Modeling)
Core Team:
- Diwas Timsina - Project Manager [LinkedIn | GitHub] (IBM Professional, Strategic Planning & Operations)
- Shahir Ahmed - Lead Developer [LinkedIn | GitHub] (Full-Stack Architecture, AI Integration & Platform Development)
Core Architecture
Three-Role Authentication System
Sarva implements strict role separation with independent auth systems:
Key Principle: Never mix auth contexts across roles. Each role has:
- Isolated Firebase collections
- Dedicated authentication hooks
- Role-specific API routes with
wrappersecureRoute() - Independent UI components and pages
Firebase Architecture
- Client SDK: Used in browser for real-time updates and auth
- Admin SDK: Used in API routes for secure server-side operations
- Collections:
,users
,vendors
,drivers
,orders
,inventory
,userRolesdriverTransactions - Storage: Firebase Storage for images (products, profiles, nutrition labels)
- Security: AppCheck required in production for all authenticated routes
API Security Pattern
All authenticated routes follow this pattern:
import { secureRoute } from "@/lib/secureRoute";
async function handlePost(
req: NextRequest,
{ user }: { user: DecodedIdToken | null }
) {
if (!user)
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
// Verify role-specific document exists
const vendorSnap = await adminDb.doc(`vendors/${user.uid}`).get();
if (!vendorSnap.exists)
return NextResponse.json(
{ error: "Vendor profile required" },
{ status: 403 }
);
// Handler logic...
}
export const { POST } = secureRoute(
{ POST: handlePost },
{
POST: {
optional: false,
requireAppCheck: process.env.NODE_ENV === "production",
},
}
);Role-Based Features
Customer Features
1. Shopping & Discovery
Product Search
- Natural language product search
- Search by vendor name or location
- Price range filtering (under $X, between $Y-$Z)
- Tag-based browsing (Snacks, Beverages, Spices, Rice, etc.)
- Sort by price, popularity, or newest arrivals
- Product images with detailed descriptions
- Real-time stock availability
Vendor Discovery
- Browse all vendors
- View vendor profiles with business hours
- See vendor locations on map
- Filter by distance and availability
- Vendor-specific product catalogs
Smart Basket Management
- Multi-vendor cart support
- Add items with voice or text commands
- Adjust quantities (increase/decrease)
- Reference items by row number
- Real-time total calculations
- Delivery fee estimation per vendor
2. Order Management
Order Placement
- Seamless checkout flow
- Address autocomplete (Google Places API)
- Multiple saved addresses
- Delivery fee calculation
- Service fees and tax breakdown
- Driver tip configuration (percentage, flat amount, custom)
- Stripe payment integration
- Apple Pay & Google Pay support
Order Tracking
- Real-time order status updates
- Search orders by ID, customer info, status
- Filter by status (delivered, cancelled, active)
- Date range queries (today, this week, custom)
- Amount filtering (over/under specific values)
- Vendor-based filtering
- Line item search (find orders with specific products)
- Sort by date or total amount
Order States
3. Customer Dashboard
Analytics & Insights
- Total orders count
- Total spending breakdown
- Average order value
- Favorite vendors by order count
- Recent order history (5 most recent)
- Spending trends over time
- Top vendors by spending
- Order frequency analysis
Profile Management
- Update display name & phone
- Multiple delivery addresses
- Address autocomplete & validation
- Set primary address
- Profile image upload
- Account settings
Data Export
- Dashboard analytics export (PDF/Excel)
- Complete order history report
- Spending breakdown (subtotal, fees, tips, tax)
- Top vendors analysis
- Favorite items & frequency
- Time-based ordering patterns
- One-click generation from AI chat
4. Customer AI Assistant
Capabilities
- Order tracking with natural queries
- "Show my orders from last week"
- "Find order ABC123"
- "Where's my delivery?"
- Product discovery
- "Find Basmati rice under $20"
- "Show me snacks from Patel Brothers"
- Basket management
- "Add 2 Basmati rice to cart"
- "Remove the first item"
- "What's in my basket?"
- Profile updates
- "Change my address to [new address]"
- "Add phone number 123-456-7890"
- Analytics queries
- "How much did I spend this month?"
- "Export my dashboard to PDF"
- Voice shopping in 90+ languages
- Image upload for product identification
- Context-aware navigation
- Multi-step workflows in one conversation
Vendor Features
1. Multi-Draft Inventory System
Revolutionary Workflow: Manage 20+ inventory items simultaneously
Draft System Architecture
{
currentDrafts: [
{
draftId: "uuid",
workingItemID: "maggi-123" | null, // null = new item, string = edit existing
item: { name, price, cost, units, description, image, tags, nutrition, ... },
status: "complete" | "incomplete",
missing: ["price", "cost"] // Required fields still needed
}
],
activeDraftId: "uuid" // Currently active tab
}Batch Operations - Target drafts by:
- Number (1-based): "save 1 and 3"
- Name: "save Maggi"
- Keywords: "save all", "save completed", "discard incomplete"
Critical Logic:
→ CREATE new itemworkingItemID === null
→ UPDATE existing itemworkingItemID !== null
Operations
- Add multiple items simultaneously
- Edit multiple items in parallel
- Save individual drafts
- Save all completed drafts
- Discard incomplete drafts
- Batch save by name/number
- Batch discard by criteria
- Switch between drafts seamlessly
2. Inventory Management
Core Features
- Product listing with images
- Price and cost tracking
- Stock level management
- Low stock alerts
- Out of stock indicators
- Category & tag management
- Barcode support
- Nutrition information
- Product descriptions
Search & Filtering
- Search by name, description, barcode
- Filter by tags (Snacks, Beverages, etc.)
- Filter by stock level (in stock, low stock, out of stock)
- Filter by profit margin
- Sort by price, sold units, date added, stock level
- Price range filtering
- Multi-criteria advanced search
Inventory Analytics
- Total items count
- Total inventory value
- Low stock items (< 10 units)
- Out of stock items (= 0 units)
- Average price across all products
- Average cost per item
- Average profit margin (%)
- Popular tags ranking
- Total revenue from sold units
- Total profit calculation
- Profit margin percentage
- Most profitable items by margin %
- Best selling items by units sold
- Top revenue generating items
- Top profit generating items
- Restock value estimation
Multi-Select Operations
- Select multiple items with checkboxes
- Select all items
- Batch delete selected items
- Clear selection
- Visual selection indicators
Inventory Health Check (AI-Powered)
- One-click comprehensive analysis
- Stock level assessment
- Profitability insights
- Priority-ranked issues
- Actionable recommendations
- Critical alerts
- Performance benchmarking
3. Vendor Dashboard
Real-Time Metrics
- Total items in inventory
- Current inventory value
- Low stock alerts
- Out of stock count
- Average pricing
- Highest priced item
- Estimated restock cost
- Popular product tags
- Total units sold
- Total revenue generated
- Total profit earned
- Overall profit margin %
- Average profit margin per item
Business Intelligence
- Sales performance charts
- Revenue trends over time
- Top performing products
- Profit analysis by item
- Inventory turnover rates
- Category performance breakdown
- Vendor-specific insights
AI Dashboard Overview (GPT-5)
- Auto-generated executive summary
- Key metrics with sentiment analysis
- Prioritized insights & recommendations
- Early warning alerts
- Strategic suggestions
- Performance benchmarking
- Updates automatically on each dashboard visit
Quick Actions
- Add new inventory item
- View/manage inventory
- Update vendor profile
- View pending orders
- Export business reports
4. Order Management
Order Discovery & Filtering
- Find orders by ID (full or 6-character tail)
- Search by customer name
- Filter by status (preparing, ready, cancelled)
- Filter by date range
- Sort by total amount, date, distance
- Multi-order batch operations
Order Actions
- Mark orders ready (single or batch)
- Cancel orders with automatic restock
- View order details
- Track delivery status
- Customer communication
Order Analytics
- Orders by status breakdown
- Revenue by time period
- Average order value
- Popular items across orders
- Customer order frequency
- Peak ordering times
5. Product Enrichment Suite (4 AI Tools)
AI Description Generator
- Input: Product name
- Output: SEO-optimized description
- Highlights key features and benefits
- Cultural context for South Asian products
- Multiple description variations
Smart Price Suggestions
- Web search across major retailers
- Captures prices from ethnic/specialty stores
- Google Custom Search API integration
- Price range analysis (min, max, median)
- Outlier filtering (> 3x median removed)
- Location-aware pricing (city/state specific)
- Competitive analysis
- Suggested pricing within observed range
- Profit margin recommendations
Nutrition Extraction (Multi-modal)
- Priority 1: User-uploaded nutrition label
- GPT-5 Vision with high detail mode
- Accurate OCR of nutrition facts
- Extracts all visible information
- Priority 2: USDA FoodData Central API
- 400,000+ verified food entries
- Complete nutrition data from database
- Standardized nutritional information
- Priority 3: AI Estimation
- GPT-5 for intelligent estimation
- Based on similar products
- Transparent about estimation method
Auto-Categorization
- AI-powered category suggestions
- Tag recommendations
- Smart product classification
- Cultural product understanding
- Multi-tag support
6. Voice Inventory Management
Capabilities
- Add multiple products with voice
- "Add Maggi price 2.99 cost 1.50 100 units"
- "Add Basmati Rice price 15.99 cost 10 50 units"
- Update multiple items simultaneously
- "Update 1 and 3 to 200 units"
- "Change Maggi price to 3.49"
- Delete operations
- "Delete all incomplete drafts"
- "Remove item 5"
- Batch operations
- "Save all completed drafts"
- "Discard incomplete items"
- 90+ language support via Whisper STT
- Auto-translation to English
- Structured output processing
- Multi-step workflow support
7. Vendor AI Assistant (Multi-Domain)
Inventory Domain
- Add/edit/delete products
- Search inventory
- Update stock levels
- Manage pricing
- Handle nutrition info
Orders Domain
- Find orders by criteria
- Mark orders ready
- Cancel orders
- View order details
- Batch order operations
Analytics Domain
- Query business metrics
- Request performance insights
- Generate reports
- Analyze profitability
- Export data to PDF/Excel
Profile Domain
- Update shop details
- Change business hours
- Modify location
- Update contact information
Advanced Capabilities
- Multi-domain in ONE conversation
- No mode switching required
- Context awareness across domains
- Intelligent navigation suggestions
- Company knowledge integration
- Business intelligence & strategy advice
Business Intelligence Features
- Profitability analysis
- Inventory optimization suggestions
- Sales strategy recommendations
- Customer insights
- Competitive intelligence
- Financial planning advice
- Pricing optimization
- Restock recommendations
Driver Features
1. Order Discovery & Acceptance
Finding Orders
- View all available orders
- Filter by location proximity
- Filter by tip amount (minimum tip)
- Filter by distance (max distance)
- Sort by earnings potential
- Sort by delivery distance
- Sort by total amount
- 6-character quick lookup (tail ID)
- Real-time order updates
Order Details
- Customer name & contact
- Vendor name & location
- Delivery address
- Total order value
- Driver earning (base + tip)
- Distance to pickup
- Distance to delivery
- Number of items
- Special instructions
Acceptance Flow
- Accept orders with voice or text
- View route to vendor
- Get pickup details
- Track order status
- Upload delivery confirmation images
2. Delivery Workflow
Status Progression
Actions at Each Stage
- Accept: Confirm order acceptance
- Pickup: Mark arrived at vendor, picked up items
- Deliver: Mark delivered, upload proof photo
- Navigation: Google Maps/HERE Maps integration
- Communication: Contact customer/vendor
Real-Time Tracking
- GPS location updates
- ETA calculations
- Route optimization suggestions
- Distance tracking
- Time tracking
3. Earnings & Analytics
Live Dashboard Metrics
- Total deliveries completed
- Total earnings (lifetime)
- Total distance driven
- Total items delivered
- Average rating
- Today's earnings
- This week's earnings
- This month's earnings
Performance Metrics (AI-Powered)
- Earnings per Mile: $/mile calculation
- Earnings per Delivery: Average per order
- Average Distance: Miles per delivery
- Items per Delivery: Average item count
- Efficiency Score: 0-100 rating based on performance
- Week-over-Week Trends: Earnings comparison
- Trend Indicators: Up, down, or stable
Analytics Breakdown
- Earnings by date (chart)
- Deliveries by vendor (pie chart)
- Peak earning hours analysis
- Distance efficiency metrics
- Top earning vendors
- Best performing time slots
Export Capabilities
- Driver Report (Full Stats)
- Complete performance metrics
- Earnings breakdown
- Delivery history
- Vehicle information
- Export to PDF/Excel
- Orders Data Export
- Transaction-level details
- Date range filtering
- Earnings per order
- Distance per order
- Export to PDF/Excel
4. AI Insights & Recommendations
Personalized Insights
-
Peak Hour Optimization
- Identifies underutilized time slots
- Suggests 11am-1pm and 6pm-8pm focus
- Shows potential 40% earning increase
-
Earnings Performance
- Compares to platform average ($6.50/delivery)
- Celebrates top performers (>$8/delivery)
- Suggests improvements for lower earners
- Recommends order types for better pay
-
Route Efficiency
- Analyzes average delivery distance
- Suggests proximity-based order acceptance
- Calculates deliveries per hour potential
- Optimizes for fuel efficiency
-
Delivery Frequency Alerts
- Tracks daily delivery activity
- Alerts on 24-hour inactivity
- Provides "Get Back on the Road" prompts
-
Vendor Diversity Tips
- Analyzes vendor distribution
- Recommends expanding vendor network
- Shows potential 60% opportunity increase
-
Streak Recognition
- Tracks consecutive delivery days
- Celebrates 3+ day streaks
- Notes 35% higher earnings for consistent drivers
-
New Driver Guidance
- Progress tracking (0-10 deliveries)
- Unlocks detailed analytics at 10 deliveries
- Shows path to bonus opportunities
Actionable Recommendations
- Each insight includes specific actions
- Links to relevant pages (orders, profile)
- Expected impact estimates
- Difficulty ratings (easy, medium, hard)
5. Driver Dashboard Features
Tabbed Interface
- Overview: Summary metrics, AI insights, recent deliveries
- Earnings: Detailed earnings analysis, payment info, charts
- Deliveries: Complete delivery history, performance stats
- Vehicle: Vehicle information, location settings
Today's Summary Cards
- Today's earnings (live update)
- Account status
- Payment status (Stripe connection)
- Active delivery count
Recent Deliveries List
- Last 10 deliveries
- Vendor and customer names
- Earnings and distance
- Delivery dates
- Quick view details
Vendor Distribution Analysis
- Pie chart of deliveries by vendor
- Percentage breakdown
- Delivery count per vendor
- Recommendations for balance
6. Driver Profile & Settings
Personal Information
- Display name
- Email address
- Phone number
- Alternate phone number
- Profile image upload
- Address
Vehicle Information
- Vehicle make
- Vehicle model
- Vehicle year
- Vehicle color
- License plate number
- Vehicle photo upload
Driver License
- License number
- License expiration date
- License state
- Background check status
Payment Settings
- Stripe account connection
- Payment method setup
- Payout schedule
- Transaction history
- Earnings withdrawal
Location Settings
- Service area
- Current location
- Address autocomplete
- Coordinate validation
7. Driver AI Assistant
Order Management
- "Show available orders with tip over $5"
- "Accept order GR1JAN"
- "Mark order picked up"
- "Mark delivered"
- "Find orders near me"
Earnings Queries
- "How much did I earn this week?"
- "Show my earnings this month"
- "What's my average per delivery?"
- "Show earnings by vendor"
Performance Insights
- "Show me my insights"
- "What are my peak hours?"
- "How can I earn more?"
- "What's my efficiency score?"
Profile Updates
- "Update my vehicle to [make] [model]"
- "Change my address to [new address]"
- "Add license plate [number]"
Voice Commands (Hands-Free)
- Full voice control while driving
- 90+ language support
- Whisper STT auto-translation
- Live waveform visualization
- Safe, eyes-free operation
Guest Features
No Account Required
Guests can shop, checkout, and track orders without creating an account.
1. Product Discovery
Features
- Browse all available products
- Natural language search
- Search by vendor
- Price range filtering
- Tag-based browsing
- Product images & descriptions
- Stock availability display
- Sort options (price, popularity, newest)
AI Assistance
- Voice shopping in 90+ languages
- Image recognition for product ID
- Context-aware suggestions
- Natural conversation flow
2. Guest Basket Management
Capabilities
- Add items to cart
- Adjust quantities
- Remove items
- Multi-vendor support
- Real-time totals
- Reference items by row number
- Clear basket
- View basket summary
AI Commands
- "Find Basmati rice under $20"
- "Add 2 of those to basket"
- "Remove the first item"
- "What's in my basket?"
- "Clear my cart"
3. Guest Checkout
Streamlined Process
- No account creation required
- Enter name, email, phone
- Address input with autocomplete
- Delivery fee calculation
- Service fee breakdown
- Tax calculation
- Driver tip (%, flat, custom)
- Stripe payment (card, Apple Pay, Google Pay)
Order Confirmation
- Receive order ID immediately
- Email confirmation
- SMS updates (optional)
- Track with order ID only
4. Order Tracking (No Login)
Track with Order ID
- Enter order ID to track
- View order status
- See delivery progress
- View line items
- Check delivery ETA
- See driver location (when assigned)
- Contact support
Status Updates
- Real-time status changes
- Preparation updates
- Driver assignment notification
- Out for delivery alert
- Delivery confirmation
5. Guest AI Assistant
Capabilities
- Product search and discovery
- Basket management
- Checkout assistance
- Order tracking
- Voice commands (90+ languages)
- Image upload for product ID
- Context-aware shopping
Example Interactions
- "Find grocery items under $10"
- "Add 3 Maggi noodles"
- "Checkout"
- "Track order ABC123"
- "Where's my delivery?"
AI-Powered Capabilities
Voice & Multimodal Support
Whisper STT Integration
- Speech-to-text in 90+ languages
- Automatic translation to English
- High accuracy transcription
- Live waveform visualization during recording
- Support for all dialects
Supported Languages Include:
- South Asian: Hindi, Urdu, Punjabi, Bengali, Tamil, Telugu, Malayalam, Gujarati, Marathi
- Middle Eastern: Arabic, Farsi, Turkish
- European: Spanish, French, German, Italian, Portuguese
- Asian: Chinese (Mandarin, Cantonese), Japanese, Korean, Vietnamese, Thai
- And 70+ more languages
Image Recognition
- Product photo upload
- Nutrition label OCR (GPT-5 Vision)
- Receipt scanning
- House number recognition
- Delivery confirmation photos
AI Copilot Architecture
AI Copilot Architecture
Context-Aware AI
Memory Across Conversations
- Remembers recent searches
- Tracks basket state
- Maintains order history context
- References previous items
- Multi-step workflow memory
Page-Aware Intelligence
- Knows which page user is on
- Provides relevant suggestions
- Smart navigation offers
- Context-sensitive help
- Seamless page transitions
Natural References
- "Add the first one" (refers to search results)
- "Show me more like that" (similar products)
- "Update row 3" (multi-draft reference)
- "Same as last time" (order history)
GPT-5 Powered Features
Customer Copilot (
/api/customer/copilot)
- Order search & tracking (50+ filter combinations)
- Product discovery with intelligent suggestions
- Basket management
- Profile updates
- Dashboard analytics generation
- Export report creation
- Voice shopping assistance
Vendor Copilot (
/api/voice/inventory)
- Multi-draft inventory management (20+ items)
- Order batch operations
- Business analytics queries
- Product enrichment
- Strategic business advice
- Profit optimization
- Inventory health analysis
Driver Copilot (
/api/driver/copilot)
- Order discovery with smart filtering
- Accept/pickup/deliver commands
- Earnings analysis
- Performance insights
- Route optimization
- Peak hour recommendations
- Report generation
Guest Copilot (
/api/guest/copilot)
- Product search without login
- Basket management
- Guest checkout assistance
- Order tracking by ID
- Voice shopping support
Structured Output Processing
OpenAI Structured Outputs
- Reliable JSON parsing
- Schema validation
- Type-safe responses
- Complex nested structures
- Multi-operation commands
Example: Voice Inventory Command
Input: "Add Maggi price 2.99 cost 1.50, Add Rice price 15"
Structured Output:
{
operations: [
{ action: "add", name: "Maggi", price: 2.99, cost: 1.50 },
{ action: "add", name: "Rice", price: 15, cost: null }
]
}
AI Product Enrichment
Description Generation
- SEO-optimized product descriptions
- Cultural context for South Asian products
- Key features & benefits highlighted
- Multiple variations
- Engaging, conversion-focused copy
Smart Pricing (
/api/ai/pricing)
- Get vendor coordinates from Firestore
- Use Google Geocoding API for location (city, state)
- Search Google Custom Search API (entire web)
- Captures major retailers (Walmart, Amazon, Target)
- Captures ethnic/specialty stores (Patel Brothers, India Bazaar)
- Critical for international products
- Extract prices from Schema.org markup and snippets
- Filter outliers (> 3x median)
- Aggregate results (min, max, median, average)
- OpenAI suggests price within observed range
- Profit margin recommendations
Nutrition Extraction (
/api/ai/nutrition)
- User Upload: GPT-5 Vision OCR on nutrition labels
- USDA Database: 400k+ verified food entries
- AI Estimation: GPT-5 for similar products
- Complete nutritional breakdown
- Serving size information
- Allergen warnings
Auto-Categorization (
/api/ai/categories)
- Intelligent category suggestions
- Multi-tag recommendations
- Cultural product understanding
- Hierarchy-aware classification
AI Dashboard & Analytics
Vendor AI Overview (
/api/vendor/ai-overview)
- GPT-5 powered business summary
- Automatic generation on dashboard load
- Executive summary with sentiment
- Key metrics analysis
- Prioritized insights
- Early warning alerts
- Strategic recommendations
- Performance benchmarking
Driver AI Insights
- Peak hour analysis
- Earnings optimization tips
- Route efficiency suggestions
- Vendor diversity recommendations
- Streak recognition
- Performance trends
- Goal tracking
Multilingual Support
Full Platform Translation
- 90+ languages supported
- Whisper STT auto-translation
- Maintains context across languages
- Cultural nuance preservation
- Dialect support
Use Case Examples:
- Hindi-speaking vendor: "आज के सभी ऑर्डर दिखाओ" → "Show today's orders"
- Spanish-speaking customer: "Buscar arroz basmati" → "Search for Basmati rice"
- Arabic-speaking driver: "قبول الطلب" → "Accept order"
SEO & AI Discoverability
Sarva is optimized for both traditional search engines (Google, Bing) and AI systems (ChatGPT, Claude, Perplexity, etc.).
Google SEO Optimization
Metadata & OpenGraph
- Comprehensive meta tags with 22+ keywords
- OpenGraph for social sharing (Facebook, LinkedIn)
- Twitter Cards for rich previews
- Canonical URLs for all pages
- Multi-language support (en-US primary, hi, ur, pa alternates)
Structured Data (JSON-LD)
{
"@type": "Organization",
"name": "Sarva Bazaar",
"url": "https://www.sarvabazaar.com"
}Four schemas implemented:
- Organization: Company identity and contact info
- WebSite: Site search and navigation
- GroceryStore: Local business with service area (15-mile radius from Carlisle, PA)
- SoftwareApplication: Platform features and ratings
Sitemap & Robots
- Dynamic sitemap at
with all public pages/sitemap.xml - Robots.txt with crawler-specific rules
- Priority and change frequency for each page
- Optimized crawl budget allocation
AI System Discoverability
AI Discovery Files
| File | Purpose | URL |
|---|---|---|
| Concise AI reference | |
| Comprehensive AI documentation | |
| AI plugin discovery | |
Robots.txt AI Rules
User-agent: GPTBot
Allow: /
User-agent: ChatGPT-User
Allow: /
User-agent: Claude-Web
Allow: /
User-agent: Anthropic-AI
Allow: /
User-agent: PerplexityBot
Allow: /FAQ Page
Location:
/faq
- 12+ frequently asked questions
- FAQPage schema markup for Google rich snippets
- Covers: delivery area, products, ordering, payments, vendors, drivers
- Direct links from all copilots
Sample FAQs:
- Where does Sarva deliver? (15-mile radius of Carlisle, PA 17013)
- What products do you offer? (200+ South Asian grocery items)
- Do I need an account to order? (No, guest checkout supported)
- How do I become a vendor/driver?
- What payment methods are accepted?
Page-Specific Metadata
Each major page has optimized metadata:
| Page | Title | Description |
|---|---|---|
| Home | Sarva Bazaar - South Asian Grocery Delivery | Shop authentic groceries |
| Order | Track Your Order | Real-time order status |
| FAQ | FAQ - Help Center | Common questions answered |
| Demo | AI Features Demo | Interactive feature showcase |
| About | About Sarva | Platform mission and team |
| Vendor Signup | Become a Vendor | Join the marketplace |
| Driver Signup | Become a Driver | Earn with deliveries |
PWA Support
Manifest:
/manifest.json
- App name and icons
- Theme colors (orange brand)
- Standalone display mode
- App shortcuts
API Infrastructure
Authentication & Security
API Route Security (
/lib/secureRoute.ts, /lib/withAuth.ts)
export const { POST } = secureRoute(
{ POST: handlePost },
{
POST: {
optional: false, // Require authentication
requireAppCheck: process.env.NODE_ENV === "production", // AppCheck in production
},
}
);Firebase Admin (Server-Side)
for token validationadminAuth.verifyIdToken()
for Firestore operationsadminDb
for file operationsadminStorage- Service account credentials
- Server timestamps with
FieldValue.serverTimestamp()
AppCheck Integration
- reCAPTCHA Enterprise in production
header validationX-Firebase-AppCheck- Prevents abuse and bot traffic
- Required for all authenticated routes
API Endpoints
Customer APIs
Order Management
- Create new orderPOST /api/orders/create
- Verify Stripe paymentPOST /api/orders/confirm-payment
- Fetch customer ordersGET /api/orders
Product Discovery
- Search products with filtersPOST /api/search/items
- Fetch all inventory itemsGET /api/inventory
Profile
- Get customer dataGET /api/customer/profile
- Update customer profilePUT /api/customer/profile
Analytics Export
- Export dashboard (PDF/Excel)POST /api/customer/export-dashboard
- Export order history (PDF/Excel)POST /api/customer/export-orders
AI Copilot
- Customer AI assistantPOST /api/customer/copilot
Vendor APIs
Inventory Management
- Fetch vendor inventoryGET /api/vendor/inventory
- Add inventory itemPOST /api/vendor/inventory
- Update itemPUT /api/vendor/inventory/:id
- Delete itemDELETE /api/vendor/inventory/:id
- Delete multiple itemsPOST /api/vendor/inventory/batch-delete
Order Management
- Fetch vendor ordersGET /api/vendor/orders
- Mark order readyPOST /api/orders/vendor/mark-ready
- Cancel order with restockPOST /api/orders/vendor/cancel
AI Features
- Generate product descriptionPOST /api/ai/description
- Get smart price suggestionsPOST /api/ai/pricing
- Extract nutrition infoPOST /api/ai/nutrition
- Auto-categorize productPOST /api/ai/categories
- Generate dashboard summaryPOST /api/vendor/ai-overview
Analytics
- Export business report (PDF/Excel)POST /api/vendor/export-report
Voice Interface
- Voice commands for inventoryPOST /api/voice/inventory
- Whisper STT translationPOST /api/stt/translate
Driver APIs
Order Discovery
- Fetch available ordersGET /api/driver/orders
- Fetch driver's ordersGET /api/driver/my-orders
Order Actions
- Accept orderPOST /api/orders/driver/accept
- Mark picked upPOST /api/orders/driver/pickup
- Mark deliveredPOST /api/orders/driver/deliver
Analytics
- Get driver statisticsGET /api/driver/stats
- Calculate earningsGET /api/driver/earnings
- Export orders (PDF/Excel)POST /api/driver/export-orders
- Export driver report (PDF/Excel)POST /api/driver/export-report
AI Copilot
- Driver AI assistantPOST /api/driver/copilot
Guest APIs
Shopping
- Search products (no auth)POST /api/search/items
- Manage guest basketPOST /api/guest/basket
- Guest checkoutPOST /api/guest/checkout
Order Tracking
- Track order by IDGET /api/guest/order/:orderId
AI Copilot
- Guest AI assistantPOST /api/guest/copilot
Payment APIs
Stripe Integration
- Create Stripe paymentPOST /api/create-payment-intent
- Verify payment statusPOST /api/orders/confirm-payment
Vendor Onboarding
- Create Stripe Connect accountPOST /api/onboard-express-account
- Vendor Stripe setupPOST /api/signup/create-stripe-account
- Verify account statusPOST /api/signup/verify-stripe-account
- Fetch account infoGET /api/signup/get-stripe-account-data
- Disconnect StripePOST /api/signup/disconnect-stripe-account
- Handle onboarding returnGET /api/onboard-return
Driver Payouts
- Automatic payout processing
- Earnings calculation
- Transaction history
- Payout schedule management
Location APIs
Address Services
- Google Places AutocompleteGET /api/address-autocomplete
- Calculate distance & timePOST /api/distance-matrix
- Get route directionsPOST /api/directions
- HERE Maps fallbackGET /api/map-fallback
Admin APIs
Vendor Approval
- Approve vendor applicationPOST /api/admin/approve-vendor
- Send notificationsPOST /api/admin/send-admin-notification
Authentication APIs
Identity Verification
- Create Stripe Identity sessionPOST /api/signup/create-id-session
- Verify identity sessionGET /api/signup/verify-id-session
Cloud Functions (Firebase)
Deployed Functions (
/functions/src/)
Order Mirroring
- Copy order to public collection on createmirrorOrderCreated
- Update public order on changesmirrorOrderUpdated
- Remove from public collection on deletemirrorOrderDeleted
Cleanup Functions
- Remove stale vendor inventory drafts (7+ days old)cleanupDrafts
- Delete expired pending orders (30+ minutes)purgeStalePendingOrders
Purpose:
- Maintain data consistency
- Optimize query performance
- Clean up abandoned operations
- Reduce storage costs
Payment & Financial Systems
Stripe Integration
Customer Payments
- Payment intents for order checkout
- Card payments (Visa, Mastercard, Amex, Discover)
- Apple Pay & Google Pay
- 3D Secure authentication
- Automatic receipt generation
- Payment verification
- Refund processing
Vendor Payouts (Stripe Connect Express)
- Vendor onboarding flow
- Identity verification (Stripe Identity)
- Bank account linking
- Automatic payout calculations
- Platform fee deduction
- Instant and scheduled payouts
- Transaction history
- Tax reporting (1099)
Driver Payouts
- Earnings calculation
- Automatic payout processing
- Transaction tracking
- Payout history
- Tax documentation
Financial Flow
Order Transaction
- Customer pays via Stripe Payment Intent
- Platform holds funds
- Order is prepared and ready
- Driver accepts and delivers
- Vendor receives payout (order total - platform fee)
- Driver receives payout (delivery fee + tip)
- Platform retains service fee
Fee Structure
- Platform Fee: Percentage of order subtotal
- Service Fee: Fixed per-order fee for customers
- Delivery Fee: Distance-based calculation
- Driver Tip: Customer-defined (%, flat, or custom)
Payout Timing
- Vendors: Upon order completion
- Drivers: Upon delivery confirmation
- Automatic processing via Stripe Connect
- Instant payout option available
Payment Security
PCI Compliance
- Stripe handles all card data
- No card info stored on servers
- PCI DSS Level 1 certified (via Stripe)
- Tokenized payments
- Encrypted transmission
Fraud Prevention
- Stripe Radar for fraud detection
- 3D Secure authentication
- Address verification (AVS)
- CVV verification
- Unusual activity monitoring
Secure Transactions
- AppCheck verification
- Firebase Auth tokens
- Server-side validation
- Idempotency keys
- Audit logging
Technical Stack
System Architecture Overview
Frontend
- Framework: Next.js 15 (App Router)
- Language: TypeScript (strict mode)
- Styling: Tailwind CSS
- UI Components: Custom components, Headless UI
- State Management: React Context API
- Forms: React Hook Form
- Charts: Recharts
- Maps: Google Maps API, HERE Maps (fallback)
- Icons: Lucide React, Heroicons
- Analytics: Vercel Analytics
- Notifications: React Hot Toast
Backend
- Runtime: Node.js
- API Framework: Next.js API Routes
- Language: TypeScript
- Authentication: Firebase Auth (3 separate auth contexts)
- Database: Firestore (NoSQL)
- Storage: Firebase Storage
- Cloud Functions: Firebase Cloud Functions (Node.js)
- Security: AppCheck (reCAPTCHA Enterprise)
AI & ML
- LLM: OpenAI GPT-5
- Vision: GPT-5 Vision
- Speech-to-Text: OpenAI Whisper
- Structured Outputs: OpenAI JSON mode
- Embeddings: (for future semantic search)
External APIs & Services
- Payments: Stripe (Payment Intents, Connect, Identity)
- Maps: Google Maps API (Places, Distance Matrix, Directions, Geocoding)
- Maps Fallback: HERE Maps API
- Search: Google Custom Search API (for pricing)
- Nutrition: USDA FoodData Central API
- Email: (Future: SendGrid/Resend)
- SMS: (Future: Twilio)
Development Tools
- Package Manager: npm
- Linting: ESLint
- Formatting: Prettier (optional)
- Version Control: Git
- Deployment: Vercel
- Environment: dotenv for local development
Infrastructure
- Hosting: Vercel (frontend & API routes)
- Functions: Firebase Cloud Functions
- Database: Firestore (multi-region)
- Storage: Firebase Storage (multi-region)
- CDN: Vercel Edge Network
- SSL: Automatic (Vercel)
- Domain: Custom domain (sarvabazaar.com)
Monitoring & Analytics
- Application: Vercel Analytics
- Errors: Console logging (Future: Sentry)
- Performance: Web Vitals tracking
- User Analytics: (Future: Google Analytics/Mixpanel)
Data Models
User Collections
// users (customers)
{
uid: string;
email: string;
displayName: string;
phoneNumber: string;
location: string;
coordinates: { lat: number; lng: number };
profileImage?: string;
order_ids: string[];
created_at: Timestamp;
updated_at: Timestamp;
}
// vendors
{
uid: string;
email: string;
displayName: string;
phoneNumber: string;
shopName: string;
location: string;
coordinates: { lat: number; lng: number };
businessDescription: string;
profileImage?: string;
inventory: string[]; // item IDs
stripeAccountId: string;
stripeOnboardingComplete: boolean;
approved: boolean;
created_at: Timestamp;
updated_at: Timestamp;
}
// drivers
{
uid: string;
email: string;
displayName: string;
phoneNumber: string;
alternatePhoneNumber?: string;
location: string;
address: string;
coordinates: { lat: number; lng: number };
vehicleInfo: {
make: string;
model: string;
year: number;
color: string;
licensePlate: string;
};
driverLicense: {
number: string;
state: string;
expirationDate: string;
};
stats: {
totalDeliveries: number;
totalEarnings: number;
totalDistance: number;
totalItems: number;
averageRating: number;
};
deliveryIds: string[];
stripeAccountId: string;
stripeOnboardingComplete: boolean;
created_at: Timestamp;
updated_at: Timestamp;
}Product & Order Models
// inventory
{
itemID: string;
vendorID: string;
name: string;
name_lc: string; // lowercase for search
description: string;
price: number;
cost: number;
units: number;
soldUnits: number;
image: string;
tags: string[];
tags_lc: string[]; // lowercase array
barcode?: string;
nutrition?: {
servingSize: string;
calories: number;
fat: number;
carbs: number;
protein: number;
// ... more fields
};
created_at: Timestamp;
updated_at: Timestamp;
created_at_ts: number; // epoch seconds for range filters
created_at_date: string; // YYYY-MM-DD for day faceting
}
// orders
{
orderID: string;
customerID: string;
customerName: string;
vendorID: string;
vendorName: string;
driverID?: string;
driverName?: string;
status: "pending" | "preparing" | "ready" | "in_transit" | "delivered" | "cancelled";
items: Array<{
itemID: string;
name: string;
price: number;
quantity: number;
}>;
amount: {
subtotal: number;
deliveryFee: number;
serviceFee: number;
driverTip: number;
tax: number;
total: number;
};
deliveryInfo: {
address: string;
coordinates: { lat: number; lng: number };
distance: number; // meters
duration: number; // minutes
};
paymentIntent: string;
created_at: Timestamp;
accepted_at?: Timestamp;
preparing_at?: Timestamp;
ready_at?: Timestamp;
picked_up_at?: Timestamp;
delivered_at?: Timestamp;
cancelled_at?: Timestamp;
}Search & Indexing
Firestore Indexing
- Composite indexes for complex queries
- Single-field indexes for sorting
- Indexes defined in
firestore.indexes.json
Search Fields (Lowercase Variants)
→name
for case-insensitive searchname_lc
→tags
for tag filteringtags_lc
→created_at
for range queriescreated_at_ts
Future Enhancements
- Algolia for advanced search
- Elasticsearch for full-text search
- Vector embeddings for semantic search
Key Differentiators
1. Multi-Role AI Architecture
Unlike single-user-type platforms, Sarva has 4 dedicated AI copilots with role-specific capabilities:
- Customer: Shopping & order management
- Vendor: Multi-draft inventory & business intelligence
- Driver: Earnings optimization & route planning
- Guest: No-account shopping experience
2. Multi-Draft Inventory System
Industry-First: Manage 20+ inventory items simultaneously
- Parallel editing of multiple products
- Draft-based workflow
- Batch operations (save/discard by name/number/keyword)
- Status tracking (complete/incomplete)
- Missing field indicators
3. Voice-First Design
90+ Languages Supported via Whisper STT
- Hands-free operations for vendors and drivers
- Automatic translation to English
- Cultural language support (Hindi, Urdu, Punjabi, Arabic, etc.)
- Voice commands for all major operations
4. AI Product Enrichment
4-Tool Suite for vendors:
- Description generation (GPT-5)
- Smart pricing (web search + AI analysis)
- Nutrition extraction (Vision OCR + USDA + AI estimation)
- Auto-categorization
5. Context-Aware AI
Persistent Memory Across Conversations
- Remembers searches and basket state
- References previous items
- Multi-step workflows in single conversation
- Page-aware suggestions
6. Production-Grade Implementation
Live Platform with real transactions:
- Stripe payments (customers, vendors, drivers)
- Firebase infrastructure (scale-ready)
- AppCheck security (production-hardened)
- Cloud Functions (automated operations)
7. Cultural Focus
Built for South Asian Communities:
- Ethnic product understanding
- Cultural context in descriptions
- Multilingual support (Hindi, Urdu, etc.)
- South Asian vendor network
- Traditional product categories
8. Guest Experience
Shop Without Account:
- Full shopping experience
- Product search and discovery
- Guest checkout
- Order tracking by ID only
- No forced registration
9. Driver Intelligence
AI-Powered Earnings Optimization:
- Peak hour recommendations
- Route efficiency analysis
- Earnings per mile calculations
- Performance benchmarking
- Personalized insights
10. Multimodal Inputs
Text, Voice, and Images:
- Type or speak commands
- Upload product photos
- Scan nutrition labels
- Attach Excel files
- Delivery confirmation photos
Future Roadmap
Planned Features
AI Enhancements
- Fine-tuned models for specific use cases
- Predictive inventory management
- Demand forecasting
- Customer preference learning
- Automated reorder suggestions
Platform Expansion
- Additional vendor categories (beyond groceries)
- Multi-city launch strategy
- Franchise model for vendors
- White-label solutions
Technical Improvements
- Algolia/Elasticsearch integration
- Real-time chat (vendor-customer, driver-customer)
- Push notifications (web & mobile)
Progressive Web App (PWA)✅ Implemented- Mobile apps (iOS, Android)
Business Features
- Loyalty programs
- Subscription plans (customers)
- Bulk ordering
- Corporate accounts
- Gift cards & vouchers
Analytics & Reporting
- Advanced business intelligence
- Market trend analysis
- Competitive benchmarking
- Customer lifetime value tracking
Conclusion
Sarva represents a comprehensive, AI-first approach to solving real-world challenges in ethnic grocery delivery. By combining cutting-edge AI technology with cultural sensitivity and practical business needs, Sarva creates value for all participants: customers gain convenient access to authentic groceries, vendors receive powerful tools to compete in the digital marketplace, and drivers maximize earnings through intelligent optimization.
The platform's production-ready status, multi-role architecture, and voice-first design position it uniquely in the market. With 450+ demo examples, 90+ language support, and live transactions, Sarva demonstrates that AI can be both powerful and accessible across diverse user bases.
Live Platform: https://www.sarvabazaar.com
Documentation: This file
Contact: customercontact@sarvabazaar.com
Last Updated: December 2025
Version: 1.1
