Skip to content

eyahammar/Lunar_Hackathon

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

27 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🌙 Benna Benna Benna Hackathon Project

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 .

📋 Project Overview

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

🏗️ Tech Stack

Backend

  • Framework: FastAPI (Python)
  • Database: PostgreSQL 15
  • ORM: SQLAlchemy 2.0
  • Server: Uvicorn
  • Database Management: Docker Compose

Frontend

  • Framework: React 19.2
  • Build Tool: Vite
  • Styling: Tailwind CSS 4.2
  • Charts: Recharts 3.8
  • HTTP Client: Fetch API with custom wrapper

Infrastructure

  • Containerization: Docker & Docker Compose
  • Version Control: Git
  • AI/ML: Google Gemini 2.5 Flash API
  • Social Media Integration: Instagram, Facebook

📁 Project Structure

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.

Features

🎯 Core Capabilities

  • 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

📱 Social Media Integration

  • Instagram - DM automation & comments parsing
  • Facebook - Messenger bot & comment responses

💡 Business Logic

  • 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

AI Agent Architecture

┌─────────────────────────────────────────────────────┐
│          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()

Conversation Flow

  1. Customer: Sends message via Instagram/Facebook/WhatsApp
  2. AI Agent: Receives message via webhook
  3. Gemini AI: Analyzes intent and extracts order details
  4. Tool Execution:
    • Verifies customer exists
    • Checks product availability
    • Validates order
  5. Database Save: Commits order to PostgreSQL
  6. Response: Sends confirmation message back to customer

API Endpoints

POST  /api/orders/chat
      Request: { messages: [{role: "user", content: "..."}, ...] }
      Response: { reply: "Votre commande est confirmée..." }

GET   /
      Response: { message: "AI Agent running" }

Tool Functions (AI Capabilities)

1. add_customer(phone_number, name)

# Adds new customer to database
# Called when customer first interacts
# Stores: ID, phone, name, created_at

2. check_customer_exists(phone_number)

# Verifies customer in database
# Prevents duplicate entries
# Links orders to customer profiles

3. 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

4. get_catalog_text()

# Returns real-time product list
# Prevents AI from inventing products
# Formats with prices and names

System Prompt (Simplified View)

The 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

Setup AI Agent

Prerequisites

  • Google Gemini API Key
  • Social media platform API credentials (optional)

Install Dependencies

pip install google-generativeai fastapi uvicorn python-dotenv pydantic

Configure Environment

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_DB

Run AI Agent

cd ai-agent
python main.py
# Or with uvicorn:
# uvicorn main:app --reload --port 8001

AI Agent listens on http://localhost:8001

Data Flow: Customer → Order → Database

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

KPI Impact from AI Orders

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

Advantages

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

Example Dashboard Impact

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

2. Backend Setup

Start PostgreSQL

cd backend
docker-compose up -d

Install Python Dependencies

pip install -r requirements.txt

Configure Environment

Create .env file in backend/:

DB_USER=BakeryUser
DB_PASSWORD=lunarbakerypassword123
DB_NAME=lunar_DB
DB_HOST=localhost
DB_PORT=5432

Run Backend

uvicorn main:app --reload

Backend will be available at http://localhost:8000

  • Swagger Docs: http://localhost:8000/docs
  • Health Check: http://localhost:8000/health

3. Frontend Setup

cd frontend
npm install

Configure Environment

Create .env file in frontend/:

VITE_API_URL=http://localhost:8000/api

Run Frontend (Development)

npm run dev

Frontend will be available at http://localhost:5173

Build for Production

npm run build
npm run preview

4. AI Agent Setup

Install AI Package

cd ai-agent
pip install google-generativeai fastapi uvicorn python-dotenv pydantic

Get Google Gemini API Key

  1. Go to Google AI Studio
  2. Click "Get API Key"
  3. Create new API key
  4. Copy the key

Configure Environment

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_DB

Run AI Agent

cd ai-agent
uvicorn main:app --reload --port 8001

