Benna Benna Benna is an AI-powered assistant designed for home food sellers who manage their business through Instagram or WhatsApp chats. Instead of losing orders, forgetting customers, or guessing what sells best, it automatically organizes conversations into structured orders, tracks customers, and gives clear insights about sales, best products, profits, and customer behavior. It helps sellers understand their business, improve marketing, and increase revenue by turning messy chat-based work into a simple, intelligent, and data-driven system .
Lunar Bakery is a business management system designed for bakery operations including:
- 📊 Dashboard Analytics - Real-time KPI tracking and business insights
- 🛍️ Product Management - Create, update, and manage bakery products
- 📦 Order Management - Track and manage customer orders
- 📈 Sales Analytics - Channel performance, profit analysis, and revenue tracking
- 👥 Customer Insights - Repeat customer identification and engagement tracking
- Framework: FastAPI (Python)
- Database: PostgreSQL 15
- ORM: SQLAlchemy 2.0
- Server: Uvicorn
- Database Management: Docker Compose
- Framework: React 19.2
- Build Tool: Vite
- Styling: Tailwind CSS 4.2
- Charts: Recharts 3.8
- HTTP Client: Fetch API with custom wrapper
- Containerization: Docker & Docker Compose
- Version Control: Git
- AI/ML: Google Gemini 2.5 Flash API
- Social Media Integration: Instagram, Facebook
Lunar_Hackathon/
├── backend/
│ ├── main.py # FastAPI app entry point
│ ├── database.py # SQLAlchemy setup
│ ├── tables.py # Database models
│ ├── requirements.txt # Python dependencies
│ ├── docker-compose.yml # PostgreSQL container
│ ├── .env # Environment variables
│ ├── routes/
│ │ ├── kpi_routes.py # Analytics/Dashboard endpoints
│ │ ├── orders_routes.py # Order management endpoints
│ │ └── prodict_routes.py # Product management endpoints
│ ├── schemas/
│ │ ├── order.py # Order Pydantic models
│ │ └── product.py # Product Pydantic models
│ └── services/
│ └── kpi_service.py # KPI calculation logic
│
├── ai-agent/
│ ├── main.py # FastAPI AI agent server
│ ├── agent.py # Gemini AI bot logic & tools
│ ├── schema.py # Request/response schemas
│ └── .env # AI agent environment (GEMINI_API_KEY)
│
├── frontend/
│ ├── src/
│ │ ├── pages/
│ │ │ ├── Dashboard.jsx # Analytics dashboard
│ │ │ ├── OrdersPage.jsx # Order management page
│ │ │ └── ProductsPage.jsx# Product management page
│ │ ├── api/
│ │ │ ├── http.js # HTTP client wrapper
│ │ │ ├── routes.js # API endpoints
│ │ │ ├── orders.js # Orders API service
│ │ │ ├── products.js # Products API service
│ │ │ ├── kpi.js # Analytics API service
│ │ │ └── transform.js # Data transformation utilities
│ │ ├── components/ # React components
│ │ └── App.jsx # Main app component
│ ├── package.json
AI Agent - Social Commerce Integration
The AI Agent is an intelligent order-taking assistant powered by Google Gemini 2.5 Flash that integrates with social media platforms to automate customer interactions, take orders, and manage the customer database.
- Conversational Order Taking - Natural language understanding of customer requests
- Catalog Management - Real-time product catalog retrieval from database
- Customer Verification - Check if customer exists or create new customers
- Order Confirmation - Extract and validate order details before saving
- Upselling & Marketing - AI-generated product recommendations
- Database Integration - Auto-saves customers and orders to PostgreSQL
- Instagram - DM automation & comments parsing
- Facebook - Messenger bot & comment responses
- Order Validation - Confirms all details before database commit
- Smart Upselling - Suggests complementary products based on order
- Customer Tracking - Links orders to customer profiles automatically
- Channel Attribution - Tracks which platform order came from
┌─────────────────────────────────────────────────────┐
│ Social Media Platforms │
│ Instagram | Facebook | WhatsApp | Custom Webhooks │
└────────────────┬────────────────────────────────────┘
│ (User Messages)
▼
┌─────────────────────────────────────────────────────┐
│ AI Agent FastAPI Server (Port 8001) │
│ - Receives messages │
│ - Routes to Gemini AI │
│ - Executes tools (add_customer, save_order, etc) │
│ - Returns bot response │
└────────────────┬────────────────────────────────────┘
│
┌────────┴─────────┬──────────────┐
▼ ▼ ▼
┌────────┐ ┌─────────────┐ ┌──────────┐
│ Gemini │ │ Database │ │ Shared │
│ 2.5 │ │ Repository │ │ Models │
│ Flash │ │ │ │ │
└────────┘ └─────────────┘ └──────────┘
│
Tool Functions:
• add_customer()
• check_customer_exists()
• save_order()
• get_catalog_text()
- Customer: Sends message via Instagram/Facebook/WhatsApp
- AI Agent: Receives message via webhook
- Gemini AI: Analyzes intent and extracts order details
- Tool Execution:
- Verifies customer exists
- Checks product availability
- Validates order
- Database Save: Commits order to PostgreSQL
- Response: Sends confirmation message back to customer
POST /api/orders/chat
Request: { messages: [{role: "user", content: "..."}, ...] }
Response: { reply: "Votre commande est confirmée..." }
GET /
Response: { message: "AI Agent running" }
# Adds new customer to database
# Called when customer first interacts
# Stores: ID, phone, name, created_at# Verifies customer in database
# Prevents duplicate entries
# Links orders to customer profiles3. save_order(client_name, phone_number, product_name, quantity, date, delivery_or_pickup, address, payment_mode)
# Only called after user confirms order
# Validates all fields
# Saves to orders table
# Links to customer and product# Returns real-time product list
# Prevents AI from inventing products
# Formats with prices and namesThe AI is instructed to:
✅ Be warm, friendly, professional
✅ Take orders in natural language
✅ Extract: product, quantity, date, address, payment
✅ Confirm order details before saving
✅ Suggest complementary products
✅ Use only catalog products (NO HALLUCINATION)
✅ Handle French, Arabic, English naturally
✅ Always validate customer exists
✅ Save confirmed orders to database
❌ Don't invent products
❌ Don't make assumptions about pricing
❌ Don't skip order confirmation
- Google Gemini API Key
- Social media platform API credentials (optional)
pip install google-generativeai fastapi uvicorn python-dotenv pydanticCreate ai-agent/.env:
GEMINI_API_KEY=your_gemini_api_key_here
DB_HOST=localhost
DB_PORT=5432
DB_USER=BakeryUser
DB_PASSWORD=lunarbakerypassword123
DB_NAME=lunar_DBcd ai-agent
python main.py
# Or with uvicorn:
# uvicorn main:app --reload --port 8001AI Agent listens on http://localhost:8001
Customer: "Je veux 2 Box Chocolates pour samedi s'il vous plaît"
↓
AI Agent: Extracts:
- product: "Box Chocolates"
- quantity: 2
- order_date: "samedi"
↓
Verification:
✓ Product exists in catalog
✓ Customer exists or gets created
↓
Confirmation:
"Vous voulez 2 Box Chocolates pour samedi?"
↓
Customer: "Oui, confirmer"
↓
save_order() → PostgreSQL
• Customer ID linked
• Product ID matched
• Quantity: 2
• Status: pending
• Channel: "Instagram"
↓
Response: "Commande enregistrée! ID: 5847"
↓
Dashboard: New order appears automatically
↓
Backend Analytics: KPIs update in real-time
When AI Agent saves an order, it automatically:
- ✅ Increases total revenue metrics
- ✅ Updates sales per product
- ✅ Tracks "Instagram" or "Facebook" channel
- ✅ Calculates profit contribution
- ✅ Updates repeat customer metrics
- ✅ Triggers customer engagement analytics
| Feature | Benefit |
|---|---|
| 24/7 Availability | Takes orders anytime, customers don't wait |
| Automatic Database | No manual data entry, no errors |
| Marketing Automation | AI upsells & cross-sells naturally |
| Real-time Analytics | Orders instantly reflect in dashboard |
| Scalable | Handles unlimited concurrent conversations |
| Cost Effective | Reduced need for human support staff |
| Customer Engagement | Regular touchpoints via social media |
Before AI Agent:
- Manual order taking (hours)
- Customer data entry (errors)
- Limited business hours
- No upselling
After AI Agent:
- Instant orders 24/7
- Auto-populated database
- Always available
- Smart recommendations
- Increased revenue per order: +15-25%
---onfig.js │ └── .env # Frontend environment │ ├── shared/ │ ├── database.py # Shared database config │ └── repository.py # Shared data access layer │ └── package.json (monorepo config)
## 🚀 Features
### Dashboard
- **Revenue Metrics** - Total revenue, sales per product, channel performance
- **Order Insights** - Total orders, top-selling products
- **Customer Analytics** - Repeat customer rate, inactive customer tracking
- **Real-time Updates** - Live data from database
### Product Management
- ✅ Create new products
- ✅ Update product pricing (cost & selling price)
- ✅ Calculate profit margins
- ✅ Delete products
- ✅ Automatic profit percentage calculation
### Order Management
- ✅ Create orders manually or via agent
- ✅ Track order status (pending → done → delivered)
- ✅ Manage order quantities and pricing
- ✅ Multiple sales channels (manual & agent)
- ✅ Mark orders as finished with one click
### Analytics & KPIs
- 📊 Total Revenue
- 📊 Sales Per Product
- 📊 Channel Performance (Manual vs Agent)
- 📊 Profit Per Product
- 📊 Top Selling Products
- 📊 Repeat Customer Rate
- 📊 Inactive Customers (14-day window)
## ⚙️ Setup Instructions
### Prerequisites
- **Python 3.10+**
- **Node.js 18+**
- **Docker & Docker Compose**
- **Git**
### 1. Clone Repository
```bash
git clone <repo-url>
cd Lunar_Hackathon
cd backend
docker-compose up -dpip install -r requirements.txtCreate .env file in backend/:
DB_USER=BakeryUser
DB_PASSWORD=lunarbakerypassword123
DB_NAME=lunar_DB
DB_HOST=localhost
DB_PORT=5432uvicorn main:app --reloadBackend will be available at http://localhost:8000
- Swagger Docs:
http://localhost:8000/docs - Health Check:
http://localhost:8000/health
cd frontend
npm installCreate .env file in frontend/:
VITE_API_URL=http://localhost:8000/apinpm run devFrontend will be available at http://localhost:5173
npm run build
npm run previewcd ai-agent
pip install google-generativeai fastapi uvicorn python-dotenv pydantic- Go to Google AI Studio
- Click "Get API Key"
- Create new API key
- Copy the key
Create ai-agent/.env:
GEMINI_API_KEY=your_gemini_api_key_here
DB_HOST=localhost
DB_PORT=5432
DB_USER=BakeryUser
DB_PASSWORD=lunarbakerypassword123
DB_NAME=lunar_DBcd ai-agent
uvicorn main:app --reload --port 8001AI Agent will be available at http://localhost:8001
- Chat API:
POST http://localhost:8001/api/orders/chat
GET /api/dashboard # All KPIs combined
GET /api/dashboard/ui # UI-formatted dashboard
GET /api/revenue/total # Total revenue
GET /api/revenue/by-product # Sales quantity per product
GET /api/revenue/by-channel # Manual vs Agent performance
GET /api/revenue/profit-by-product # Profit per product
GET /api/orders # List all orders
POST /api/orders # Create order
GET /api/orders/{id} # Get order by ID
PATCH /api/orders/{id}/finish # Mark order as done
DELETE /api/orders/{id} # Delete order
GET /api/products # List all products
POST /api/products # Create product
GET /api/products/{id} # Get product by ID
PATCH /api/products/{id} # Update product
DELETE /api/products/{id} # Delete product
GET /api/customers/repeat # Repeat customer stats
GET /api/customers/inactive # Inactive customers (params: days=14)
api/transform.js- Converts between frontend camelCase and backend snake_casetoBackendOrder()- Frontend → Backend formattoFrontendOrder()- Backend → Frontend formattoBackendProduct()- Frontend → Backend formattoFrontendProduct()- Backend → Frontend format
api/orders.js- Order operations with automatic data transformationapi/products.js- Product operations with automatic data transformationapi/kpi.js- Analytics data fetchingapi/http.js- Generic HTTP client with error handling
- id (PK, Auto-increment)
- customer_id (FK → customers)
- product_id (FK → products)
- quantity (Integer)
- price_sold (Float)
- channel (String: 'manual' or 'agent')
- status (Enum: pending, done, delivered, cancelled)
- created_at (DateTime, default: UTC now)
- id (PK, Auto-increment)
- name (String, unique)
- cost_price (Float)
- selling_price (Float)
- id (String, PK)
- name (String, nullable)
- created_at (DateTime, default: UTC now)
# Terminal 1: PostgreSQL & Docker
cd backend
docker-compose up -d
# Terminal 2: Backend API
cd backend
uvicorn main:app --reload
# Terminal 3: AI Agent
cd ai-agent
uvicorn main:app --reload --port 8001
# Terminal 4: Frontend
cd frontend
npm run devBackend: Changes auto-reload with --reload flag
Frontend: Hot Module Replacement (HMR) with Vite
Backend:
- Swagger UI at
http://localhost:8000/docs - Terminal logs
Frontend:
- Browser DevTools
- Vite error overlay
- Terminal output
- Navigate to
http://localhost:8000/docs - Click "Try it out" on any endpoint
- Fill in parameters and execute
curl -X POST http://localhost:8001/api/orders/chat \
-H "Content-Type: application/json" \
-d '{
"messages": [
{"role": "user", "content": "Je voudrais commander 2 croissants pour demain"}
]
}'curl -X POST http://localhost:8000/api/products \
-H "Content-Type: application/json" \
-d '{"name":"Cookie","cost_price":2.0,"selling_price":5.0}'curl http://localhost:8000/api/orderscurl http://localhost:8000/api/dashboardcurl -X POST http://localhost:8001/api/orders/chat \
-H "Content-Type: application/json" \
-d '{
"messages": [
{"role": "user", "content": "Bonjour! Je veux 3 croissants"},
{"role": "assistant", "content": "Bonjour! Vous voulez 3 croissants?"},
{"role": "user", "content": "Oui, pour samedi s'il vous plaît"}
]
}'- fastapi ≥0.110
- uvicorn[standard] ≥0.27
- sqlalchemy ≥2.0
- python-dotenv ≥1.0
- psycopg2-binary ≥2.9
- google-gena ≥0.3.0
- fastapi ≥0.110
- uvicorn[standard] ≥0.27
- python-dotenv ≥1.0
- pydantic ≥2.0
- sqlalchemy ≥2.0
- psycopg2-binary ≥2.9
- react ^19.2.4
- react-dom ^19.2.4
- recharts ^3.8.1
- tailwindcss ^4.2.2
Backend allows requests from:
http://localhost:5173(Vite dev server)http://localhost:3000(Production)
- All timestamps stored in UTC
- Frontend displays in local timezone
- Uses
datetime.utcnow()for server timestamps
- Backend returns 404 for missing resources
- Frontend gracefully handles API errors
- Fallback to mock data if backend unavailable
- React hooks (
useState,useEffect) - Optimistic UI updates for better UX
- Data transformation layer separates concerns
# Build Docker image
docker build -t lunar-backend:latest .
# Deploy with environment variables
heroku config:set DB_HOST=... DB_USER=...
git push heroku main# Build production bundle
npm run build
# Deploy dist/ folder
# Netlify: Connect repo and select build command
# Vercel: Deploy directly or use CLIThis project is part of the Lunar Hackathon 2026.
- Backend Development
- Frontend Development
- Database Design
Last Updated: April 12, 2026 Status: Active Development 🚀