AI Agent will be available at http://localhost:8001

  • Chat API: POST http://localhost:8001/api/orders/chat

📡 API Endpoints

Dashboard

GET  /api/dashboard              # All KPIs combined
GET  /api/dashboard/ui           # UI-formatted dashboard

Revenue KPIs

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

Orders

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

Products

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

Customers

GET  /api/customers/repeat       # Repeat customer stats
GET  /api/customers/inactive     # Inactive customers (params: days=14)

🔄 Frontend-Backend Integration

Data Transformation Layer

  • api/transform.js - Converts between frontend camelCase and backend snake_case
    • toBackendOrder() - Frontend → Backend format
    • toFrontendOrder() - Backend → Frontend format
    • toBackendProduct() - Frontend → Backend format
    • toFrontendProduct() - Backend → Frontend format

API Service Layer

  • api/orders.js - Order operations with automatic data transformation
  • api/products.js - Product operations with automatic data transformation
  • api/kpi.js - Analytics data fetching
  • api/http.js - Generic HTTP client with error handling

💾 Database Models

Order Table

- 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)

Product Table

- id (PK, Auto-increment)
- name (String, unique)
- cost_price (Float)
- selling_price (Float)

Customer Table

- id (String, PK)
- name (String, nullable)
- created_at (DateTime, default: UTC now)

🛠️ Development Workflow

Starting Everything

# 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 dev

Making Changes

Backend: Changes auto-reload with --reload flag Frontend: Hot Module Replacement (HMR) with Vite

Debugging

Backend:

  • Swagger UI at http://localhost:8000/docs
  • Terminal logs

Frontend:

  • Browser DevTools
  • Vite error overlay
  • Terminal output

🧪 Testing Endpoints

Using Swagger UI

  1. Navigate to http://localhost:8000/docs
  2. Click "Try it out" on any endpoint
  3. Fill in parameters and execute

Testing AI Agent Chat

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"}
    ]
  }'

Using cURL

Backend - Create a product

curl -X POST http://localhost:8000/api/products \
  -H "Content-Type: application/json" \
  -d '{"name":"Cookie","cost_price":2.0,"selling_price":5.0}'

Backend - Get all orders

curl http://localhost:8000/api/orders

Backend - Get dashboard KPIs

curl http://localhost:8000/api/dashboard

AI Agent - Multi-turn conversation

curl -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"}
    ]
  }'

📚 Dependencies

Backend (backend/requirements.txt)

  • fastapi ≥0.110
  • uvicorn[standard] ≥0.27
  • sqlalchemy ≥2.0
  • python-dotenv ≥1.0
  • psycopg2-binary ≥2.9

AI Agent

  • 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

Frontend (package.json)

  • react ^19.2.4
  • react-dom ^19.2.4
  • recharts ^3.8.1
  • tailwindcss ^4.2.2

📝 Key Implementation Details

CORS Configuration

Backend allows requests from:

  • http://localhost:5173 (Vite dev server)
  • http://localhost:3000 (Production)

Date Handling

  • All timestamps stored in UTC
  • Frontend displays in local timezone
  • Uses datetime.utcnow() for server timestamps

Error Handling

  • Backend returns 404 for missing resources
  • Frontend gracefully handles API errors
  • Fallback to mock data if backend unavailable

State Management

  • React hooks (useState, useEffect)
  • Optimistic UI updates for better UX
  • Data transformation layer separates concerns

🚢 Deployment

Backend (Heroku/PaaS)

# Build Docker image
docker build -t lunar-backend:latest .

# Deploy with environment variables
heroku config:set DB_HOST=... DB_USER=...
git push heroku main

Frontend (Netlify/Vercel)

# Build production bundle
npm run build

# Deploy dist/ folder
# Netlify: Connect repo and select build command
# Vercel: Deploy directly or use CLI

📄 License

This project is part of the Lunar Hackathon 2026.

👥 Contributors

  • Backend Development
  • Frontend Development
  • Database Design

Last Updated: April 12, 2026 Status: Active Development 🚀

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors